Question

From Niko's java blog

These classes are defined in the same file. What is the output? (1 correct answer)

class Job extends Thread {
    private Integer number = 0;
    public void run() {
        for (int i = 1; i < 1000000; i++) {
            number++;
        }
    }
    public Integer getNumber() {
        return number;
    }
}
public class Test {
    public static void main(String[] args) 
    throws InterruptedException {
        Job thread = new Job();
        thread.start();
        synchronized (thread) {
            thread.wait();
        }
        System.out.println(thread.getNumber());
    }
}
  • It prints 0.
  • It prints 999999.
  • The output is not guaranteed to be any of the above.

The output is 999999. I understand that when a Thread completes its run() method, it terminates and with it, all the locks the Thread had get released. However, in this exercise, it's used the Thread object as a lock, should not it be considered as a normal object? I mean the lock it's not owned by the Thread thread but by the main Thread.

Was it helpful?

Solution

This code relies on an implementation detail that was not documented before Java 7, and now is (in the documentation of the join() method), but with the following words:

As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

So I don't know where this question was asked, but it really tests if you know the hidden corner-cases of threading, that you should never use in any sane program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top