简体   繁体   中英

mutual exclusion using Hashtable of java

hi mate i have a global Hashtable in my class, and two thread A and B that work with her. A reads from HashTable and B write in Hashtable.. is there a problem of mutual exclusion ? i need to syncrhonize it or Hashtable class is safe ?

Hashtable is a thread-safe implementation of the Map interface.

In regular put and get operations you will be safe. However, when you will iterate on it in one thread and modify its contents from another thread, you will have ConcurrentModificationException issues. So, when iterating, make sure you iterate on a copy of the original Hashtable .

您应该改用ConcurrentHashMap ,它是java.util.Map接口的更好/更快的实现。

It's useful to use a synchronized HashMap offered by java collections. This class is a simple wrapper and encapsulates the hashmap :

Collections.synchronizedMap(new HashMap());

Further example example is in the java docs : http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html synchronizedMap

HashTable gaurantees that any operation executed on it is atomic. but If you are executing multiple operations you should synchronize them. In below example even if contains and put are atomic but the code has a check and act raise condition so you need additional synchronization for this.

    if(!hashtable.contains(Object))
    {
        hashtable.put(key, value);
    }

Also check Collections.synchronizedMap() or ConcurrentHashMap rather than HashTable

Everyone has said what can be said but this is just to complement with regards to what you call mutual exclusion . You are asking if there won't be such a problem. A thread-safe program must ensure that that if threadA is using say a block of code block1 no other thread will access it until the thread is done. So, if I understand well what you mean by mutual exclusion , yes threads accessing the same synchronized (thread-safe) shared resource are mutually exclusive because they both can't access it at the same time.
Java practically does much of the hard for you if you choose one of the proposed safe Map implementation. Now if your Hashtable ( or whatever else thread-safe mao you prefer ) is a shared resource, the only thing you need to take care of is the happens-before relation. It will be important if one thread is reading data and the other writing data.
More can be found at java concurrency tutorial and java concurrent package docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM