jdk1.5 - thread concurrency library - java.util.concurrent.atomic

 

 

Search for the keyword Atomic in the JDK API documentation

 

eg: AtomicInteger AtomicIntegerArray etc. Please refer to API for details

 

It should be noted that these classes provided by jdk are only encapsulated atomic operation classes provided for multi-threaded operation of member variables.

If it is a local variable under multiple threads , this class is not needed

 

 

J2SE 5.0 provides a set of atomic classes to help us simplify synchronization. The basic working principle is to use the synchronized method to implement the addition, subtraction, assignment (update) operation of a long, integer, object.

 

In java multi-threading usage - use AtomicInteger for a brief comparison:

class Counter {
private volatile int count = 0;


public synchronized void increment() {
count++; //To execute count++ thread-safely, you need to lock
}


public int getCount() {
return count;
}
}


class Counter {
private AtomicInteger count = new AtomicInteger();


public void increment() {
count.incrementAndGet();
}
       //After using AtomicInteger, thread safety can be achieved without locking.
public int getCount() {
return count.get();
}
}

 

Counting program counts during high concurrent access is definitely thread-unsafe without locking .

AtomicInteger can achieve as much without chaos, and can handle high concurrency with ease, because the hardware provides atomic operation instructions to achieve,

Compared with the locking operation of the first writing method, the latter has less overhead and faster speed in the case of no fierce competition.

 

The atomic operation classes implemented in java.util.concurrent include:

AtomicBoolean、AtomicInteger、AtomicLong、AtomicReference。
 
 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486325&siteId=291194637