In Java, the reading and writing of 32-bit or smaller quantities are guaranteed to be atomic. By atomic we mean each action takes place in one step and cannot be interrupted. Thus, when we have multithreaded applications, the read and write operations are thread-safe and need not be made synchronized.
For example, the following code is thread safe:
public class ThreadSafe
private int x;
public void setX(int x)
this.x = x;
However, we should be careful to note that the guarentee applies only to reading and writing. For eg. check the following code snippet:
public void increment()
Although the above snippet looks to be atomic operation, it is not. The above instruction actually consists of three instructions:
1) Read current setting of 'value'.
2) Increment the setting.
3) Write the new setting back.
Thus, the above code is not thread-safe. To add to the problem, this mistake is not very easily caught during testing due to two reasons:
1) Threading bugs are difficult to detect and are time consuming.
2) This code snippet might translate into a single instruction on some CPUs and thus work correctly. The problem might arise when tested with other JVMs.
The above code can be made threadsafe by simply synchronizing the code as follows:
public synchronized void increment()