0

As per my knowledge in Java class with

  1. Non static synchronize method : lock acquire on particular object
  2. Static synchronize method : lock acquire on class

I am little bit confuse with this, since we can call the static method by class name OR by object name.

Please assume there are 4 methods is my class all are synchronized. 2 methods are static and 2 are not static. If I create 1 object of my class "obj1" and there are 2 threads Thread1 and Thread2 as well

Question 1: if I will try to access the static synchronized method, using the obj1 (or class name), does it mean there is no lock on "obj1", only 2 static methods will be locked (class level lock)? Does this mean another thread can access non-static method, but not the static method using the "obj1" simultaneously?

Question 2: if I will try to access the non-static synchronized method using the obj1 in Thread1, does it mean only 2 methods are locked for Thread2? Does this mean Thread2 can access 2 static methods, OR we can access the static method using the className(MyClass) as well simultaneously?

Question 3: if all the methods in my class are static and synchronized, does it mean there will be no object level lock and there is only one class level lock for all threads?

Please explain little bit about the class level lock.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rakesh Soni
  • 10,135
  • 5
  • 44
  • 51

1 Answers1

12

Even if you call a static method with

someObject.staticMethod()

It doesn't change the fact that the lock is on the Class object. It just means that you're calling static methods in a confusing way and you should call it properly. Just because it works perfectly well, doesn't mean it should be used (unless you intend to make your code less readable).

There's nothing special about the class level lock. It just uses the Class object instead of the instance, and since all static synchronization uses the same Class object, it works like it does.

As for your last question, yes. If you have only static synchronized methods, they will all share the Class object as their lock, no matter how many instances of the class you have created.

Kayaman
  • 72,141
  • 5
  • 83
  • 121