Junior — Middle
What methods and tools are used in Java to implement thread synchronization?
sobes.tech AI
Answer from AI
In Java, several main methods and tools are used for thread synchronization:
-
The
synchronizedkeyword — allows making a block of code or a method a critical section, ensuring that only one thread executes this code at a time. -
Objects from the
java.util.concurrentpackage:ReentrantLock— a more flexible alternative tosynchronizedwith the ability to attempt lock acquisition, timeouts, etc.Semaphore,CountDownLatch,CyclicBarrier— for more complex thread coordination.
-
Classes for atomic operations from
java.util.concurrent.atomic(e.g.,AtomicInteger) — allow performing operations without locks. -
Volatile variables — guarantee visibility of variable changes between threads, but do not ensure atomicity.
Example of using synchronized:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
This code guarantees that increment and read operations on the counter are thread-safe.