Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

What's a "static factory" method?

1 Answer

0 votes
by (46k points)

We avoid presenting a direct path to database connections because they're resource-intensive. So we use a static factory method to get a connection that forms a connection if we're beneath the limit. Unless, it tries to present a "spare" connection, failing with an exemption if there are none.

public class DbConnection{

   private static final int MAX_CONNS = 100;

   private static int totalConnections = 0;

   private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();

   private DbConnection(){

     // ...

     totalConnections++;

   }

   public static DbConnection getDbConnection(){

     if(totalConnections < MAX_CONNS){

       return new DbConnection();

     }else if(availableConnections.size() > 0){

         DbConnection dbc = availableConnections.iterator().next();

         availableConnections.remove(dbc);

         return dbc;

     }else {

         throw new NoDbConnections();

     }

   }

   public static void returnDbConnection(DbConnection dbc){

     availableConnections.add(dbc);

     //...

   }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...