Reputation: 137
I have a quick question about Java synchronization.
Please assume the following code:
public class Test {
private String address;
private int age;
public synchronized setAddress(String a) {
address = a;
}
public synchronized setAge(int a) {
age = a;
}
public synchronized void start() {
...
listener = new Thread(new Runnable(){
public void run() {
...
setAge(10);
...
synchronized(Test.this) {
address = null;
}
}
}
}
}
I am a little bit unsure about Java synchronization when synchronized method or synchronized block is called inside another thread.
Assume the thread running class Test as A, and the listener thread B.
Then if I execute the code above, does it guarantee that synchronized method calls and synchronized block are synchronized with the A (the thread running Test class) ?
Thank you for reading.
Upvotes: 0
Views: 904
Reputation: 30131
No,
The synchronized methods are locking the Test
instance, while the synchronized block is locking the Test
class object.
See Java synchronized static methods: lock on object or class and Java Synchronized Block for .class
Upvotes: 3