How does join() work? (Multithreading in Java)

pkluz picture pkluz · Feb 4, 2011 · Viewed 7.8k times · Source

I'm preparing for an exam and after going over some sample exercises (which have the correct answers included), I simply cannot make any sense out of them.

The question

(Multiple Choice): What are the some of the possible outcomes for the program below?

A) Value is 1. Value is 1. Final value is 1.

B) Value is 1. Value is 1. Final value is 2.

C) Value is 1. Final value is 1. Value is 2.

D) Value is 1. Final value is 2. Value is 2.

The Program

public class Thread2 extends Thread {

    static int value = 0;
    static Object mySyncObject = new Object();

    void increment() {

        int tmp = value + 1;
        value = tmp;

    }

    public void run() {

        synchronized(mySyncObject) {

            increment();
            System.out.print("Value is " + value);

        }

    }

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread2();
        Thread t2 = new Thread2();

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.print("Final value is " + value);

    }

}

The correct answers are: A), C) and D).

For case A) I don't understand how it's possible that both threads (after incrementing a seemingly static variable from within a synchronized block(!)) end up being set to 1 and the final value is thus 1 as well...?

Case C and D are equally confusing to me because I really don't understand how it's possible that main() finishes before both of the required threads (t1 and t2) do. I mean, their join() methods have been called from within the main function, so to my understanding the main function should be required to wait until both t1 and t2 are done with their run() method (and thus have their values printed)...??

It'd be awesome if someone could guide me through this.

Thanks in advance, much appreciated! wasabi

Answer

Erick Robertson picture Erick Robertson · Feb 4, 2011

There is something wrong with the answers or the question.

Your understanding of join() is correct. The "Final value is" message cannot be printed until both threads have completed. The calls to join() ensures this.

Furthermore, the increment() method is only called from within a synchronized block keyed on a static field. So there's no way this method could be called simultaneously by two threads. The "Value is" output is also within the same synchronized block. So there's no access to the value property from anywhere except within the synchronized block. Therefore, these operations are thread-safe.

The only possible output from this program is "Value is 1. Value is 2. Final value is 2." (In reality, there are no periods or spaces between the outputs - I'm just matching the format of the answers.)

I cannot explain why this matches none of the answers except that whoever wrote the question messed something up.