*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes A synchronize question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "A synchronize question" Watch "A synchronize question" New topic
Author

A synchronize question

Salish Tankard
Greenhorn

Joined: Oct 08, 2002
Posts: 8
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
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://aspose.com/file-tools
 
subject: A synchronize question
 
Similar Threads
Lock Manager question
Collections
Question on collections
TreeSet & TreeMap
TreeSet and compareTo Java 5