KiranCK KiranCK - 17 days ago 6
Java Question

Lambda is not evaluated till function returns

public Resposne some_function(){
Response resp = null;
try{
resp = Response.ok().type(APPLICATION_ZIP).entity((StreamingOutput) out -> {
//Some code here.
}).header(CONTENT_DISPOSITION_HEADER, "ABC").build();
}catch()
{
}
return resp.
}


Hi,

I have a function similar to the above. The lambda passed to the entity function is not evaluated till the function some_function returns. Looks like Java 8 feature. Any pointers to what could be happening? Also, is there a way to force the evaluation? Thanks.

Answer

Presumably, you're using JAX-RS's ResponseBuilder type. It has an entity method which accepts an Object. This method

Set the response entity in the builder.

Any Java type instance for a response entity, that is supported by the runtime can be passed.

You've passed it a StreamingOutput object.

A type that may be used as a resource method return value or as the entity in a Response when the application wishes to stream the output. This is a lightweight alternative to a javax.ws.rs.ext.MessageBodyWriter.

JAX-RS will have called your resource method, some_function(), and will receive a Response object in return. When it has that, it will attempt to serialize it. Internally, your JAX-RS implementation likely has a handler that knows how to process StreamingOutput entities. All it has to do is invoke its write method.


Lambda expression evaluation consists in creating an instance of the corresponding functional interface. In your example, no code has yet invoked that functional interface's method. JAX-RS will eventually.

Comments