Trade offs between using Java's built in concurency mechanism versus Utilities provided in java.util.concurrent
What are the trade offs between usi开发者_如何学Pythonng Java's built in concurency mechanism versus utilities (like ReentrantLocks for example) provided in java.util.concurrent
There are two main differences:
- The
java.util.concurrent
classes represent a higher level of abstraction and tested implementations of specific concepts. You could implement most or all of those concepts using just synchronization, but it would be more code, more work, and much, much more error-prone. - Some of those classes are based on atomic hardware operations (compare and set) instead of sychronization, which performs better than sychronization under heavy (but not extreme) contention.
These come to mind:
The "synchronized" feature is a language construct and has special flow control for entering and exiting blocks whereas the "util.concurrent" must obey the rules of any other object. This will incur some cognitive load for programmers.
The "util.concurrent" interfaces and implementations can define their own unique behaviors (such as fairness, or separate read/write locks) so there is room for improved performance in specific situations.
The "util.concurrent.atomic" classes can provide hardware-level support for compare-and-swap instructions which enable lock-free and wait-free algorithms which can be have better performance in some applications.
Advantages of synchronized
:
- Obviously, using a simply
synchronized
block (or method) is easier from the syntax side, and you can't forget theunlock()
step.
Advantages of Lock
:
With explicit
Lock
objects, on the other hand, you can have non-nested protected blocks - like when iterating over a linked list, you may always want to lock the next list element and only after this unlock the previous one.A Lock object allows blocking non-interruptible, blocking interruptible and non-blocking acquiring of a lock, while a synchronized block only allows the blocking non-interruptible one.
There are other Lock implementations allowing different locking strategies (like ReadWriteLock).
There are no tradeoffs, only pitfalls.
Almost no one uses wait(), notify() and notifyAll() to implement concurrency control, unless they are writing some construct not available in java.util.concurrent. It is very hard to get right, even for Doug Lea (author of Concurrent Programming in Java and JSR-166 spec lead).
Synchronized works for simple cases, but does not give the needed granularity (multiple reader, single writer locks are something not supported by synchronized alone, although you could use it to implement semaphores and then implement RW locks, but you would be reinventing the wheel).
精彩评论