So Java supports object l开发者_开发技巧evel 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.
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
}
}
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.
精彩评论