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:
-
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!).
-
Thread1 wants to get an item and in the same time Thread2 wants to get an item too.
This should fail.
THANKS
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
Lockon theaddmethod, 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
Listimplementation, and overriding theaddandgetmethods (or all relevant methods), or by using composition instead of inheritance, having a proxy class that forwards the calls to the list, but decorates theaddandgetwith the explicit obtaining of the Lock.A very simple example would be something like: