Question

I was reading the source code of the Functional Java library and noticed this:

public static <T> Option<T> none() {
    return new None<T>();
}

I was wondering why they don't always return a singleton parameter, specially because of None's equality implementation:

private static final class None<A> extends Option<A> { 

...

@Override
public int hashCode() {
    return 31;
}

@Override
public boolean equals(Object obj) {
   if (this == obj)
      return true;
   if (obj == null)
      return false;
   if (getClass() != obj.getClass())
      return false;
   return true;
}

}

So I did a search at Functional Java's forum and I found this question and answer:

Is it possible to set this up so it doesn't create a new None for every call to none, can we use a single object to represent None in all cases?

No, but then, who cares? The JIT optimiser can take care of these things quite well nowadays.

My question is how the JIT optimiser handles this in a way that it isn't necessary to return a singleton. I know that object creation is cheap, but I think a singleton would be cheaper and in this case it doesn't add any complexity.

Was it helpful?

Solution

No, Java VMs I know don't perfom such optimizations. With modern JVMs it's actually cheaper to create new object rather then look for some existing one. What they also mean in this FAQ is that short-lived, throw-away objects don't really impact garbage collection time (but might increase GC frequency). Also I can imagine JVM performing escape analysis and allocating such object on stack rather than on heap.

However I do think it's quite wasteful. Look at java.lang.Integer (and all other primitive wrappers) cache or Optional.absent() in Guava:

public static <T> Optional<T> absent() {
  return (Optional<T>) Absent.INSTANCE;
}

There are plenty of other optimizations like that in the JDK: enums are singletons, Collections.emptyList() always returns the same instance, etc.

OTHER TIPS

It is more type safe, otherwise we need to rely on erasure.

Creating an object is probably still more expensive than looking up a cached one. See java8's Optional:

http://hg.openjdk.java.net/lambda/lambda/jdk/file/ad394630273b/src/share/classes/java/util/Optional.java

   43     private final static Optional<?> EMPTY = new Optional<>();

   63      * There is no guarantee that it is a singleton.

   69     @SuppressWarnings("unchecked")
   70     public static<T> Optional<T> empty() {
   71         return (Optional<T>) EMPTY;
   72     }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top