Try구문 괄호에 Autoclosable을 implement한 소캣 객체가 들어갈 경우 try 구문이 끝나면서 알아서 소캣도 닫치는 점을 이용함.

JDK 7버전부터 가능해진 구문임.




package jdbc;


import java.sql.Connection;

import java.sql.DriverManager;


//Template Method Pattern

public abstract class ConnectAgent3 {

static final String path = "jdbc:oracle:thin:@thinker.ipdisk.co.kr:1521:orcl";

static final String userId = "user00";

static final String userPw = "user00";

public void execute() throws Exception {

try(Connection con2=  DriverManager.getConnection(path, userId, userPw);

) {

doJob();

System.out.println(con);

}

}

protected abstract void doJob() throws Exception;

}


------------------------------------------------------------------------------------------------

Connection이 제대로 닫히는지 보여주기 위한 예제


package jdbc;

import java.sql.Connection;

import java.sql.DriverManager;


//Template Method Pattern

public abstract class ConnectAgent3 {

static final String path = "jdbc:oracle:thin:@thinker.ipdisk.co.kr:1521:orcl";

static final String userId = "user00";

static final String userPw = "user00";

public void execute() throws Exception {

Connection con = null;

try(Connection con2=  DriverManager.getConnection(path, userId, userPw);

) {

con = con2;

doJob();

System.out.println(con);

}

System.out.println(con.isClosed());

}

protected abstract void doJob() throws Exception;

}



------------------------------------------------------------------------------------

Test용 Class



package jdbc;

//Template Method Pattern

public class ConnectTest3 implements Runnable {

public void makeConnection() throws Exception {

new ConnectAgent3() { 

@Override

protected void doJob() throws Exception {

System.out.println("Doing Job...");

}

}.execute();

}

@Override

public void run() {

try {

makeConnection();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void main(String[] args) {

ConnectTest3 c = new ConnectTest3();

for (int i=0; i<10; i++) {

Thread t = new Thread(c);

t.start();

}

}

}



Posted by 타다키치

댓글을 달아 주세요