dimanche 24 juillet 2022

Strange Pattern in a Java Db Manager, uses Inner Class for creating connections to db

I found a db manager class that uses a strange pattern in a Java project (the project is in production), i am trying to understand it's purpose, the comments left by the author give only hints:

public class MongoDBManagerFactory {

    /**
     * Using thread local and proxies for storing database
     * 
     * One thread = one db connection = one transaction
     */
    final class MongoDBManager implements IMongoManager {

       private MongoClient client = null;
       private DB db = null;
       private Jongo jongo = null;

       /*
        * New instance management
        */

       private MongoDBManager(String domain) {
            // ...code for entering credentials and connecting to the db
            db = client.getDB(domain);
            jongo = new Jongo(db);
       }

       public Jongo getJongo() {
            return jongo;
       }

       public MongoClient getClient() {
            return client;
       }

    }

    /*
     * Singleton Replace by Spring, seam or other later on
     */
    private static MongoDBManagerFactory instance = new MongoDBManagerFactory();

    private Map<String, IMongoManager> mapDBManager = new HashMap<>();

    private MongoDBManagerFactory() {}

    public static MongoDBManagerFactory getInstance() {
        return instance;
    }

    public IMongoManager getManager() {
        IMongoManager mongoManager = null;
        String domain = "dnName";
        if (domain != null && mapDBManager.get(domain) == null) {
            mongoManager = new MongoDBManager(domain);
            mapDBManager.put(domain, mongoManager);
        } else if (domain != null && mapDBManager.get(domain) != null) {
            mongoManager = mapDBManager.get(domain);
        }
        return mongoManager;
    }

}

English is not the first language for whoever wrote this code but they may give an idea about what they were trying to achieve. Questions:

  1. what are they trying to achieve?
  2. What is the purpose of the single threaded connection/transactions?
  3. How using this pattern (whith the inner class and signleton) helps in achieving the above?

Aucun commentaire:

Enregistrer un commentaire