Lock at the class level

In order to protect static data, locking at the class level can be achieved by marking a static method/block or acquiring a lock on the .class reference with synchronized. In the following examples, only one thread of one of the available instances at runtime will be allowed to execute the synchronized block at a time:

  • synchronized static method:
public class ClassCll {

public synchronized static void methodCll() {
...
}
}
  • Synchronized block and lock on .class:
public class ClassCll {

public void method() {
synchronized(ClassCll.class) {
...
}
}
}
  • Synchronized block of code and lock on some other static object:
public class ClassCll {

private final static Object aLock = new Object();

public void method() {
synchronized(aLock) {
...
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.34.25