1

what is the right way to initialize my database only once? See this example:

@Path("/")
public class Resource {
    private static final Map<Integer,String> data = new ConcurrentHashMap<Integer,String>()

    public Resource() {
        data.put(1, "1");
        data.put(2, "2");
        ...
    }
}

For example if I delete entry 1, it will be present on the next request again.

S1lentSt0rm
  • 1,989
  • 2
  • 17
  • 28

1 Answers1

1

You can use a static initialization:

@Path("/")
public class Resource
{
    private static final Map<Integer,String> data;
    static
    {
        myMap = new new ConcurrentHashMap<Integer,String>();
        myMap.put(1, "1");
        myMap.put(2, "2");
    }
}

The static block only gets called once, when the class is constructed.

user987339
  • 10,519
  • 8
  • 40
  • 45
  • That's it, thanks! Together with http://stackoverflow.com/questions/2070293/exception-in-static-initialization-block and rethrowing an exception the solution – S1lentSt0rm Jan 09 '14 at 23:10