When to use @Singleton in a Jersey resource
- by dexter
I have a Jersey resource that access the database. Basically it opens a database connection in the initialization of the resource. Performs queries on the resource's methods.
I have observed that when I do not use @Singleton, the database is being open at each request. And we know opening a connection is really expensive right?
So my question is, should I specify that the resource be singleton or is it really better to keep it at per request especially when the resource is connecting to the database?
My resource code looks like this:
//Use @Singleton here or not?
@Path(/myservice/)
public class MyResource {
private ResponseGenerator responser;
private Log logger = LogFactory.getLog(MyResource.class);
public MyResource() {
responser = new ResponseGenerator();
}
@GET
@Path("/clients")
public String getClients() {
logger.info("GETTING LIST OF CLIENTS");
return responser.returnClients();
}
...
// some more methods
...
}
And I connect to the database using a code similar to this:
public class ResponseGenerator {
private Connection conn;
private PreparedStatement prepStmt;
private ResultSet rs;
public ResponseGenerator(){
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:testdb");
}
public String returnClients(){
String result;
try{
prepStmt = conn.prepareStatement("SELECT * FROM hosts");
rs = prepStmt.executeQuery();
...
//do some processing here
...
} catch (SQLException se){
logger.warn("Some message");
} finally {
rs.close();
prepStmt.close();
// should I also close the connection here (in every method) if I stick to per request
// and add getting of connection at the start of every method
// conn.close();
}
return result
}
...
// some more methods
...
}
Some comments on best practices for the code will also be helpful.