I have two threads running ( One is Main Thread(Say Thread1
) and another one is background thread (say Thread2
)). I can access HashMap
variable hashMap
from Thread1
and Thread2
. Thread1
modifies the hashMap
and Thread2 reads the HashMap.
In Thread1
code will be:
synchronized(hashMap){
//updating hashMap
}
In Thread2 code will be:
synchronized(hashMap){
//reading hashMap
}
Can I synchronize the access to hashMap
using synchronized block
in this way?
Yes. But also you can use Collections.synchronizedMap utility method to make a hashmap thread safe:
Map yourMap = new HashMap();
Map synchronizedMap = java.util.Collections.synchronizedMap(yourMap);
Or you can use ConcurrentHashMap or Hashtable which are thread safe by default.