What methods of thread synchronization do you know in Java?
sobes.tech AI
Answer from AI
In Java, there are several ways to synchronize threads:
-
The synchronized keyword — locks methods or blocks of code to ensure mutual exclusion.
-
Lock objects from java.util.concurrent.locks — a more flexible locking mechanism, such as ReentrantLock, allowing attempts to acquire the lock with a timeout, checking the lock state, etc.
-
Volatile — guarantees visibility of variable changes between threads but does not ensure atomicity.
-
Atomic classes (AtomicInteger, AtomicReference, etc.) — provide atomic operations without locks.
-
Semaphores — limit the number of threads executing a certain section of code simultaneously.
-
CountDownLatch, CyclicBarrier — for thread coordination, waiting for events.
-
Concurrent collections (ConcurrentHashMap, ConcurrentLinkedQueue, etc.) — provide thread-safe access without external synchronization.
Example of using synchronized:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
The choice of method depends on the task: for simple mutual exclusion, synchronized is suitable; for more complex scenarios, Lock or atomic classes are preferable.