Reputation: 83
There is a multi-threaded environment given. I have the below dummy class with a Map attribute, which is initialized with values when an instance is being created. The key of the map is a String while the value is a Boolean, which will indicate whether the respective entry is currently used by somebody else (another thread), or free for usage. I would like this map to be shared between all the accessing threads with the condition that everybody can immediately see if an entry update happens (indicating that the respective entry was just picked or freed up). What is the appropriate and most safe way to achieve this? Will it do the trick if I mark the map attribute as volatile, while the two methods synchronized? (The next step would be to enhance it with a waiting logic, so if there is no available entry the thread could wait until a certain timeframe before it throws an exception.)
public class Dummy {
private Map<String, Boolean> sharedMap;
public Dummy() {
this.sharedMap = new HashMap<String, Boolean>(){{
put("key1", Boolean.FALSE);
put("key2", Boolean.FALSE);
put("key3", Boolean.FALSE);
put("key4", Boolean.FALSE);
put("key5", Boolean.FALSE);
put("key6", Boolean.FALSE);
}};
}
public String getFreeEntry() throws CustomException {
Map.Entry<String, Boolean> entry = this.sharedMap.entrySet().stream()
.filter(x -> Boolean.FALSE.equals(x.getValue()))
.findFirst().orElseThrow(CustomException::new);
entry.setValue(Boolean.TRUE);
return entry.getKey();
}
public void releaseEntry(String key) {
this.sharedMap.put(key, Boolean.FALSE);
}
}
Upvotes: 0
Views: 787
Reputation: 1744
You can take a look at ConcurrentHashMap
which is thread-safe.
A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.
Any number of threads can perform retrieval operation, but an update can be done with utmost one thread at a time. And this thread must lock the particular segment in which the thread wants to operate.
Note that inserting null objects is not possible in ConcurrentHashMap
as a key or value.
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html
Upvotes: 1