I have read that access to Collection instances should not be synchronised within a class. The reason seems to be that another object might manipulate the list, without synchronising to the first object. However, the List I want synchronised is a private field, is created by the owner object, and has no accessor methods.
I am using two inner classes, a producer and a consumer, which each implement class Runnable and run in a separate thread. Whenever they access the list belonging to the parent class, they will synchonise on the parent class.
Furthermore, my implementation only uses a single instance of the parent class, and one each of the inner classeses.
Is it acceptable, then, simply to use synchronise blocks to control access? Or is this still a no-no?
I don't think I can use a synchronisedList. The reason is that the consumer thread consumes in bulk: it first sorts using Collections.Sort and a comparator, then uses the subList method to get a list of the first 20 (by default) objects in the list (it actually creates a new list, by passing the subList call to an ArrayList constructor), and then passes the list returned by subList to removeAll of the original list:
Collections.sort(pool, examComparator);
List<Candidate> squad = new ArrayList<Candidate>(pool.subList(0, squadSize));
pool.removeAll(squad);
return squad;
Since this is a multi-step operation, and needs to be atomic, I can't see how it would be facilitated by synchronisedList, which (as I understand it) simply provides synchronisation for individual method calls such as add() and get().