JDK-6729834 : (coll) Check before wrapping at Collections.synchronized* and Collections.unmodifiable*
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6
  • Priority: P5
  • Status: Closed
  • Resolution: Duplicate
  • OS: linux
  • CPU: x86
  • Submitted: 2008-07-25
  • Updated: 2024-04-12
  • Resolved: 2017-06-03
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
Other
tbdResolved
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
Current implementation of java.util.Collections.synchronizedList (Map, Set) as well as unmodifiableList (Map, Set) blindly wrap given collections into synchronized/unmodifiable counterparts without checking, if, for example, an unmodifiable map is already passed to Collections.unmodifiableMap() as an incoming parameter.


JUSTIFICATION :
There can be plenty of situations (e.g. injection) when code does not know what underlying types of collections it operates with. When implementing, for example, immutable behavior, Collections.unmodifiable* methods come in very handy. However, creation of unnecessary objects (see Description) costs extra memory and CPU. And it doesn't seem that it would affect any of existing behavior.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Quick solution:
If given object is already an instance of java.util.Collections.SynchronizedMap(Set, List), quickly return whatever was passed to that method. Similarly for the unmodifiable counterparts.

Proper solution:
Provide a marker interface so that incoming collections could be checked against being instance of synchronized/unmodifiable map (set, list) but not necessarily being a derivative of inner Synchronized* or Unmodifiable* classes of java.util.Collections.
ACTUAL -
The incoming collections are blindly wrapped into unmodifiable/synchronized counterparts (e.g. see public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) method of java.util.Collections class).

CUSTOMER SUBMITTED WORKAROUND :
When the collections are not injected, a flag needs to be kept outside collection to know whether it was made unmodifiable/synchronized or not.