Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A synchronize question

 
Salish Tankard
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic