Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaEE Web JAX-RS: can i use instance variables inside it's class?

I'm looking for thread-safe Servlet alternative and I've found JAX-RS technology.

So can i use instance variables inside it's class like this (is it thread safe):

@Path("helloworld")
public class HelloWorldResource {

    private String msg;

    @GET
    public void doSmth() {
       this.msg = "test";
    }    
}

?

like image 644
WildDev Avatar asked Oct 20 '22 13:10

WildDev


1 Answers

Resource scope will default to @RequestScope so a new instance of your resource will be created per request.

From Chapter 3. JAX-RS Application, Resources and Sub-Resources

@RequestScoped

Default lifecycle (applied when no annotation is present). In this scope the resource instance is created for each new request and used for processing of this request. If the resource is used more than one time in the request processing, always the same instance will be used. This can happen when a resource is a sub resource is returned more times during the matching. In this situation only on instance will server the requests.

So as long as msg is not static it should be created per request.

This also means that after the request is handled you are going to lose any state contained in the resource, what use case are you trying to solve here?

like image 174
francis Avatar answered Oct 22 '22 03:10

francis