Junior — Middle
How can access control be implemented among multiple threads for shared resources?
sobes.tech AI
Answer from AI
To manage access to shared resources among multiple threads in Java, synchronization mechanisms are used to prevent race conditions and ensure data correctness.
Main methods:
synchronizedkeyword — blocks access to a method or code block, allowing only one thread to execute it at a time.
public synchronized void increment() {
counter++;
}
- Classes from the
java.util.concurrent.lockspackage, such asReentrantLock, which provide more flexible control over locks.
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
-
Use of atomic classes (
AtomicInteger,AtomicReference), which provide atomic operations without explicit locks. -
Semaphores, barriers, and other synchronization primitives for more complex scenarios.
The choice of a specific mechanism depends on the task, performance requirements, and synchronization complexity.