Instantiation of resources

From WebLichtWiki

Revision as of 13:46, 13 December 2012 by Yana (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

By default, Jersey application creates Resource objects on a per-request basis, then they are discarded. That means, that you should use these default behavior only if your Resource does not introduce much of a performance penalty. On the plus side, per-request instances are simpler to deal with, you don't have to worry whether your Resource is thread-safe or not. For example, per-request Resource can be used in a converter service, because the converters are commonly neither time nor memory consuming. On the other hand, you should not use per-request paradigm if your resource requires a considerable amount of time when being created and takes a considerable amount of memory when created. This is usually the case when service uses huge list resources, databases, search indexes, machine learning models, etc. behind the hood.


In order to create Resource object only once and use it to serve all client requests, you should either register it as Singleton inside your implementation of Application, or annotate the Resource object with @Singleton annotation. In all the Creating a WebLicht Web Service tutorials the Resource object is registered as Singleton inside corresponding implementation of Application.


Even if your Resource is Singleton itself, its method annotated with a resource method designator (e.g., @POST) will be called on per-request bases. Therefore, you can still have some objects of your Resource created per-request if desired. For example, the implementation of Tokenizer and Sentence Boundary Detector Service has a tokenizer tool that does not consume much memory and is not expensive to create. As such, the tokenizer tool is created inside Resource @POST method and is discarded when the method returns. On the other hand, both the reference identifier in References Identifier Service and the named entity recognizer in Named Entities Recognizer Service mock using tools that are expensive to create and to keep in memory. Therefore, these tools are created at Resource construction and are stored in Resource instance fields, so that the same tool is shared among different client requests.