Recently I attended interview in java, the interviewer asked a question like below:
I have a request which go throgh A,B,C modules and response go back throgh A , in module A I need to talk to database and again in module C I need to talk to database, so in this situation how many connections you will open and where do you close those connections?
My Answer: I said that in module A I will open a connection and I will close it then and there, then control go to module B then module C, in module C again I will open one more connection and i will close it again. then he asked me again another question I want to open one connection per one request processing, how can i do this?
Sharing the connection in the modules.
EDIT You can share the connection by passing it to the different modules:
class ModuleA {
void process(){
Connection c = getConnection();
doA();
new ModuleB( c ).doBs();
new ModuleC( c ).doCs();
doSomeMoreA();
c.close();
}
}
You can also have the connection in a external class and search for it when needed ( perhaps using a sessionid )
I'm not sure if this counts as "Connection pooling"
Here's it anyway.
class Db {
private static Map<Integer, Connection> map;
public static Connection getConnection( int sessionId ){
if( !map.containsKey( sessionId ) ) {
map.put( sessionId, createConnection());
}
return map.get( sessionId );
}
}
class Main {
void processs() {
int sessionId = createSesionId();
ModuleA a = new ModuleA( sessionId );
a.doAsStuff();
ModuleB b = new ModuleB( sessionId );
b.doBsStuff();
ModuleC c = new ModuleC( sessionId );
b.doCsStuff();
a.closeTransaction();
}
}
class ModuleA{
public doAsStuff() {
Connection c = Db.getConnection(sessionId);
doSomethingWith( c );
}
public closeTransaction() {
Connection c = Db.getConnection(sessionId);
c.close();
}
}
class ModuleB{
public doBsStuff() {
Connection c = Db.getConnection(sessionId);
doSomethingWith( c );
}
}
class ModuleC{
public doCsStuff() {
Connection c = Db.getConnection(sessionId);
doSomethingWith( c );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With