Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

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();
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top