Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why synchronized static method and synchronized non static method never block each other

 
vvus bharadwaj
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we have a instance variable then that variable is accessed by both static synchronized method using an instance and that same instance variable is accessed by non static synchronized instance method.If one thread1 calls the static synchronized method and thread2 calls the non static synchronized method then there is a threat to instance variable.Is my assumption right?
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vvus bharadwaj wrote:If we have a instance variable then that variable is accessed by both static synchronized method using an instance and that same instance variable is accessed by non static synchronized instance method.If one thread1 calls the static synchronized method and thread2 calls the non static synchronized method then there is a threat to instance variable.Is my assumption right?



when a thread enters a synchronized non-static method it acquires lock of the object on which method was called. whereas in case of static methods , thread acquires lock on object of the class Class associated with your particular class. which means that thread A can enter non-static method and another thread B can enter static method and can run concurrently. however as you have said, static synchronized method can access instance variable. now if this instance variable is associated with the object on which non static synchronized method is called then both the threads A as well as B will be accessing the instance variable concurrently.
 
vvus bharadwaj
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then is there any threat to that instance variable if one threadA writes the variable and thread b also writes that variable.What is solution for this.I think the solution is to keep the synchronization block around instance variable modifying code.Is this right?
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vvus bharadwaj wrote:Then is there any threat to that instance variable if one threadA writes the variable and thread b also writes that variable.What is solution for this.I think the solution is to keep the synchronization block around instance variable modifying code.Is this right?


yes you are right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic