A disclaimer or two for Optional

Doug Lea dl at cs.oswego.edu
Sun Oct 20 06:13:20 PDT 2013

On 10/19/2013 03:38 PM, Tim Peierls wrote:
> I suppose there's no harm in adding this, but I think most people already get
> that a reference to an Optional isn't a meaningful value.

The reaction of others seems to argue for adding the wording.
Most people know that comparing Integers via "==" is
almost always wrong. (So wrong that autoboxing normally
rescues you from this if one of the arguments is an int.)
And most people would not even think to do
synchronized(Integer.valueOf(aNumber), and would if asked
think that it is such a terrible idea that it is a good
candidate to being outlawed.
But most people haven't noticed that the same issues apply
even moreso to Optional.


> On Sat, Oct 19, 2013 at 2:16 PM, Doug Lea <dl at cs.oswego.edu
> <mailto:dl at cs.oswego.edu>> wrote:
>     This arose while contemplating some JDK9 possibilities...
>     Note that Optional is itself a value-like class, without
>     a public constructor, just factory methods.
>     The factory methods do not even guarantee to return unique
>     objects. For all that the spec does and should say,
>     every call to Optional.of could return the same Optional
>     object. (This would require a magical implementation,
>     but still not disallowed, and variants that sometimes
>     return the same one are very much possible.)
>     This means that there are no object-identity-related
>     guarantees for Optionals. "myOptional1 == myOptional2"
>     tells you nothing, and synchronized(myOptional) has
>     unpredictable effects -- it might block forever.
>     People might find this surprising, so we probably want to
>     add a sentence or two to the javadoc. How about the following.
>     (We could symmetrically say that the instance returned by
>     Optional.empty() need not be the  same each time, but that
>     might be overkill?)
>          /**
>           * Returns an {@code Optional} with the specified present non-null value.
>     adding...
>     * The returned instance need not be unique. Thus the results of
>     * comparing two instances using @code{==}, or using one as the
>     * argument for a @code{synchronized} block are arbitrary and should
>     * be avoided.
>           *
>           * @param <T> the class of the value
>           * @param value the value to be present, which must be non-null
>           * @return an {@code Optional} with the value present
>           * @throws NullPointerException if value is null
>           */
>          public static <T> Optional<T> of(T value) {
>              return new Optional<>(value);
>          }

More information about the lambda-libs-spec-experts mailing list