Local database reading edition
Identify Atomic and Non-Atomic Operations
Reconstructed from database records, not a captured original forum layout. Dates and display names are retained as recorded; timezone and real-world identity are not inferred. Historical advice, contact details and offers are not current. Original markup is shown as inert text.
Forum index · Java - Tips Of The Day
Opening post
Asha · 2001-04-06 14:09:18
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:
<pre id=code><font face=courier size=2 id=code>
public class ThreadSafe
{
private int x;
public void setX(int x)
{
this.x = x;
}
}</font id=code></pre id=code>
However, we should be careful to note that the guarentee applies only to reading and writing. For eg. check the following code snippet:
<pre id=code><font face=courier size=2 id=code>
public void increment()
{
++this.value;
}</font id=code></pre id=code>
Although the above code looks to be atomic operation, it is not. The above instruction actually consists of three instructions:
<i>
1) Read current setting of 'value'.
2) Increment the setting.
3) Write the new setting back.
</i>
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:
<i>
1) Threading bugs are difficult to detect and are time consuming.
2) This code might translate into a single instruction on some CPUs and thus work correctly. The problem might arise when tested with other JVMs.
</i>
The above code can be made threadsafe by simply synchronizing the code as follows:
<pre id=code><font face=courier size=2 id=code>
public synchronized void increment()
{
++this.value;
}</font id=code></pre id=code>
Asha Balasubramanyan
http://www.ammu.org
Source notes
MyCommunity/nandighosha.org.zip!/forum/tools/snitz_forums_2000.mdb
Table: FORUM_TOPICS + FORUM_REPLY · record IDs: 79