java - Concurrency : full collection or element -
I have such a collection that I need to update every other. I use that for ScheduledExecutorService but I have questions Is it better to give thread full collection or send each element of the collection to the pool pool?
I recommend the following solution:
-
Collection for the map, replace them withconcurrenthashmap . Thismap is tolerant for collection changes, and its locking ishash code () .- Use the set made by the
set collection, factoryCollections.newSetFromMap () with theconcurrenthashmap example of the argument As I've mentioned above, themap done in the form will give you thisset with the same thread-related properties.For the
list collection, first consider if you really need thelist . If so, consider using theCopyOnWriteArrayList orwrap the original list with the list list = archive. (New Arreist); // perhaps linked, but it is not related to the question.
Please advise that the hearer threads returned from this wrapped list are not secure and
ConcurrentModificationException .Now, you may have trouble - the factory returned in the
set can not have the same values. If this is a problem for you, try using some GuavaMultiset . More information about this can be found.Ok, we ended up with the archive. Now, consider the update of the
concurrent hashmap .Implementation of this structure gives you the so-called final visibility guarantee. This means that each itater represents some collection state - perhaps not the last one, but in a few moments of time, probably in the past the state is guaranteed to be valid usually it is sufficient for most cases it happens.
This means that to parallel some of the handling of some activities, you can modify your
threads orrunnable code> Reads otherthreads orrunner , and you should be OK.Note that the
list I mentioned above will be lower below because this collection has been specially linked to that cover due to thesynchronize blocks.
- Use the set made by the
Comments
Post a Comment