Junior — Middle
Can you explain how to use locking mechanisms when working with multithreading?
sobes.tech AI
Answer from AI
In Java, various locking mechanisms are used for multithreading, which allow synchronizing access to shared resources and prevent race conditions.
Main methods:
- synchronized — a keyword that can be applied to methods or code blocks. It provides exclusive access to an monitor object.
public synchronized void increment() {
counter++;
}
- java.util.concurrent.locks.Lock — an interface that offers more flexible locking capabilities than synchronized. For example, you can explicitly acquire and release the lock.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
Lock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}
- ReadWriteLock — allows separating locks for reading and writing, which increases performance when there are many read operations.
Using locks helps avoid issues with concurrent access, such as race conditions and deadlocks, if the order of lock acquisition is managed correctly and they are released in a finally block.