java syncronized, lock, atomicXXX

Tags:

“Minkoo Seo” wrote in message

news:1127735094.563923.46420@g43g2000cwa.googlegroups.com…

> Here’s my question. As some of you might already knows,
> JDK 5.0 added some new synchronization constructs like
> ReentrantLock, Semaphore, and AtomicInteger. Before
> them, ‘synchronized’ was the only keyword available. And it
> automatically inserts memory barrier which make it possible to
> thread-safe programs in SMP. However, it is not obvious whether
> those new constructs are thread safe or not. So, please tell me.
> Are those constructs insert memory barriers as the synchronized
> keyword does?

For Lock implementations like ReentrantLock the memory semantics are clearly
documented: see the heading “Memory Synchronization” in the Lock javadocs.
All Lock implementations must behave in a simila fashion to monitor
acquisition and release.

For Atomics the memory synchronization semantics are documented on the
package.html page for java.util.concurrent.atomic. Basically atomic
variables act like volatile variables.

For synchronizers like Semaphore the memory semantics are not currently
documented, but will be in Java 6. Basically “acquire” operations like
Semaphore.acquire have acquire semantics, and release operations like
Semaphore.release have release semantics.

The j.u.c classes are not built on-top of the built-in language
synchronization features – like synchronized methods, or use of
Object.wait()/notify(). Atomics are intrinsified by the VM (for the basic
atomic classes); the lock implementations are built on top of atomics, and
use of the LockSupport.park/unpark API for blocking; other classes are then
built on top of locks and/or use atomics themselves. Most of the
synchronizer classes build on AbstractQueuedSynchronizer which uses atomics
and LockSupport.

The built-in synchronized mechanism generally (pre Java 6 anyway) performs
better in the uncontended case as a lot of effort has gone into making
uncontended synchronization as cheap as possible in the VM. However,
implementations like ReentrantLock perform much better under contention. A
Semaphore used as a mutual exclusion lock should perform similarly to
ReentrantLock – or marginally better as it is built from the same mechanism
but doesn’t have to support reentrant acquisition.

You generally don’t find a lot of good information about Java concurrency in
comp.programming.threads. If you are really interested then look at the
concurrency-interest mailing list:
http://gee.cs.oswego.edu/dl/concurrency-interest/

David Holmes

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *