Object level lock
Only one thread will be able to execute the code block on given instance of the class.
Use synchronized method
public class MyClass {
public synchronized void method1(){}
}
or - Use synchronized block with this reference
public class MyClass {
public void method1(){
synchronized (this) {
// thread safe code
}
}
}
or - Use synchronize block with other object
public class MyClass {
private final Object lock = new Object();
public void method1(){
synchronized (lock) {
// thread safe code
}
}
}
Class level lock
It prevents multiple threads to enter in synchronized block in any of all available instances.
Only one thread will be able to execute the method/block in any one of instance at a time, and all other instances will be locked for other threads.
Use synchronized + static method
public class MyClass {
public synchronized static void method1(){}
}
or - Use synchronized block with Class type
public class MyClass {
public void method1(){
synchronized (MyClass.class) {
// thread safe code
}
}
}
or - Use synchronized block with other static object
public class MyClass {
private final static Object lock = new Object();
public void method1(){
synchronized (lock) {
// thread safe code
}
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.