1

I'm little confused about behaviour for synhronization (static and non static method).

For example:

1.

    class MyClass  {
  ...
  public synchronized static someMethod() {
    ...
  }
  public static someMethod2() {
    ...
  }

  ...
}

So if thread A call someMethod1(), does thread B have lock on someMethod2()?

2.

     class MyClass  {
  ...
  public synchronized someMethod() {
    ...
  }
  public someMethod2() {
    ...
  }

  ...
}

If we have MyClass a = new MyClass(),thread A call method someMethod(),does thread have lock on someMethod2()?

0

3 Answers 3

1

The answer to both is no. Synchronization is a cooperative mechanism. Synchronizing on an instance or class doesn't prevent other threads from calling another method unless that method also synchronizes on the same monitor.

Sign up to request clarification or add additional context in comments.

Comments

0

In both of your questions the answer is No: thread B won't be locked on method someMethod2 since this method is not synchronized. Synchronization and related locks will be working only when both threads will call someMethod.

The only difference in this case is the target that will be locked. A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods)

2 Comments

Synchronization doesn't block invocation of unsynchronized methods.
Thanks, modified the answer. I didnt understand the question correctly
0

No, another method is free to lock in these cases. A thread can get a lock for the static method when another thread lock non static method of the class. These methods have different monitors.

When a static method is synchronized it's synchronize on a class. That means while execution of a static method the whole class is blocked. So other static synchronized methods are also blocked. In other case when a not static method is synchronized it's synchronize on an instance. All synchronized methods of only this specific object are blocked.

1 Comment

But the other method is not synchronized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.