Search code examples
javaoptimizationjvminternalsjava-8

Java - SAM type optimization


A working document describing the state of Project Lambda mentions the so-called SAM (single abstract method) types. As far as I know the current lambda proposal doesn't affect the runtime just the compiler by making possible automatic conversion from lambda expressions to these types.

I think in ideal circumstances instances of SAM types could be internally represented by function pointers. Therefore the JVM could avoid memory allocation for these instances.

I am wondering whether the modern virtual machines are able to provide such optimization.


Solution

  • @Tamás You should probably have a read of this mailing list post by Brian Goetz:

    http://mail.openjdk.java.net/pipermail/lambda-dev/2011-August/003877.html

    Basically, the lambda abstraction is currently implemented using objects. However, it has been designed to permit alternative realizations of lambdas, which would be "smaller" than instances of classes.

    You can think of the situation as similar to autoboxing - ints are boxed to Integer, but have a "smaller" representation (as ints).

    Currently, lambdas have to be boxed to instances of SAM types, b/c the JVM currently has no way to represent a lambda with any smaller construct. In the future, there may be a new JVM standard which includes "primitive functions" which could represent lambdas as something other than objects.

    So, to answer your question, the type of optimization you propose above, may be possible, but it probably would come with post-Java 8 work on "primitive functions" rather than being an implementation-specific feature.