JAX-RS: getClasses vs getSingletons
jax-rs, jersey, web-applications, web-services
Solution
No, it won't. Multiple threads in JVM are able to access one instance of a class at the same time (invoke a resource method on your resource in this case). You just need to make sure your resource is thread-safe.
To illustrate the difference between `getClasses()` and `getSingletons()` lets assume we have a `HelloWorldResource` like:
@Path("helloworld")
public class HelloWorldResource {
private volatile int counter = 0;
@GET
@Produces("text/plain")
public String getHello() {
return "Hello World! " + counter++;
}
}
Multiple invocations of `getHello` resource method would return you:
in case you register your resource via `getClasses`
Hello World! 0
Hello World! 0
Hello World! 0
...
in case you use `getSingletons` to register your resource
Hello World! 0
Hello World! 1
Hello World! 2
...
Problem
I'm using JAX-RS (Jersey implementation) to build a web service. The entry point to the web application is a class that extends `Application` and overrides the `getClasses` method. I understand that JAX-RS will create a new instance for each new request. It is possible to override `getSingleton` instead. My understanding is that this will reuse the same instance for all requests. However, won't this approach (assuming I'm correct) destroy concurrency within the web application? That is, since the same instance is always used, incoming requests will be processed one at a time (FIFO?).