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:
It is also worth looking at:
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.