I am writing a small embedded Jetty web server, but I have a shared object that has an expensive construction and I don't want each single request to the servlet to have to rebuild this object. Unfortunately the way I add a resource in Jetty is through the ResourceConfig
constructor, but this does not allow me to do anything beyond adding the class name:
// instantiate this expensive object
MyExpensiveSharedObjectClass myExpensiveSharedObject = new MyExpensiveSharedObjectClass();
String result = myExpensiveSharedObject.search("alpha");
// set up the service
final ResourceConfig resourceConfig = new ResourceConfig(MyService.class);
Then MyService.java
contains your standard declarations such as:
@GET
@Path("/doSomething")
@Produces(MediaType.APPLICATION_JSON)
public String doSomething() {
// do stuff with myExpensiveSharedObject....except how do I get to it??
// String result = myExpensiveSharedObject.search("alpha");
What I want ideally is a way that each time a request comes into /doSomething
, I can perform methods on the myExpensiveSharedObject
object that I've created earlier.
I imagine this is quite simple but I can't find a simple method of accomplishing this.
Alternatively - is there a way to have some form of shared memory space within the Jetty servlet? I noticed that every single request seems to instantiate a new instance of the servlet, so I can't, for example, build up a shared memory map within the object that can be reused by all instances of the class. I am sure this is possible but I can't figure out how to do it.
Basically, I'm just trying to find a way to have an object that is expensive to construct, something that would be ideal within a constructor method or passed into the servlet itself, but within the context of these servlets, constructors are called every single request, so I can't go that route.