Critical Section
A critical section is a sequence of instructions that only one thread at a time should be allowed to execute. We can protect critical sections using some sort of a lock which gives us a guarantee of mutual exclusion, where only one thread gets exclusive access.
Link to original
synchronized keyword
If we declare a method or block with the keyword synchronized, the JVM will ensure only thread will ever enter that method or block at a time.
public class SynchronisedDemo implements Runnable {
private int counter = 0;
private synchronized void increment() {
// only one thread can enter this method
counter++;
}
@Override
public void run() {
// call increment() 1000 times
}
}
var demo = new SynchronisedDemo();
Thread t1 = new Thread(demo);
Thread t2 = new Thread(demo);
t1.start();
t2.start();
// demo.counter must be 2000Locks
Lock
A lock is a construct that enables the programmer to declare a critical section that can only be accessed by one thread at a time. Before entering the section, the thread attempts to acquire the lock. When exiting, the lock is released.
Link to original
Locks in Java
Every Java object has an intrinsic lock, when we define a critical section it is also defined in respect to particular objects which are also locked. This means other threads will not be able to enter any synchronised method in that object.
A method-level lock is not always necessary as it may capture objects which need not be locked during the operation.
// locks this and amount
private synchronized void addToCounter(int amount) {
if (amount >= 0) {
counter += amount;
}
}
// locks this only
private void addToCounter(int amount) {
if (amount >= 0) {
synchronized(this) {
counter += amount;
}
}
}