Singleton Objects and Thread Synchronization

April 11, 2018

Question: What happens when a singleton object that is used for thread synchronization is set to point to a new instance?

Answer: The example code below introduces a race condition scenario. The Main class creates 1000 sets of 1000 threads. Half of the threads (500 threads) execute runnableA, invoking MyObject.doSomething("ThreadA", 100) to increment the counter. The other half execute runnableB, which invokes MyObject.reinitialize() to set a new object to the lock variable within the synchronized block.

Since threads can execute concurrently, there is a possibility that a thread executing runnableA acquires the lock before another thread executing runnableB, causing the counter to be incremented in a synchronized manner. However, if a thread executing runnableB acquires the lock first and reassigns a new object to lock within the synchronized block, the threads executing runnableA will no longer synchronize on the same lock object, potentially leading to a race condition.

Running the code multiple times may produce varying results. In some runs, a race condition may occur, resulting in the counter value being different from the expected 150,000.

Home