Reputation: 1049
In Collections javadoc it is mentioned like below..
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:
Map m = Collections.synchronizedMap(new HashMap());
...
Set s = m.keySet(); // Needn't be in synchronized block
...
synchronized (m) { // Synchronizing on m, not s!
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
My Question is, if I declared an Hashtable and can I use it without synchronizing on it. Like below
Hashtable ht = new Hashtable();
Set s = m.keySet();
Iterator i = s.iterator();
while (i.hasNext())
foo(i.next());
Upvotes: 1
Views: 396
Reputation: 824
As you are doing every operation in a single thread, there should be no concurrency issue observed in this case. Though I must say that the example you provided from JavaDoc is not related to example you have question regarding. Please modify the question with more details.
Upvotes: 0
Reputation: 36064
if I declared an Hashtable and can I use it without synchronizing on it?
No, you need to synchronize it.
Reason:
Iteration over [any] collections in Java is not thread safe.
This is the implementation of the Hashtable#keyset() method:
public Set<K> keySet() {
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
If you notice, it returns synchronizedSet. As it's mentioned in the javadoc It is imperative that the user manually synchronize on the returned set when iterating over it
because the iterator
method in the SyncronizedSet is not synchronized.
Upvotes: 1
Reputation: 533492
if I declared an Hashtable and can I use it without synchronizing on it.
You can but you shouldn't if you want to avoid a ConcurrentModificationException. I.e. it uses synchronization just like a synchronized HashMap as has the same limitation.
Note: if you use a ConcurrentHashMap, you don't need to lock it (and in fact you can't)
Upvotes: 3
Reputation: 43391
Yes.
The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a
ConcurrentModificationException
.
So, if you want to go through an iterator from a Hashtable
, you have to ensure that nobody else modifies the Hashtable
object in the meanwhile. If that object is shared among multiple threads, the best way to do that is to synchronize on a common object, such as that very same Hashtable
you're iterating over.
Upvotes: 3