简体   繁体   中英

Synchronize access to HashMap from two threads in java

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.

I would use ReadWriteLock

ReadWriteLock rwl = new ReentrantReadWriteLock();

void read() {
    rwl.readLock().lock();
    try {
        ... read
    } finally {
        rwl.readLock().unlock();
    }
}

void write() {
    rwl.writeLock().lock();
    try {
        ... write
    } finally {
        rwl.writeLock().unlock();
    }
}

You should try using HashTable or ConcurrentHashMap . Both these classes are synchronized so you wouldnt have to deal with it yourself.

Also, consider using a Lock .

Do see:

1. Java Synchronized Blocks .

2. Intrinsic Locks and Synchronization .

3 . Synchronization, Thread-Safety and Locking Techniques in Java and Kotlin .

4. On properly using volatile and synchronized .

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