Search code examples
javahashmapjettyconcurrenthashmap

Shared HashMap in Jetty


I'm currently building a simple REST interface using Jersey with embedded Jetty.

Server server = new Server(8080);
ContextHandlerCollection contexts = new ContextHandlerCollection();
ServletContextHandler  servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
ServletHolder sh = new ServletHolder(ServletContainer.class);
servletContextHandler.addServlet(sh, "/*");
server.setHandler(servletContextHandler);
sh.setInitParameter("com.sun.jersey.config.property.packages", "my.package.containing.jersey.resource");

In my resource I define @GET, @PUT, @DELETE methods, which all get/put/remove objects from a hashmap.

Currently I'm defining the HashMap as a static ConcurrentHashMap in my resource class, which works fine so far.

public class MyResource {

private static final Map<String, MyObjects> myRepository = new ConcurrentHashMap<String, MyObjects>();

@GET
...

@PUT
...

}

However, I plan to make the HashMap accessible for potential other resources and servlets.
Therefore want to add it in some wider scope application context.
Not sure though, how this can be best done?
Ideally programatically.
(I've seen there's a WebAppContext in jetty.webapp, not sure if this is the way to go though).


Solution

  • Use some dependency injection in your application (Spring, Guice) to inject one instance of the hashmap in all resources needing to access/modify it.