Unsynchronized code in Java

We have two threads that execute the sequences below, without any synchronization:

x = y = 0
Thread 1 Thread 2
x = 1
j = y
y = 1
i = x

Is it possible for both i and j to be 0 if print is called in another thread?

Sadly the answer is YES! If the code is unsynchronized and you don’t use volatile variables the compiler is free to optimize this code, it can even reorder the instructions. Even if the compiler does not reorder the instructions, it is very possible that the x=1 or y=1 assignments are done in the local caches only and are not visible to the other threads until later on.

The moral of this story?

Unsynchronized code may seem intuitive but it is not! Because of hardware and implementation details the code is totally unpredictable. Always synchronize your multi-threaded code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s