0

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.

joyinside
  • 127
  • 1
  • 2
  • 8

1 Answers1

3

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

Community
  • 1
  • 1
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
  • Sorry for my mistake. I just changed Test.class to Test.this. Does it still mean they are not synchronized? – joyinside Feb 13 '12 at 04:37
  • @so-ju no, in that case they *are* synchronized, since they are locking the same object. – The Scrum Meister Feb 13 '12 at 04:42
  • So, you are saying that synchronized blocks or synchronized methods called inside the listener thread are synchronized with such methods called outside of the listener thread? – joyinside Feb 13 '12 at 04:51
  • 1
    Read this : http://docs.oracle.com/javase/tutorial/essential/concurrency/ It will make everything much more clear. – Alex Calugarescu Feb 13 '12 at 04:55