This content has been marked as final. Show 2 replies
It seems to me that if you "clear" a set in one thread and "add" an entry to the set at the same time that the "clear" is taking place, then whether or not you see the result of the "add" after both operations are complete would be undefined. And indeed for the case of "clear" and "get" the API documentation says exactly that:
For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.However if you're wanting to wait until N puts have taken place before doing something with the contents of the map, I would suggest that something involving a CountdownLatch or a CyclicBarrier would be suitable. And I would consider not clearing the map when the countdown is complete, but just creating a new map for the next batch of puts to use.
In fact now that I read up on CyclicBarrier a bit, it looks like it would be quite suitable for your requirement:
A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.In other words when N entries have been added to your map, the barrier point is reached and your Runnable creates a new empty map for subsequent parties to use and processes the old map with N entries.