Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4073220
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T16:59:16+00:00 2026-05-20T16:59:16+00:00

Servlets runs in several threads, so my question is: If I have a lot

  • 0

Servlets runs in several threads, so my question is:

If I have a lot of servlets which call some utility class (DbUtils, for example

Connection c = DbUtils.getConnection();
//....some action with db here

should I assume additional actions for synchronization inside DbUtils?

Actually I’d like to inherit HttpServlet into something like DatabaseInvokerServlet:

public abstract class DatabaseInvokerServlet extends HttpServlet

with methods:

public abstract void getResultSets(Connection connection) throws SQLException;
private AbstractUser currentUser;
private HttpServletRequest request;
private HttpServletResponse response;
protected void processData() {}
protected void afterRequestProcessed() throws ServletException, IOException {}
protected void beforeRequestProcessed() throws ServletException, IOException {}

protected void execute() {
    Connection c = null;
    try {
        c = DbUtils.getConnection();
        getResultSets(c);
        processData();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public HttpServletRequest getRequest() {
    return request;
}

public HttpServletResponse getResponse() {
    return response;
}

public AbstractUser getCurrentUser() {
    return currentUser;
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");


    this.request = request;
    this.response = response;
    this.currentUser = (AbstractUser) request.getSession().getAttribute("currentUser");

}

Then I’d just inherit my DatabaseInvokerServlet to new servlets to do custom stuff. The reason is not to copy-paste database invoke block with try-catch-finally in a lot of places.

But as I can see such approach won’t work because of synchronization issues. Am I right?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T16:59:17+00:00Added an answer on May 20, 2026 at 4:59 pm

    If the DbUtils creates the connection in the same thread, like as:

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    

    Then it’s threadsafe.

    But if the connection is a class variable, like as:

    private static Connection connection = DriverManager.getConnection(url, username, password);
    
    public static Connection getConnection() throws SQLException {
        return connection;
    }
    

    Then it is definitely not threadsafe because the same connection will be shared among all threads. Also when it’s closed in a thread, all subsequent threads won’t be able to use the connection because it’s not open anymore. Also when it’s never closed, the DB will timeout the connection sooner or later, usually after a few hours, and your application won’t work anymore because the connection is not open anymore.


    As to the servlet,

    public abstract class DatabaseInvokerServlet extends HttpServlet {
        private AbstractUser currentUser;
        private HttpServletRequest request;
        private HttpServletResponse response;
        // ...
    }
    

    it’s definitely not threadsafe. You’re assigning the current user, request and response as instance variables. From each servlet class, there is only one instance during the application’s lifetime. This instance is shared among all visitors/sessions throughout the entire application’s lifetime. Each HTTP request operates in a separate thread and uses the same instance.

    Imagine two simultaneous visitors: visitor A will set the current user, request and response. The DB process however takes a long time. Before the response of visitor A has returned, visitor B calls the same servlet and thus the current user, request and response will be overriden. Then, the query of visitor A finishes and wants to write to the response, it is instead writing to the response of visitor B! Visitor B sees the result of the query of visitor A and visitor A sees nothing on his screen!

    You should never assign request/session-specific data as instance variable of the servlet. You should keep them method (thread) local.

    public abstract class DatabaseInvokerServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AbstractUser currentUser = request.getSession().getAttribute("user");
            // Keep the variables in the method block! 
            // Do not assign them as instance variable!
        }
    }
    

    As to the complete picture, this approach is clumsy. The database access layer should have nothing to do with servlets. It should operate in its own standalone classes which you could just construct/invoke in every other Java class, any servlet class, or a normal application with main(), or whatever. You should not have any single line of java.sql.* imports in your servlet classes (expect of maybe SQLException if it is not abstracted away). You should not have any single line of javax.servlet.* imports in your database classes.

    See also:

    • Servlet instantiation and (session) variables
    • Basic DAO tutorial
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have inherited a Java application (servlets) that runs under Tomcat. For historical reasons,
I have a server behind a firewall. It runs a web application (Java servlets
I am developing a web app using servlets and jsps. I have a question
I have developed a simple server using Tomcat which runs a servlet. The servlet
I have a Eclipse Dynamic Web Project which host a simple servlet and runs
I have two servlets which are running on different tomcat servers. I and trying
I am new to Servlets. I want to use a method which is called
I have servlets that caches user information rather then retrieving it from the user
I've inherited a web project (Servlets) which is currently build inside eclipse. I want
I am currently doing some work for a company that runs a legacy web

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.