문제

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.

다른 팁

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();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top