Question

Consider you have a shared memory (List) which will serve as the "critic section".
Now, consider you that you always have items in the list for these scenarios and you want that your system will behave this way:

  1. Thread1 get some item from the list, in the very same time Thread2 wants to add item to the list. Allow this scenario( in assumption I will take first item from begining and insert the new item in the end of the list - in the SAME TIME!).

  2. Thread1 wants to get an item and in the same time Thread2 wants to get an item too. This should fail.

THANKS

Was it helpful?

Solution

One possibility is to wrap your List in a class that proxies or overrides the get and add methods.

That way, you can use an explicit Lock on the add method, so that only one thread can add at any given time.

See for instance:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html

You could do this either by extending a List implementation, and overriding the add and get methods (or all relevant methods), or by using composition instead of inheritance, having a proxy class that forwards the calls to the list, but decorates the add and get with the explicit obtaining of the Lock.

A very simple example would be something like:

public class SharedMemory<K> {

private final List<K> memoryList;
private static final ReentrantLock lock = new ReentrantLock();

public SharedMemory() {
    memoryList = new ArrayList<>();
}

public void storeItem(K item) {
    memoryList.add(item);
}

public K getItem(int pos){
    lock.lock();
    try{
        return memoryList.get(pos);
    } finally {
        lock.unlock();
    }
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top