The synchronization concept is divided into three categories.
- Exclusive locking: enabling only one thread to execute a critical code part. syncronized, Mutix, Spinlock and Lock belong to this category.
- Non-exclusive locking: limiting the concurrency by allowing certain threads(reader threads, writer threads,…etc) to access the critical fields or code sections. the semaphores and the reentrant read-write locks belong to this category.
- Signaling: this is the wait-notify concept in java where a thread can halt until receiving a signal from the other threads.
synchronized method
Executing a thread-safe execution by locking the instance or the class
synchronized block
Executing a thread-safe execution by locking the object
reentrant lock and reentrant read-write lock
private final Lock lock = new ReentrantLock(isFair); | |
// usage: | |
try{ | |
lock.lock(); | |
// Do some stuff | |
} finally{ | |
lock.unlock(); | |
} |
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); | |
protected final Lock readLock = readWriteLock.readLock(); | |
protected final Lock writeLock = readWriteLock.writeLock(); | |
// usage – same idea as before! |
Mutex
Mutix is like a lock, The difference that it is cross-process and slower. You can name a mutex and acquire it or release it by its name via the same thread from anywhere.
try { mutex.acquire(); try { // do something } finally { mutex.release(); } } catch(InterruptedException ie) { // ... } |
Signaling Wait-Notify
Part of the Object type.
Semaphore
Used in niche scenarios. won’t elaborate on it.