mercredi 29 avril 2020

Question regarding the implementation of a connection pool

I was asked in an interview the below question. The code given to me is

interface Connection {
    void execute();
    void close();
}


interface ConnectionPool {
    Connection getConnection();
}

class Client {

    ConnectionPool connectionPool = new MyConnectionPool() ;

    Connection connection  = connectionPool.getConnection();

    public void execute() {
        try{
        connection.execute();
    }finally {
            connection.close();
        }
    }
}

class MyConnectionPool implements ConnectionPool {

    MyConnectionPool(List<Connection> connections) {

    }
    @Override
    public Connection getConnection() {
        return null;
    }
}

Here the implementation of the Connection is done by somebody else, I can only change the MyConnection pool class or create new classes. The issue is whenever the client call connection.close, the connection object is actually closed, the requirement is instead it should be added back to the connection pool which somebody else can use.

My implementation is like

class MyConnectionPool implements ConnectionPool {

    Queue<Connection> connections;

    MyConnectionPool(List<Connection> connections) {
        this.connections = new LinkedList(connections);
    }
    @Override
    public Connection getConnection() {
        MyConnection connection = new MyConnection(connections.poll(), this);
        return connection;
    }

    public void closeConnection(Connection connection) {
        connections.add(connection);
    }
}

class MyConnection implements Connection {


    Connection connection;
    boolean isClosed = false;
    MyConnectionPool connectionPool;

    MyConnection(Connection connection, MyConnectionPool connectionPool) {
        this.connection = connection;
    }

    @Override
    public void execute() {
        if (!isClosed){
            connection.execute();
        }
    }

    @Override
    public void close() {
        if (!isClosed) {
            connectionPool.closeConnection(this);
        }

    }
}

Is it correct ? Is there a better way to achieve the same.

Aucun commentaire:

Enregistrer un commentaire