简体   繁体   中英

AtomicBoolean where is the lock?

AtomicBoolean uses native code for synchronization. How does it translate into java locks?

what's the difference between:

AtomicBoolean a = new AtomicBoolean();
synchronized (a) {
   a.set(true);
}

vs:

a.set(true)

I know the synchronized(a) is not needed because a itself will ensure the operation is atomic. But is the lock in synchronized (a) the same lock as in a.set(true) ?

The atomic relies on the JVM for some if the atomicity, such as in set/get, but relies on the sun.misc.Unsafe class in other cases. You can check out the code at:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/atomic/AtomicBoolean.java

It is also worth looking at:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/misc/Unsafe.java#Unsafe

which is used for lots of stuff in the JDK, although sadly it is not a public class. Made more sad because it is so obviously named that it could be public and completely "safe" to use ;-)

I should add, the whole idea of the atomic classes is to avoid locks and synchronization, which will often improve performance. You do not need to use locks to protect them, but may rely on operations like compareAndSwap or incrementAndGet (for numbers) that are not standard when you use a lock.

AtomicBoolean ,事实上,所有的原子类 ,使用比较并交换 ,以保证atomicitiy。

this:

a.set(true);

isn't internally synchronized at all , have a look at the code of AtomicBoolean.java in JDK 1.7 (from src.zip):

/**
 * Unconditionally sets to the given value.
 *
 * @param newValue the new value
 */
public final void set(boolean newValue) {
    value = newValue ? 1 : 0;
}

so, yes, it is different to the synchronized version

Synchronization keyword provide three guarantees according to JMM. 1. Atomicity 2. Visibility 3. Reordering

but synchronization is blocking in nature.

All the Atomic Classes in java like AtomicInteger, AtomicLong, AtomicBoolean etc also provide the above three guarantees. But they dont block other threads.

They Provide 1. Atomicity - by using compareAndSwap operation. 2. Visibility and Reordering - these are provide by declaring the underlying variable as volatile.

for example in AtomicInteger the underlying int variable is declared as volatile

private volatile int value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM