- The use of synchronized methods or statements provides lock acquisition and release to occur in a block-structured way.
- Lock interface enables lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.
The Lock interface provides more extensive locking operations than it's possible to obtain via synchronized methods and statements
methods:
- void lock()
- void lockInterruptibly()
- Condition newCondition()
- boolean tryLock()
- boolean tryLock(long time, TimeUnit unit)
- void unlock()
- ReentrantLock(boolean fair) - creates a reentrant lock with the given fairness policy. Passing true to fair results in a lock that uses a fair ordering policy, which means that under contention, the lock favors granting access to the longest-waiting thread.
- int getHoldCount()
- boolean isFair()
- boolean isHeldByCurrentThread()
Condition: Where Lock replaces synchronized methods and statements, Condition replaces Object monitor methods.
additionaly having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations.
Atomic variables
- Contended synchronization is expensive and throughput suffers as a result.A major reason for the expense is the frequent context switching that takes place; a context switch operation can take many processor cycles to complete.
- volatile variables only solve the visibility problem
java.util.concurrent.atomic offers classes for Boolean (AtomicBoolean), integer (AtomicInteger), long integer (AtomicLong) and reference (AtomicReference) types.
-----------------
- Java Synchronization protects data corruption on race conditions.
- spin lock (Busy wait) - overhead.
- Sleep lock - Context switching overhead.
- re-entrant mutual exclusion lock that extends the built-in monitor lock capabilities.
- Low overhead than ReentrantReadWriteLock
- improves performance when resource more often read than write.
- Provides more parallelism on multi core or multi processor hardware
- A non-negative integer that controls the access of multiple threads to a limited number of shared resources.
- Block thread until some conditions becomes true.
- Allow one or more thread to wait until s set of operation being performed in other threads complete.
ConditionObject(uses sleep locks) & Semaphore(uses busy waiting) big overhead than ReentrantLock&ReentrantReadWriteLock
Semaphore & ConditionObject are flexible and provides more capability.
------------------
reference ( javaworld )
No comments:
Post a Comment