5

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";
    }    
}

?

WildDev
  • 2,250
  • 5
  • 35
  • 67

1 Answers1

3

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?

Community
  • 1
  • 1
francis
  • 5,889
  • 3
  • 27
  • 51
  • Operations in my project requires the set of operations which are use the single variable to share the state, like `set()`, `register()`, `execute()`. So if i use Servlet, I forced to create two classes instead of one to implement the single action because Servlet is not thread safe. Thank you :)) – WildDev Apr 26 '15 at 16:17
  • 1
    I'd just mention that JAX-RS and Jersey aren't the same thing. Jersey is an implementation of JAX-RS. JAX-RS has it specification, and Jersey implements it, along with the addition of extra features. The `@RequestScoped` annotation is not part of the JAX-RS spec, it's a Jersey specific feature. Though, yes the default scope specified by JAX-RS is per request, it all depends on external configuration. Just thought I'd mention this, as the question had no mention of Jersey :-) – Paul Samsotha Apr 26 '15 at 18:52