Collections.synchronizedXXX() and internal mutex (aka SyncRoot)
Jason Mehrens
jason_mehrens at hotmail.com
Wed Apr 29 21:58:58 UTC 2020
Background on this can be found here: https://bugs.openjdk.java.net/browse/JDK-4335520
Jason
________________________________________
From: core-libs-dev <core-libs-dev-bounces at openjdk.java.net> on behalf of dmytro sheyko <dmytro.sheyko.jdk at gmail.com>
Sent: Wednesday, April 29, 2020 2:58 AM
To: core-libs-dev
Subject: Collections.synchronizedXXX() and internal mutex (aka SyncRoot)
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