• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object level locking in Java threads  RSS feed

 
Prats Dev
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that below code would put a lock on current instance of DemoClass, What I am not sure of is the role of lock on Object Class in second example.
How does below works - Is it putting a lock on Object Class? If yes how will putting a lock on Object help? I mean, locking DemoClass ensure no two threads access it concurrently, how does this apply to Object class?

private final Object lock = new Object();
synchronized (lock)


public class DemoClass
{
public void demoMethod(){
synchronized (this)
{
//other thread safe code
}
}
}


public class DemoClass
{
private final Object lock = new Object();
public void demoMethod(){
synchronized (lock)
{
//other thread safe code
}
}
}
 
Mangal Pandey
Greenhorn
Posts: 8
Eclipse IDE Java ME Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class object will be used as mutex. Your method will look like.

public class DemoClass
{
public void demoMethod(){
synchronized (ClassName.class) //ClassName is name of the class containing method.
{
//other thread safe code
}
}
}

See this

For a class (static) method, the monitor associated with the Class object for the method's class is used.

For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Prats, welcome to CodeRanch!

It really doesn't matter very much which object you use to lock on, as long as different critical sections that may interfere with each other lock on the same object. A good way to make sure that competing critical sections don't interfere, but letting unrelated critical sections run uninterrupted, is to lock on an object that is being used. Usually this is the current object, but sometimes you might need temporary access to an object that's shared between other objects. In that case it makes sense to lock on that particular object.
I believe the java.util.concurrent package has more ways to deal with this problem though, such as actual lock objects, and conditions, etc.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!