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 6016443
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T02:58:59+00:00 2026-05-23T02:58:59+00:00

I have a class MyClass that has a static variable. Class implements smth like

  • 0

I have a class MyClass that has a static variable. Class implements smth like singleton(it has java.sql.DataSource as static variable and has method getConnection() which checks whether DataSource variable is not null and if it is null – obtains the connection, else – return dataSource.getConnection())
When I call MyClass.getConnection() method for the first time the class is loaded to the memory and DataSource variable is obtained. Will this class stay in memory while the program is running or it will be garbage collected when the control flow of the program will exit outside the method where MyClass.getConnection() was invoked?
Actually I want to know whether I have to obtain Connection object in each method(obtaining connection object is rather long operation, isn’t it?) where I use it or only once in some place?

edit
This is my class that obtains a connection

public class ResourceManager {

    private static DataSource dataSource;


    public static synchronized Connection getConnection() throws NamingException, SQLException {
        if (dataSource == null) {
            Locale.setDefault(Locale.ENGLISH);
            Context context = (Context) new InitialContext().lookup("java:comp/env");
            dataSource = (DataSource) context.lookup("jdbc/Project");
            context.close();
        }
        return dataSource.getConnection();
    }


    public static void close(Connection con) {
        if (con != null)
            try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public static void close(ResultSet rs) {
        if (rs != null)
            try {
            rs.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public static void close(PreparedStatement stmt) {
        if (stmt != null)
            try {
            stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

in this class I obtain connection from tomcat pool

So, if in one method I call ResourseManager.getConnection() and it obtains the datasource, will it be the same datasource when I call this method after some time passed or it will be GC?

P.S. I use close methods in finally blocks

  • 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-23T02:58:59+00:00Added an answer on May 23, 2026 at 2:58 am

    Will this class stay in memory while
    the program is running or it will be
    garbage collected when the control
    flow of the program will exit outside
    the method where
    MyClass.getConnection() was invoked?

    Class objects will become eligible for garbage collection just like any other object – when no references exist to the Class objects. Typically, these references are held by the ClassLoader that loaded the Class in the first place. So, the class will stay as long as the Classloader that references it, is in use. It will not be unloaded after method execution, unless the Classloader was created by the caller, and the reference to the classloader no longer exists.

    In long running applications (like Java EE applications), the class and the classloader (a unique one will typically exist for every application) will not be eligible for garbage collection, until the application itself is brought down.

    The singleton pattern and its effect on GC

    The garbage collection of classes that implement the singleton pattern is a unique situation. The class continues to be referenced by its instance, so it will never be eligible for garbage collection. This could lead to problems where the classloaders themselves may not be garbage collected, especially during application restarts in a container, thus leading to a memory leak. The solution to prevent such a problem, is to destroy the singleton instance in a context listener that listens for the context (application) destruction event.

    Update #2

    For the updated question:

    Actually I want to know whether I have to obtain Connection object in each method(obtaining connection object is rather long operation, isn’t it?) where I use it or only once in some place?

    Obtaining a connection is expensive, but only if you manage the connection. That’s why you use a datasource backed by a connection pool. Everytime you need a connection, the datasource will fetch one from the pool. Once you are done with the connection, you should close it, so that it can be returned to the pool. My advice is to not perform premature optimizations; connection pools are a fact in modern Java EE applications, and application servers perform enough optimization to ensure that there is very little latency here. IMHO, a properly tuned pool will give you better performance than a hand-crafted class put in place to centralize access to connection objects.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class with static method which has a local static variable. I
Okay, newbie multi-threading question: I have a Singleton class. The class has a Static
I have a class that has a Generic type G In my class model
I have a class that subclasses NSMutableArray. I init it using: MyClass class =
I have a generic class public MyClass<TContext, T> where TContext : DataContext that effectively
I have a ton of repeating code in my class that looks like the
I have: class MyClass extends MyClass2 implements Serializable { //... } In MyClass2 is
I have a class like this: public class myClass { public List<myOtherClass> anewlist =
let's say we have a c++ class like: class MyClass { void processArray( <an
If you have a class that has some named constants, what is the best

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.