Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to judge which object to be synchronized in java thread?

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?

like image 299
jiafu Avatar asked Mar 23 '12 14:03

jiafu


1 Answers

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.

like image 68
aioobe Avatar answered Oct 05 '22 11:10

aioobe