This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: In programmingThey are atomic.What does that mean?

In Effective Java, it says:

The language specification guarantees that read and write variables are atomic, unless the variable is of type long or double [JLS, 17.4.7].

What exactly does the word atom mean in Java coding?

Answer a

Here’s an example, because an example is often clearer than a lengthy explanation. Suppose foo is a variable of type long. The following line is not atomic:

foo = 65465498L;
Copy the code

In fact, the variable is written using two separate operations: one for the first 32 bits and one for the last 32 bits. This means that another thread might read the value of Foo and look at the intermediate state.

Atomizing an operation involves using a synchronization mechanism to ensure that the operation is treated as a single atomic (that is, non-divisible into parts) operation from any other thread. This means that any other thread, once the operation is atomic, will either see the value of Foo before the assignment or after the assignment. But you will never see its value during the assignment.

An easy way to do this is to make variables variable:

private volatile long foo;
Copy the code

Or use the synchronize modifier for variables

public synchronized void setFoo(long value) {
    this.foo = value;
}

public synchronized long getFoo(a) {
    return this.foo;
}
// no other use of foo outside of these two methods, unless also synchronized
Copy the code

Or replace the variable type with AtomicLong:

private AtomicLong foo;
Copy the code

Answer two

If you have multiple threads executing M1 and M2 in the code below

class SomeClass {
    private int i = 0;

    public void m1(a) { i = 5; }
    public int m2(a) { returni; }}Copy the code

You can guarantee that any thread that calls M2 will read 0 or 5.

On the other hand, use the following code (where I is of type long) :

class SomeClass {
    private long i = 0;

    public void m1(a) { i = 1234567890L; }
    public long m2(a) { returni; }}Copy the code

A thread calling M2 can read 0, 1234567890L, or some other random value because the statement I =1234567890L is not guaranteed to be atomic for long periods of time (the JVM can write the first and last 32 bits in two operations, and the thread may observe I between the two operations).

The article translated from Stack Overflow:stackoverflow.com/questions/1…