I'm trying to create a simple API Backend using Jetty and HttpServlets. I've read here and here about the details of thread safety with HttpServlets The general consensus seems to be that this is the proper way to deal with variable access in HttpServlerts:
public class MyServlet extends HttpServlet {
private static Object thisIsNotThreadsafe;
private Object thisIsAlsoNotThreadsafe;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object thisIsThreadsafe;
thisIsNotThreadsafe = request.getParameter("foo"); // BAD! Shared among all requests.
thisIsAlsoNotThreadsafe = request.getParameter("foo"); // BAD! Shared among all requests.
thisIsThreadsafe = request.getParameter("foo"); // Good.
}
}
What I'm trying to do is create a new MongoClient:
MongoClient mongoClient = new MongoClient("localhost", 27017);
I could make this a "global variable", but that wouldn't be threadsafe. I could make a new instance everytime doGet
or doPost
is called. But MongoDB's Java Driver Documentation seems to advise against that as well:
A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.
What's the best way to go about this?