I have a implemented a class that acts as a Cache for objects. It has a DelayQueue for removing objects from cache.
class mySingletonClass {
ConcurrentHashMap map<String,MyObject>();
DelayQueue queue <MyObject>();
boolean alreadySeen(MyObject myObject) {
MyObject obj = map.putIfAbsent(myObject.getID(),myObject);
if(obj != null) return true;
queue.add(myObject);
return false;
}
It works fine for single threaded. I am trying to test it with multiple threads concurrently. I have tried to reason about if this method is thread safe but I am unsure. I have tried the static analyzer FindBugs plugin. I am unsure how to unit test this. I have never used java.util.concurrent nor worked with threads so I am trying to learn it all relatively quickly.
My thoughts for unit testing were create an AtomicInteger and run multiple threads trying to add the same object to the map. If the method returns true increment the integer. This integer should equal one if successful. As my second test I was thinking similarly with AtomicInteger try to have maybe 10? threads with each thread adding a list of 5 unique objects and ensure the total after all threads are done is 5.
I have been playing with Executors and creating Runnable methods but I am getting NullPointerExceptions and I am not sure exactly what I am doing.
I'm looking for:
Is this method thread safe? If not is there a way to make it thread safe (other than just making the method synchronized)?
How to I implement the two unit tests with multiple threads in junit4?