Search code examples
javaresteasyquarkus

Java variable values persist in memory after responding to a request


I'm going to deploy a Java application using this docker image. I'm trying to eliminate the issue that the variable's value persists even after the response is generated. My assumption is to have an isolated environment per each request, BUT I'm not sure is correct or not.

For example, the given code block below will add the given URL param to a dummy list.

@Path("/hello")
public class GreetingResource {

    private final List<String> dummyList = new ArrayList<>();

    @GET
    @Path("/{param}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response hello(@PathParam("param") String param) throws InterruptedException {
        dummyList.add(param);
        
        return Response.ok(dummyList.toString()).build();
    }
}

If you curl the endpoint twice like:

/hello/client1
/hello/client2

my expectation is to receive:

[client1]
[client2]

but what I get actually is:

[client1]
[client1, client2]

This will make me a little worried about the concurrent sessions, and the question is how can I fix it.


Solution

  • This is why:

    private final List<String> dummyList = new ArrayList<>();
    

    As a rule of thumb: Never keep instance variables in service classes. Use DTOs and value objects to maintain state wherever you can. What you have up there is a big no-no in building service oriented architectures.

    For this scenario specifically, Quarkus defaults the scope of the service class ( GreetingResources) to singleton scope, which means a single instance will be used to serve all requests.

    You can change this behaviour by configuring the quarkus.resteasy.singleton-resources property in your config.