I think I can use any object to be synchronized as block such as:
synchronized(new Object()){
}
but I often see to synchronized one hashmap when need hashmap be thread safe.but I think I can use one other object to instead of the hashmap. So which object be synchronized best?
Doing synchronized (new Object()) { ... }
is of no use at all, since no other thread would ever get hold of the object which is locked anyway.
You should synchronize on an object "guarding" a resource. Obviously, if several threads needs access to the same resource, the object guarding the resource needs to be available to both threads.
Perhaps you've seen this:
class SomeClass {
final private Object lock = new Object();
void method() {
...
synchronized (lock) {
...
}
...
}
}
That is however very different from doing synchronized (new Object())
since in the above code, the same object is used for all threads executing the method.
but I often see to synchronized one hashmap when need hashmap be thread safe.but I think i can use one other object to instead of the hashmap. So which object be synchrozied best?
Right, if a hash map is the resource to be shared among several threads, then it is common to synchronize on that object.
synchronized (someHashMap) {
... use someHashMap in a thread safe way ...
}
And yes, you could just as well synchronize on some member field lock = new Object()
as well. In fact, synchronizing using a dedicated lock object is sometimes preferred, since it doesn't interfere with the synchronized methods of the object you're protecting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With