user886516
user886516

Reputation: 1

How exclusion is achieved using monitor in java

So Java supports object level monitors. So when we create an instance of a class basically we are creating different objects. Now, consider a scenario in which there is a shared data accessed by the all the instances of the object through a method in the object.

Please let me know how the keyword synchronized makes it possible to achieve thread safety in this case because i have different instances (objects) of the same class.

Upvotes: 0

Views: 73

Answers (2)

Binil Thomas
Binil Thomas

Reputation: 13799

If all instances of the class are accessing a piece of data, you might be using a static members:

public class Foo {
  private static Object shared;

  public static void accessShared() { /* code */ }
}

In that case, you can make the static method synchronized:

public class Foo {
  private static Object shared;

  public static synchronized void accessShared() { /* code */ }
}

This is equivalent to the code:

public class Foo {
  private static Object shared;

  public static void accessShared() { 
    synchronized (Foo.class) { /* code */ }
  }
}

Remember, Foo.class is itself an object, and hence has a monitor associated with it.

Upvotes: 0

rfeak
rfeak

Reputation: 8204

In that case you would synchronize on the object which is the data you are accessing.

So, if you have 100 instances of Foo all accessing a piece of data, that data has a single reference. Lets call that reference Bar. Then all your Foos would access Bar while synchronizing on it.

void changeBar(){
  synchronized(bar){
    //insert logic here
  }
}

Upvotes: 2

Related Questions