Kiran
Kiran

Reputation: 757

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?

Upvotes: 4

Views: 4514

Answers (3)

Yash Sampat
Yash Sampat

Reputation: 30601

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.

Upvotes: 1

Serdar
Serdar

Reputation: 383

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.

Upvotes: 5

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

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();
    }
}

Upvotes: 0

Related Questions