This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

parallel execution on synchronised static method  RSS feed

 
Vijay Venkat
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is question on parallel execution two different method which are static and synchronised in the same class

class Test
{
public synchronized static One()
{
System.out.println("one");
}
public synchronized static two()
{
System.out.println("two");
}
}

This is my understanding can this be validated.
Say now multiple thread are accessing the two methods of this class.

Consider that thread1 is now executing method One - during this time synchronisation is carried out by obtaining a lock on the class Test.class and if during execution of method One() another thread2 tries to access method Two() it will be blocked since it cannot obtain a lock on the class.

Am i right or is my understanding wrong.

regards,
Vijay V
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right. Only one instance of either of the two methods may be executing at any given time in any thread.
 
Vijay Venkat
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest

I have one more clarification - i am not sure it is right to ask in the same thread by it is similar to the first one.


For the above example if method Two() was not static.
If thread1 one accessed the method One() it would obtain lock on Test.class
now since method Two() is not static - thread2 can access method Two() and it does this by acquiring lock on "this" the current instance of that class

Thus parallel execution can take place.

Is my understanding correct?

Thanks,
Vijay V
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again, yes. Your understanding is perfect.
 
Vijay Venkat
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again thanks Ernest :-)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!