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:
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.Right, if a hash map is the resource to be shared among several threads, then it is common to synchronize on that object.
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.