I have a Java code which searches for values in the hash table in following way:
class HTDemo {
public static void main(String args[]) {
Hashtable balance = new Hashtable();
double bal;
balance.put("John Doe", new Double(3434.34));
balance.put("Tom Smith", new Double(123.22));
balance.put("Jane Baker", new Double(1378.00));
balance.put("Todd Hall", new Double(99.22));
balance.put("Ralph Smith", new Double(-19.08));
**System.out.println("John Doe's balance: " + balance.get("John Doe"));**
**System.out.println("Tom Smith's balance: " + balance.get("Tom Smith"));**
**System.out.println("Jane Baker's balance: " + balance.get("Jane Baker"));**
}
}
Now, I want to run it on multiple thread i.e. I want to modify the code in such a way thus the get methods (inside **) works concurrently. Can anybody help me how to do that. Actually, I am facing issue with passing hash tables and making it concurrent while running.
Hashtable is synchronized and therefore already thread safe. You don’t need anything else to access your code safely in a multi threaded environment.
However, HashTable is obsolete and its performance will be quite poor in a highly concurrent environment due to the thread-safety mechanism that is implemented (all methods are synchronized) and the provided iterators are not thread safe and will fail if you modify the table while iterating.
Bottom line: use a ConcurrentHashMap, and use generics if you can:
The rest of your code should remain unchanged.
One thing you also need to keep in mind, is that even with a thread safe data structue (be it a HashTable or a ConcurrentMap), you still need to deal with concurrency issues such as atiomcity.
For example, if you check the balance to authorise a payment like this:
There is an atomicity issue: the balance on John’s account might have changed between the call to
balance.get(...)and the payment authorization.If this is one of your use cases, you will need to introduce an additional layer of synchronization.