I have a multithreading program, and I am wondering which of the way using “synchronized” is correct.
Way 1 :
I have a class object (which will be passed to multiple threads), called MyClass, inside it:
public synchronized void set(String name) {
this.name = name;
}
Way 2 :
I have same class, but not having “synchronized” in its set method:
public void set(String name) {
this.name = name;
}
And the caller will do this :
MyClass myclass = new MyClass();
synchronized(myclass) {
myclass.set("myclass");
}
Can anyone tell me which one is correct way of implementing multithreading object sharing? I am confused by these two and I tried both, they seems to work correctly.
Synchronize on the method:
It depends on the context, really – e.g. in some cases it’s better for callers to do the synchronization, as then they can decide whether the synchronization overhead is worth it. For example, all callers that are known to work on one thread do not need synchronization and this will only slow things down.
For all things that are not time-critical, it will most likely be better to avoid issues you need to debug while on your 5th coffee at 3am, while your colleagues wave a baseball bat and yell words that are not to be mentioned to kids…