Skip to content
Advertisement

Unexpected behaviour of Threads

I am trying to achieve that thread2 should complete first, then thread1, For this O am using join() method. But if I uncomment the System.out.println() present in the try block of thread1 class. then code give null pointer exception. Why in try block I need to add line, it doesn’t make any sense that adding a line code start working.

Demo class

JavaScript

Thread1 class

JavaScript

Thread2 class

JavaScript

OUTPUT of the program

JavaScript

Advertisement

Answer

It is working purely by “pure luck” the

JavaScript

internally calls synchronized, which is working as a delay that gives enough time for Thread 2 its field fetcher in:

JavaScript

In order to avoid this race-condition you need to ensure that the Thread 2 sets the field fetcher before Thread 1 accesses it. For that you case use, among others, a CyclicBarrier.

??A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.** CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

First, create a barrier for the number of threads that will be calling it, namely 2 threads:

JavaScript

With the CyclicBarrier you can then force Thread 1 to wait for Thread 2 before accessing its field fetcher:

JavaScript

Thread 2 also calls the barrier after having setting up the field fetcher, accordingly:

JavaScript

Both threads will continue their work as soon as both have called the barrier.

An example:

JavaScript

If your code is not for education purposes, and you are not force to use any particular synchronization mechanism for learning purposes. In the current context you can simply pass the thread 2 as parameter of the thread 1, and call join directly on it as follows:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement