Synchronized
static volatile Boolean running = false; |
Synchronized method
synchronized void incrementSync() { |
Synchronized block
void incrementSync() { |
Internally Java uses a so called monitor also known as monitor lock or intrinsic lock in order to manage synchronization. This monitor is bound to an object, e.g. when using synchronized methods each method share the same monitor of the corresponding object.
All implicit monitors implement the reentrant characteristics. Reentrant means that locks are bound to the current thread. A thread can safely acquire the same lock multiple times without running into deadlocks (e.g. a synchronized method calls another synchronized method on the same object).
Lock
private static boolean running = false; |
- ReentrantLock
- ReadWriteLock
- StampedLock
Semaphore
In addition to locks the Concurrency API also supports counting semaphores. Whereas locks usually grant exclusive access to variables or resources, a semaphore is capable of maintaining whole sets of permits. This is useful in different scenarios where you have to limit the amount concurrent access to certain parts of your application.
private Semaphore semaphore = new Semaphore(1); |
Synchronized
allows only one thread of execution to access the resource at the same time. Semaphore
allows up to n (you get to choose n) threads of execution to access the resource at the same time.
Queue
private final int CPU_COUNT = 4; |
Read more