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();
}
}
}