Reputation: 43
I have a hashmap which contain Link object as value and Integer as a key.which is getting updated after every one second and at the same time it is accessed from some other class in some different thread. I want to make hashmap inaccessible while updating Value part(Link object after api response) and make it accessable once updation is complete. what is best possible way to do this.
class Link{
int id;
int currentBWidth;
//getter and setter
}
public class Cache implements Runnable {
public static HashMap<Integer, Link> linkDetailsMap;//accessed by some other class
static {
initMap();
}
private static void initMap() {
linkDetailsMap = new HashMap<Integer, Link>(667);//needed a hashmap
with fixed size 500
for (int count = 0; count < 500; count++) {
Link link = new Link();
link.setLinkId(count);
link.setCurrentBWidth(count);
linkDetailsMap.put(link.getLinkId(), link);
}
}
@Override
public void run() {
while (true) {
try {
// making a rest appi call and modifying link CurrentBWidth in
// linkDetailsMap
**for(Map.Entry<Integer, Link> entry:linkDetailsMap.entrySet())
Link link = entry.getValue();
link.setCurrentBWidth(//some vallue);
}**
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
......... ///extra code
}
Upvotes: 0
Views: 1068
Reputation: 251
You can try to use Semaphores as below.
Semaphore semaphore = new Semaphore(1); //Have this as singleton instance all with the map.
.....
//before write
semaphore.acquire();
//actual write.
semaphore.release()
.....
//Before read check if semaphore is already acquired as below.
if(semaphore.availablePermits() == 1) {
//Perform read
} else {
//Wait and read later.
}
Upvotes: 1
Reputation: 41178
Just do this by synchronising on the hash map.
In both threads do
synchronized (linkDetailsMap) {
// Do stuff here
}
While one of the threads is inside that synchronized block the other cannot enter it and will wait - so anything done in there will not have any threading problems.
A good alternative would be to use ConcurrentHashMap
to store your values, I didnt suggest it immediately though as this line here "I want to make hashmap inaccessible while updating Value part(Link object after api response)" suggests that there more be more processing to do than just the put() operation and that all that processing needs protecting.
Upvotes: 1
Reputation: 3098
Use a ReentrantReadWriteLock to protect modification with the write lock and reading with the read lock. You can have many readers at the same time but only one writer. That way, readers will be blocked while the writer holds the lock.
Upvotes: 2