Collections.synchronizedXXX() and internal mutex (aka SyncRoot)
dmytro sheyko
dmytro.sheyko.jdk at gmail.com
Wed Apr 29 07:58:27 UTC 2020
Hello,
Have you ever discussed to make field mutex in synchronized collections
accessible?
Javadoc for Collections#synchronizedSortedSet suggest to iterate collection
this way:
SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
SortedSet s2 = s.headSet(foo);
...
synchronized (s) { // Note: s, not s2!!!
Iterator i = s2.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}
I.e. in order to iterate subset, we also need a reference to the whole set,
which is not really convenient. How about to make it possible to write:
SortedSet s2 = s.headSet(foo);
...
synchronized (Collections.getSyncRoot(s2)) { // Note:
Collections.getSyncRoot(s2)
Iterator i = s2.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}
Also I think it would be convenient to let to provide custom sync root when
synchronized collection is created.
E.g.
Object customSyncRoot = new Object();
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(),
customSyncRoot);
What do you think about this?
Regards,
Dmytro
More information about the core-libs-dev
mailing list