Synchronised Method Only Execute Once A Class
A class can only execute 1 synchronised method at a time. This is because the synchronised
method is synchronising the this
keyword
package org.example.chapter2;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SynchronisedClass {
public synchronized void synchroniseMethod() {
System.out.println("Synchronised method acquired " + Thread.currentThread().getName());
try {
Thread.sleep(10000); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Synchronised method called by " + Thread.currentThread().getName());
}
public synchronized void synchroniseMethod2() {
System.out.println("Synchronised method 2 acquired " + Thread.currentThread().getName());
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Synchronised method 2 called by " + Thread.currentThread().getName());
}
public static void main(String[] args) {
SynchronisedClass synchronisedClass = new SynchronisedClass();
CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
try {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(() -> {
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
synchronisedClass.synchroniseMethod2();
});
executorService.submit(() -> {
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
synchronisedClass.synchroniseMethod();
});
executorService.shutdown();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
In this example, if synchroniseMethod
acquire the lock first, it will take 10 seconds to release the lock before synchroniseMethod2
get called. This can lead to poor performance if we use this keyword.