简体   繁体   中英

Thread-safe Tree

Is there a thread-safe implementation of a tree in Java? I have found a bit of information that recommends using synchronized() around the add and remove methods, but I interested in seeing if there is anything built into Java.

Edit: I am trying to use an Octree . Just learning as I go, but I am using this project to learn both multi-threading and spatial indexing so there are lots of new topics for me here. If anyone has some particularly good reference material please do share.

From the documentation for TreeMap :

SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

Note that this only makes each call synchronized. In many cases this is the wrong granularity for an application and you are better off synchronizing at a higher level. See the docs for synchronizedSortedMap .

You can use Collections.synchronizedSet() or synchronizedMap() to add the synchronization around individual methods, but thread safety isn't really a property of a data structue but of an application. The wrapper will not be sufficient if you iterate over the tree, or do series of operations that need to be atomic.

A java.util.concurrent.ConcurrentSkipListMap might be of interest. This is overkill for most uses, but if you need fine-grained synchronization there's nothing like it. And overkill beats underkill. Of course, it's not a tree, but does the same job. I do not believe you can get low-level synchronization in a real tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM