Hi, I am planning to use SortedSet to store my locked record number, however, I am not sure if it is threadsafe. I read the java doc 1.4, and here is what it said. Am I understanding it correctly that I have two choice: 1. explicitly synchronize my SortedSet object 2. if not, at the creation time, I can wrap the object by using Collections.synchronizedSet method, and the object will be thread safe? Please help me to clarify this..... thanks in advance...
http://java.sun.com/j2se/1.4/docs/api/java/util/TreeSet.html Note that this implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
[ November 07, 2002: Message edited by: Salish Tankard ]
Peter den Haan
author
Ranch Hand
Joined: Apr 20, 2000
Posts: 3252
posted
0
Originally posted by Salish Tankard: 2. if not, at the creation time, I can wrap the object by using Collections.synchronizedSet method, and the object will be thread safe?
The object will be threadsafe, but your code probably will not. The reason is that you are likely to perform composite operations taking more than one method call which need to be atomic with respect to other threads. My advice would be to avoid synchronized collections. This forces you to think carefully about what synchronization you need and where, and increase the likelihood of actually producing threadsafe code. - Peter
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.