Junior — Middle
Can you name alternative ways to implement thread synchronization similar to synchronized?
sobes.tech AI
Answer from AI
In Java, besides the synchronized keyword, there are alternative ways to synchronize threads:
-
The
ReentrantLockclass from thejava.util.concurrent.lockspackage — a more flexible locking mechanism with the ability to attempt to acquire the lock and with a timeout. -
Using
volatileto ensure visibility of variable changes between threads (does not guarantee atomicity). -
Classes from the
java.util.concurrentpackage, such asSemaphore,CountDownLatch,CyclicBarrier— for more complex thread coordination. -
Methods
wait(),notify(),notifyAll()for thread interaction via object monitors.
Example with ReentrantLock:
import java.util.concurrent.locks.ReentrantLock;
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}