S1lentSt0rm
S1lentSt0rm

Reputation: 2039

Initialize Database in Jersey Resource

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.

Upvotes: 1

Views: 244

Answers (1)

user987339
user987339

Reputation: 10707

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.

Upvotes: 1

Related Questions