블로그 이미지
좋은느낌/원철
이것저것 필요한 것을 모아보렵니다.. 방문해 주셔서 감사합니다..

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

    2008. 6. 30. 17:47 개발/Java
    출처 : http://msinterdev.org/blog/archive/200804?TSSESSIONmsinterdevorgblog=7701d2cc7e6ea2d431e379532dd3888d

    서블렛 + JDBC 연동시 코딩 고려사항 -제2탄-
    [JDBC Connection Pooling]

    최근수정일자 : 2001.01.19
    최근수정일자 : 2001.03.20(샘플예제추가)
    최근수정일자 : 2001.10.22(디버깅을 위한 로직추가)
    최근수정일자 : 2001.10.29(Oracle JDBC2.0 샘플추가)
    최근수정일자 : 2001.11.08(윤한성님 도움 OracleConnectionCacheImpl 소스수정)
    최근수정일자 : 2001.11.09(Trace/Debugging을 위한 장문의 사족을 담)

    5. JDBC Connection Pooling 을 왜 사용해야 하는가 ?

     Pooling 이란 용어는 일반적인 용어입니다. Socket Connection Pooling, Thread
     Pooling, Resource Pooling 등 "어떤 자원을 미리 Pool 에 준비해두고 요청시 Pool에
     있는 자원을 곧바로 꺼내어 제공하는 기능"인 거죠.

     JDBC Connection Pooling 은 JDBC를 이용하여 자바에서 DB연결을 할 때, 미리 Pool에
     물리적인 DB 연결을 일정개수 유지하여 두었다가 어플리케이션에서 요구할 때 곧바로
     제공해주는 기능을 일컫는 용어입니다. JDBC 연결시에, (DB 종류마다, 그리고 JDBC
     Driver의 타입에 따라 약간씩 다르긴 하지만 ) 대략 200-400 ms 가 소요 됩니다. 기껏
     0.2 초 0.4 초 밖에 안되는 데 무슨 문제냐 라고 반문할수도 있습니다.
     
     하지만, 위 시간은 하나의 연결을 시도할 때 그러하고, 100 - 200개를 동시에 연결을
     시도하면 얘기가 완전히 달라집니다.

     아래는 직접 JDBC 드라이버를 이용하여 연결할 때와 JDBC Connection Pooling 을 사용
     할 때의 성능 비교 결과입니다.


     ------------------------------------------------------------------
     테스트 환경
     LG-IBM 570E Notebook(CPU:???MHz , MEM:320MB)
     Windows NT 4.0 Service Pack 6
     IBM WebSphere 3.0.2.1 + e-Fixes
     IBM HTTP Server 1.3.6.2
     IBM UDB DB2 6.1

     아래에 첨부한 파일는 자료를 만들때 사용한 JSP소스입니다. (첨부파일참조)

     [HttpConn.java] 간단한 Stress Test 프로그램


     아래의 수치는 이 문서 이외에는 다른 용도로 사용하시면 안됩니다. 테스트를 저의
     개인 노트북에서 측정한 것이고, 또한 테스트 프로그램 역시 직접 만들어한 것인
     만큼, 공정성이나 수치에 대한 신뢰를 부여할 수는 없습니다.
     그러나 JDBC Connection Pooling 적용 여부에 따른 상대적인 차이를 설명하기에는
     충분할 것 같습니다.

     테스트 결과

     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     매번 직접 JDBC Driver 연결하는 경우
     java HttpConn http://localhost/db_jdbc.jsp -c <동시유저수> -n <호출횟수> -s 0

     TOTAL( 1,10)  iteration=10 ,  average=249.40 (ms),   TPS=3.93
     TOTAL(50,10)  iteration=500 , average=9,149.84 (ms), TPS=4.83
     TOTAL(100,10)  iteration=1000 , average=17,550.76 (ms), TPS=5.27
     TOTAL(200,10)  iteration=2000 , average=38,479.03 (ms), TPS=4.89
     TOTAL(300,10)  iteration=3000 , average=56,601.89 (ms), TPS=5.01

     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     DB Connection Pooing 을 사용하는 경우
     java HttpConn http://localhost/db_pool_cache.jsp -c <동시유저수> -n <호출횟수> -s 0

     TOTAL(1,10)  iteration=10 , average=39.00 (ms), TPS=23.26
     TOTAL(1,10)  iteration=10 , average=37.10 (ms), TPS=24.33
     TOTAL(50,10)  iteration=500 , average=767.36 (ms), TPS=45.27
     TOTAL(50,10)  iteration=500 , average=568.76 (ms), TPS=61.26
     TOTAL(50,10)  iteration=500 , average=586.51 (ms), TPS=59.79
     TOTAL(50,10)  iteration=500 , average=463.78 (ms), TPS=67.02
     TOTAL(100,10)  iteration=1000 , average=1,250.07 (ms), TPS=57.32
     TOTAL(100,10)  iteration=1000 , average=1,022.75 (ms), TPS=61.22
     TOTAL(200,10)  iteration=1462 , average=1,875.68 (ms), TPS=61.99
     TOTAL(300,10)  iteration=1824 , average=2,345.42 (ms), TPS=61.51

     NOTE: average:평균수행시간, TPS:초당 처리건수
     ------------------------------------------------------------------

     즉, JDBC Driver 를 이용하여 직접 DB연결을 하는 구조는 기껏 1초에 5개의 요청을
     처리할 수 있는 능력이 있는 반면, DB Connection Pooling 을 사용할 경우는 초당
     60여개의 요청을 처리할 수 있는 것으로 나타났습니다.
     12배의 성능향상을 가져온거죠. (이 수치는 H/W기종과 측정방법, 그리고 어플리케이션에
     따라 다르게 나오니 이 수치자체에 너무 큰 의미를 두진 마세요)


     주의: 흔히 "성능(Performance)"을 나타낼 때, 응답시간을 가지고 얘기하는 경향이
      있습니다. 그러나 응답시간이라는 것은 ActiveUser수가 증가하면 당연히 그에 따라
      느려지게 됩니다. 반면 "단위시간당 처리건수"인 TPS(Transaction Per Second) 혹은
      RPS(Request Per Second)는 ActiveUser를 지속적으로 끌어올려 임계점을 넘어서면,
      특정수치 이상을 올라가지 않습니다. 따라서 성능을 얘기할 땐 평균응답시간이 아니라
      "단위시간당 최대처리건수"를 이야기 하셔야 합니다.
      성능(Performance)의 정의(Definition)은 "단위시간당 최대처리건수"임을 주지하세요.
      성능에 관련한 이론은 아래의 문서를 통해, 함께 연구하시지요.
      [강좌]웹기반시스템하에서의 성능에 대한 이론적 고찰
      http://www.javaservice.net/~java/bbs/read.cgi?m=resource&b=consult&c=r_p&n=1008701211

     PS: IBM WebSphere V3 의 경우, Connection 을 가져올 때, JNDI를 사용하게 되는데
       이때 사용되는 DataSource 객체를 매번 initialContext.lookup() 을 통해 가져오게
       되면, 급격한 성능저하가 일어납니다.(NOTE: V4부터는 내부적으로 cache를 사용하여
       성능이 보다 향상되었습니다)
       DataSource를 매 요청시마다 lookup 할 경우 다음과 같은 결과를 가져왔습니다.

       java HttpConn http://localhost/db_pool.jsp -c <동시유저수> -n <호출횟수> -s 0

       TOTAL(1,10)  iteration=10 , average=80.00 (ms), TPS=11.61
       TOTAL(50,10)  iteration=500 , average=2,468.30 (ms), TPS=16.98
       TOTAL(50,10)  iteration=500 , average=2,010.43 (ms), TPS=18.18
       TOTAL(100,10)  iteration=1000 , average=4,377.24 (ms), TPS=18.16
       TOTAL(200,10)  iteration=1937 , average=8,991.89 (ms), TPS=18.12

       TPS 가 18 이니까 DataSource Cache 를 사용할 때 보다 1/3 성능밖에 나오지 않는 거죠.



    6. JDBC Connection Pooling 을 사용하여 코딩할 때 고려사항

     JDBC Connecting Pooling은 JDBC 1.0 스펙상에 언급되어 있지 않았습니다. 그러다보니
     BEA WebLogic, IBM WebSphere, Oracle OAS, Inprise Server, Sun iPlanet 등 어플리케
     이션 서버라고 불리는 제품들마다 그 구현방식이 달랐습니다.
     인터넷에서 돌아다니는 Hans Bergsten 이 만든 DBConnectionManager.java 도 그렇고,
     JDF 에 포함되어 있는 패키지도 그렇고 각자 독특한 방식으로 개발이 되어 있습니다.
     
     JDBC를 이용하여 DB연결하는 대표적인 코딩 예를 들면 다음과 같습니다.
     
     ------------------------------------------------------------------
     [BEA WebLogic Application Server]

        import java.sql.*;

        // Driver loading needed.
        static {
          try {
            Class.forName("weblogic.jdbc.pool.Driver").newInstance();          
          }
          catch (Exception e) {
            ...
          }
        }

        ......

        Connection conn = null;
        Statement stmt = null;
        try {
          conn = DriverManager.getConnection("jdbc:weblogic:pool:<pool_name>", null);
          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( conn != null ) try{conn.close();}catch(Exception e){}
        }


     ------------------------------------------------------------------
     IBM WebSphere Application Server 3.0.2.x / 3.5.x

        /* IBM WebSphere 3.0.2.x for JDK 1.1.8 */
        //import java.sql.*;
        //import javax.naming.*;
        //import com.ibm.ejs.dbm.jdbcext.*;
        //import com.ibm.db2.jdbc.app.stdext.javax.sql.*;

        /* IBM WebSphere 3.5.x for JDK 1.2.2 */
        import java.sql.*;
        import javax.sql.*;
        import javax.naming.*;

        // DataSource Cache 사용을 위한 ds 객체 static 초기화
        private static DataSource ds = null;
        static {
          try {
            java.util.Hashtable props = new java.util.Hashtable();
            props.put(Context.INITIAL_CONTEXT_FACTORY,
                      "com.ibm.ejs.ns.jndi.CNInitialContextFactory");
            Context ctx = null;
            try {
              ctx = new InitialContext(props);
              ds = (DataSource)ctx.lookup("jdbc/<data_source_name>");
            }
            finally {
              if ( ctx != null ) ctx.close();
            }
          }
          catch (Exception e) {
           ....
          }
        }

        .....   

        Connection conn = null;
        Statement stmt = null;
        try {
          conn = ds.getConnection("userid", "password");
          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( conn != null ) try{conn.close();}catch(Exception e){}
        }

     ------------------------------------------------------------------
     IBM WebSphere Application Server 2.0.x
     
        import java.sql.*;
        import com.ibm.servlet.connmgr.*;


        // ConnMgr Cache 사용을 위한 connMgr 객체 static 초기화

        private static IBMConnMgr connMgr = null;
        private static IBMConnSpec    spec = null;
        static {
          try {
            String poolName = "JdbcDb2";  // defined in WebSphere Admin Console
            spec = new IBMJdbcConnSpec(poolName, false,  
                  "com.ibm.db2.jdbc.app.DB2Driver",
                  "jdbc:db2:<db_name>",   // "jdbc:db2://ip_address:6789/<db_name>",
                  "userid","password");                    
            connMgr = IBMConnMgrUtil.getIBMConnMgr();
          }
          catch(Exception e){
            .....
          }
        }

        .....

        IBMJdbcConn cmConn = null; // "cm" maybe stands for Connection Manager.
        Statement stmt = null;
        try {
          cmConn = (IBMJdbcConn)connMgr.getIBMConnection(spec);    
          Connection conn = jdbcConn.getJdbcConnection();
          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( cmConn != null ) try{cmConn.releaseIBMConnection();}catch(Exception e){}
        }
        // NOTE: DO NOT "conn.close();" !!


     ------------------------------------------------------------------
     Oracle OSDK(Oracle Servlet Development Kit)

        import java.sql.*;
        import oracle.ec.ctx.*;


        .....
        
        oracle.ec.ctx.Trx trx = null;
        Connection conn = null;
        Statement stmt = null;
        try {
          oracle.ec.ctx.TrxCtx ctx = oracle.ec.ctx.TrxCtx.getTrxCtx();
          trx = ctx.getTrx();
          conn = trx.getConnection("<pool_name>");
          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( conn != null ) try{ trx.close(conn,"<pool_name>");}catch(Exception e){}
        }
        // NOTE: DO NOT "conn.close();" !!


     ------------------------------------------------------------------
     Hans Bergsten 의 DBConnectionManager.java

        import java.sql.*;

        .....
        
        db.DBConnectionManager connMgr = null;
        Connection conn = null;
        Statement stmt = null;
        try {
          connMgr = db.DBConnectionManager.getInstance();
          conn = connMgr.getConnection("<pool_name>");
          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( conn != null ) connMgr.freeConnection("<pool_name>", conn);
        }
        // NOTE: DO NOT "conn.close();" !!

     ------------------------------------------------------------------
     JDF 의 DB Connection Pool Framework

        import java.sql.*;
        import com.lgeds.jdf.*;
        import com.lgeds.jdf.db.*;
        import com.lgeds.jdf.db.pool.*;


        private static com.lgeds.jdf.db.pool.JdbcConnSpec spec = null;
        static {
          try {
            com.lgeds.jdf.Config conf = new com.lgeds.jdf.Configuration();
            spec =  new com.lgeds.jdf.db.pool.JdbcConnSpec(
                 conf.get("gov.mpb.pbf.db.emp.driver"),
                 conf.get("gov.mpb.pbf.db.emp.url"),
                 conf.get("gov.mpb.pbf.db.emp.user"),
                 conf.get("gov.mpb.pbf.db.emp.password")
              );
          }
          catch(Exception e){
            .....
          }
        }

        .....

        PoolConnection poolConn = null;
        Statement stmt = null;
        try {
          ConnMgr mgr = ConnMgrUtil.getConnMgr();
          poolConn = mgr.getPoolConnection(spec);
          Connection conn = poolConnection.getConnection();
          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( poolConn != null ) poolConn.release();
        }
        // NOTE: DO NOT "conn.close();" !!

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


     여기서 하고픈 얘기는 DB Connection Pool 을 구현하는 방식에 따라서 개발자의 소스도
     전부 제 각기 다른 API를 사용해야 한다는 것입니다.
     프로젝트를 이곳 저곳 뛰어 본 분은 아시겠지만, 매 프로젝트마나 어플리케이션 서버가
     다르고 지난 프로젝트에서 사용된 소스를 새 프로젝트에 그대로 적용하지 못하게 됩니다.
     JDBC 관련 API가 다르기 때문이죠.
     같은 제품일지라도 버전업이 되면서 API가 변해버리는 경우도 있습니다. 예를 들면,
     IBM WebSphere 버전 2.0.x에서 버전 3.0.x로의 전환할 때, DB 연결을 위한 API가
     변해버려 기존에 개발해둔 400 여개의 소스를 다 뜯어 고쳐야 하는 것과 같은 상황이
     벌어질 수도 있습니다.
     닷컴업체에서 특정 패키지 제품을 만들때도 마찬가지 입니다. 자사의 제품이 어떠한
     어플리케이션 서버에서 동작하도록 해야 하느냐에 따라 코딩할 API가 달라지니 소스를
     매번 변경해야만 하겠고, 특정 어플리케이션 서버에만 동작하게 하려니 마켓시장이
     좁아지게 됩니다.
     IBM WebSphere, BEA WebLogic 뿐만 아니라 Apache JServ 나 JRun, 혹은 Tomcat 에서도
     쉽게 포팅하길 원할 것입니다.

     이것을 해결하는 방법은 우리들 "SE(System Engineer)"만의 고유한 "Connection Adapter
     클래스"를 만들어서 사용하는 것입니다.

     예를 들어 개발자의 소스는 이제 항상 다음과 같은 유형으로 코딩되면 어떻겠습니까 ?


        -----------------------------------------------------------
        .....
        ConnectionResource resource = null;
        Statement stmt = null;
        try {
          resource = new ConnectionResource();
          Connection conn = resource.getConnection();

          stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select ....");
          while(rs.next()){
            .....
          }
          rs.close();
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( resource != null ) resource.release();
        }
        // NOTE: DO NOT "conn.close();" !!
        -----------------------------------------------------------



     이 때 ConnectionResource 는 다음과 같은 형식으로 누군가 한분이 만들어 두면 되겠죠.

        -----------------------------------------------------------
        import java.sql.*;
        public class ConnectionResource
        {
          private java.sql.Connection conn = null;
          public ConnectionResource() throws Exception {
             ......
             conn =  ..... GET Connection by Connection Pooling API
          }
          public Connection getConnection() throws Exception {
             return conn;
          }
          public void release(){
             // release conn into "Connection Pool"
             .......
          }
        }
        -----------------------------------------------------------



      예를 들어 IBM WebSphere Version 3.0.2.x 의 경우를 든다면 다음과 같이 될 겁니다.

      -----------------------------------------------------------
      package org.jsn.connpool;
      /*
       * ConnectionResource V 1.0
       * JDBC Connection Pool Adapter for IBM WebSphere V 3.0.x/3.5.x
       * Author: WonYoung Lee, javaservice@hanmail.net, 011-898-7904
       * Last Modified : 2000.11.10
       * NOTICS: You can re-distribute or copy this source code freely,
       *         you can NOT remove the above subscriptions.
      */

      /* IBM WebSphere 3.0.2.x for JDK 1.1.8 */
      //import java.sql.*;
      //import javax.naming.*;
      //import com.ibm.ejs.dbm.jdbcext.*;
      //import com.ibm.db2.jdbc.app.stdext.javax.sql.*;

      /* IBM WebSphere 3.5.x for JDK 1.2.2 */
      import java.sql.*;
      import javax.sql.*;
      import javax.naming.*;

      public class ConnectionResource
      {
         private static final String userid = "userid";
         private static final String password = "password"
         private static final String datasource = "jdbc/<data_source_name>";
         private static DataSource ds = null;

         private java.sql.Connection conn = null;

         public ConnectionResource() throws Exception {
           synchronized ( ConnectionResource.class ) {
             if ( ds == null ) {
               java.util.Hashtable props = new java.util.Hashtable();
               props.put(Context.INITIAL_CONTEXT_FACTORY,
                  "com.ibm.ejs.ns.jndi.CNInitialContextFactory");
               Context ctx = null;
               try {
                 ctx = new InitialContext(props);
                 ds = (DataSource)ctx.lookup("jdbc/<data_source_name>");
               }
               finally {
                 if ( ctx != null ) ctx.close();
               }
             }
           }
           conn =  ds.getConnection( userid, password );
         }
         public Connection getConnection() throws Exception {
            if ( conn == null ) throw new Exception("Connection is NOT avaiable !!");
            return conn;
         }
         public void release(){
            // release conn into "Connection Pool"
            if ( conn != null ) try { conn.close(); }catch(Excepton e){}
            conn = null;
         }
       }
       -----------------------------------------------------------
              


     
      만약 Hans Bersten 의 DBConnectionManager.java 를 이용한 Connection Pool 이라면
      다음과 같이 만들어 주면 됩니다.

       -----------------------------------------------------------
       package org.jsn.connpool;
       import java.sql.*;
       public class ConnectionResource
       {
          private String poolname = "<pool_name>";
          private Connection conn = null;
          private db.DBConnectionManager connMgr = null;

          public ConnectionResource() throws Exception {
             connMgr = db.DBConnectionManager.getInstance();
             conn =  connMgr.getConnection(poolname);
          }
          public Connection getConnection() throws Exception {
             if ( conn == null ) throw new Exception("Connection is NOT avaiable !!");
             return conn;
          }
          public void release(){
             if ( conn != null ) {
               // Dirty Transaction을 rollback시키는 부분인데, 생략하셔도 됩니다.
               boolean autoCommit = true;
               try{ autoCommit = conn.getAutoCommit(); }catch(Exception e){}
               if ( autoCommit == false ) {
                 try { conn.rollback(); }catch(Exception e){}
                 try { conn.setAutoCommit(true); }catch(Exception e){}
               }

               connMgr.freeConnection(poolname, conn);
               conn = null;
             }
          }
       }
       -----------------------------------------------------------


      또, Resin 1.2.x 의 경우라면 다음과 같이 될 겁니다.
      -----------------------------------------------------------
      package org.jsn.connpool;
      /*
       * ConnectionResource V 1.0
       * JDBC Connection Pool Adapter for Resin 1.2.x
       * Author: WonYoung Lee, javaservice@hanmail.net, 011-898-7904
       * Last Modified : 2000.10.18
       * NOTICS: You can re-distribute or copy this source code freely,
       *         you can NOT remove the above subscriptions.
      */
      import java.sql.*;
      import javax.sql.*;
      import javax.naming.*;
      public class ConnectionResource
      {
         private static final String datasource = "jdbc/<data_source_name>";
         private static final String userid = "userid";
         private static final String password = "password"
         private static DataSource ds = null;

         private java.sql.Connection conn = null;

         public ConnectionResource() throws Exception {
            synchronized ( ConnectionResource.class ) {
              if ( ds == null ) {
                Context env = (Context) new InitialContext().lookup("java:comp/env");
                ds = (DataSource) env.lookup(datasource);
              }
            }    
            conn =  ds.getConnection( userid, password );
         }
         public Connection getConnection() throws Exception {
            if ( conn == null ) throw new Exception("Connection is NOT avaiable !!");
            return conn;
         }
         public void release(){
            // release conn into "Connection Pool"
            if ( conn != null ) try { conn.close(); }catch(Excepton e){}
            conn = null;
         }
       }
       -----------------------------------------------------------


      Oracle 8i(8.1.6이상)에서 Oracle의 JDBC 2.0 Driver 자체가 제공하는 Connection
      Pool을 이용한다면 다음과 같이 될 겁니다.
      -----------------------------------------------------------
      package org.jsn.connpool;
      /*
       * ConnectionResource V 1.0
       * JDBC Connection Pool Adapter for Oracle JDBC 2.0
       * Author: WonYoung Lee, javaservice@hanmail.net, 011-898-7904
       * Last Modified : 2001.10.29
       * NOTICS: You can re-distribute or copy this source code freely,
       *         but you can NOT remove the above subscriptions.
      */
      import java.sql.*;
      import javax.sql.*;
      import oracle.jdbc.driver.*;
      import oracle.jdbc.pool.*;

      public class ConnectionResource
      {
         private static final String dbUrl = "jdbc:oracle:thin@192.168.0.1:1521:ORCL";
         private static final String userid = "userid";
         private static final String password = "password"
         private static OracleConnectionCacheImpl oraclePool = null;
         private static boolean initialized = false;

         private java.sql.Connection conn = null;

         public ConnectionResource() throws Exception {
            synchronized ( ConnectionResource.class ) {
              if ( initialized == false ) {
                DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
                oraclePool = new OracleConnectionCacheImpl();
                oraclePool.setURL(dbUrl);
                oraclePool.setUser(userid);
                oraclePool.setPassword(password);
                oraclePool.setMinLimit(10);
                oraclePool.setMaxLimit(50);
                //oraclePool.setCacheScheme(OracleConnectionCacheImpl.FIXED_WAIT_SCHEME);
                // FIXED_WAIT_SCHEME(default), DYNAMIC_SCHEME, FIXED_RETURN_NULL_SCHEME
                //oraclePool.setStmtCacheSize(0); //default is 0

                initialized = true;
              }
            }    
            conn = oraclePool.getConnection();
         }
         public Connection getConnection() throws Exception {
            if ( conn == null ) throw new Exception("Connection is NOT avaiable !!");
            return conn;
         }
         public void release(){
            // release conn into "Connection Pool"
            if ( conn != null ) try { conn.close(); }catch(Exception e){}
            conn = null;
         }
       }
       -----------------------------------------------------------

      또한 설령 Connection Pool 기능을 지금을 사용치 않더라도 향후에 적용할 계획이
      있다면, 우선은 다음과 같은 Connection Adapter 클래스를 미리 만들어 두고 이를
      사용하는 것이 효과적입니다. 향후에 이 클래스만 고쳐주면 되니까요.
      Oracle Thin Driver를 사용하는 경우입니다.

      -----------------------------------------------------------
      import java.sql.*;
      public class ConnectionResource
      {
         private static final String userid = "userid";
         private static final String password = "password"
         private static final String driver = "oracle.jdbc.driver.OracleDriver"
         private static final String url = "jdbc:oracle:thin@192.168.0.1:1521:ORCL";
         private static boolean initialized = false;

         private java.sql.Connection conn = null;

         public ConnectionResource() throws Exception {
            synchronized ( ConnectionResource.class ) {
              if ( initialized == false ) {
                  Class.forName(driver);
                  initialized = true;
              }
            }
            conn = DriverManager.getConnection( url, userid, password );
         }
         public Connection getConnection() throws Exception {
            if ( conn == null ) throw new Exception("Connection is NOT avaiable !!");
            return conn;
         }
         public void release(){
            if ( conn != null ) try { conn.close(); }catch(Excepton e){}
            conn = null;
         }
       }
       -----------------------------------------------------------

     
     프로그램의 유형이나, 클래스 이름이야 뭐든 상관없습니다. 위처럼 우리들만의 고유한
     "Connection Adapter 클래스"를 만들어서 사용한다는 것이 중요하고, 만약 어플리케이션
     서버가 변경된다거나, DB Connection Pooling 방식이 달라지면 해당 ConnectionResource
     클래스 내용만 살짝 고쳐주면 개발자의 소스는 전혀 고치지 않아도 될 것입니다.

     NOTE: ConnectionResource 클래스를 만들때 주의할 것은 절대 Exception 을 클래스 내부에서
       가로채어 무시하게 하지 말라는 것입니다. 그냥 그대로 throw 가 일어나게 구현하세요.
       이렇게 하셔야만 개발자의 소스에서 "Exception 처리"를 할 수 있게 됩니다.

     NOTE2: ConnectionResource 클래스를 만들때 반드시 package 를 선언하도록 하세요.
       IBM WebSphere 3.0.x 의 경우 JSP에서 "서블렛클래스패스"에 걸려 있는 클래스를
       참조할 때, 그 클래스가 default package 즉 package 가 없는 클래스일 경우 참조하지
       못하는 버그가 있습니다. 통상 "Bean"이라 불리는 클래스 역시 조건에 따라 인식하지
       않을 수도 있습니다.
       클래스 다지인 및 설계 상으로 보더라도 package 를 선언하는 것이 바람직합니다.

     NOTE3: 위에서  "userid", "password" 등과 같이 명시적으로 프로그램에 박아 넣지
       않고, 파일로 관리하기를 원한다면, 그렇게 하셔도 됩니다.
       JDF의 Configuration Framework 을 참조하세요.


     PS: 혹자는 왜 ConnectionResource 의 release() 메소드가 필요하냐고 반문할 수도 있습
       니다. 예를 들어 개발자의 소스가 다음처럼 되도록 해도 되지 않느냐라는 거죠.

        -----------------------------------------------------------
        .....
        Connection conn = null;
        Statement stmt = null;
        try {
          conn = ConnectionResource.getConnection(); // <---- !!!

          stmt = conn.createStatement();
          .....
        }
        catch(Exception e){
          .....
        }
        finally {
          if ( stmt != null ) try{stmt.close();}catch(Exception e){}
          if ( conn != null ) try{conn.close();}catch(Exception e){} // <---- !!!
        }
        -----------------------------------------------------------

      이렇게 하셔도 큰 무리는 없습니다. 그러나, JDBC 2.0 을 지원하는 제품에서만
      conn.close() 를 통해 해당 Connection 을 실제 close() 시키는 것이 아니라 DB Pool에
      반환하게 됩니다. BEA WebLogic 이나 IBM WebSphere 3.0.2.x, 3.5.x 등이 그렇습니다.
      그러나, 자체제작된 대부분의 DB Connection Pool 기능은 Connection 을 DB Pool에
      반환하는 고유한 API를 가지고 있습니다. WebSphere Version 2.0.x 에서는
      cmConn.releaseIBMConnection(), Oracle OSDK 에서는 trx.close(conn, "<pool_name">);
      Hans Bersten 의 DBConnectionManager 의 경우는
      connMgr.freeConnection(poolname, conn); 등등 서로 다릅니다. 이러한 제품들까지
      모두 지원하려면 "release()" 라는 우리들(!)만의 예약된 메소드가 꼭 필요하게 됩니다.

      물론, java.sql.Connection Interface를 implements 한 별도의 MyConnection 을 만들어
      두고, 실제 java.sql.Connection 을 얻은 후 MyConnection의 생성자에 그 reference를
      넣어준 후, 이를 return 시에 넘기도록 하게 할 수 있습니다. 이때, MyConnection의
      close() 함수를 약간 개조하여 DB Connection Pool로 돌아가게 할 수 있으니까요.


     PS: 하나 이상의 DB 를 필요로 한다면, 다음과 같은 생성자를 추가로 만들어서 구분케
      할 수도 있습니다.

      -----------------------------------------------------------
      ....
      private String poolname = "default_pool_name";
      private String userid = "scott";
      private String password = "tiger";
      public ConnectionResource() throws Exception {
        initialize();
      }
      public ConnectionResource(String poolname) throws Exception {
        this.poolname = poolname;
        initialize();
      }
      public ConnectionResource(String poolname,String userid, String passwrod)
      throws Exception
      {
        this.poolname = poolname;
        this.userid = userid;
        this.password = password;
        initialize();
      }
      private void initialize() throws Exception {
        ....
      }
      ...
      -----------------------------------------------------------



    -------------------------------------------------------------------------------
    2001.03.20 추가
    2001.10.22 수정
    2001.11.09 수정(아래 설명을 추가함)

    실 운영 사이트의 장애진단 및 튜닝을 다녀보면, 장애의 원인이 DataBase 연결개수가
    지속적으로 증가하고, Connection Pool 에서 더이상 가용한 연결이 남아 있지 않아
    발생하는 문제가 의외로 많습니다. 이 상황의 십중팔구는 개발자의 코드에서 Pool로
    부터 가져온 DB연결을 사용하고 난 후, 이를 여하한의 Exception 상황에서도 다시
    Pool로 돌려보내야 한다는 Rule 를 지키지 않아서 발생한 문제가 태반입니다.
    이름만 말하면 누구나 알법한 큼직한 금융/뱅킹사이트의 프로그램소스에서도 마찬가지
    입니다.
    문제는 분명히 어떤 특정 응용프로그램에서 DB Connection 을 제대로 반환하지 않은
    것은 분명한데, 그 "어떤 특정 응용프로그램"이 꼭집어 뭐냐 라는 것을 찾아내기란
    정말 쉽지 않습니다. 정말 쉽지 않아요. 1초당 수십개씩의 Request 가 다양하게 들어
    오는 상황에서, "netstat -n"으로 보이는 TCP/IP 레벨에서의 DB연결수는 분명히 증가
    하고 있는데, 그 수십개 중 어떤 것이 문제를 야기하느냐를 도저히 못찾겠다는 것이지요.
    사용자가 아무도 없는 새벽에 하나씩 컨텐츠를 꼭꼭 눌러 본들, 그 문제의 상황은
    대부분 정상적인 로직 flow 에서는 나타나지 않고, 어떤 특별한 조건, 혹은 어떤
    Exception 이 발생할 때만 나타날 수 있기 때문에, 이런 방법으로는 손발과 눈만 아프게
    되곤 합니다.

    따라서, 애초 부터, 이러한 상황을 고려하여, 만약, 개발자의 코드에서 실수로 DB연결을
    제대로 Pool 에 반환하지 않았을 때, 그 개발자 프로그램 소스의 클래스 이름과 함께
    Warnning 성 메세지를 남겨 놓으면, 되지 않겠느냐는 겁니다.

    Java 에서는 java.lang.Object 의 finalize() 라는 기막힌 메소드가 있습니다. 해당
    Object instance의 reference 가 더이상 그 어떤 Thread 에도 남아 있지 않을 경우
    JVM의 GC가 일어날 때 그 Object 의 finalize() 메소드를 꼭 한번 불러주니까요.

    계속 반복되는 얘기인데, 아래 글에서 또한번 관련 의미를 찾을 수 있을 것입니다.
    Re: DB Connection Pool: Orphan and Idle Timeout
    http://www.javaservice.net/~java/bbs/read.cgi?m=devtip&b=servlet&c=r_p&n=1005294960

    아래는 이것을 응용하여, Hans Bergsten 의 DBConnectionManager 를 사용하는
    ConnectionAdapter 클래스를 만들어 본 샘플입니다. Trace/Debuging 을 위한 몇가지
    기능이 첨가되어 있으며, 다른 ConnectionPool을 위한 Connection Adapter 를 만들때도
    약간만 수정/응용하여 사용하실 수 있을 것입니다.


    /**
     * Author : Lee WonYoung, javaservice@hanmail.net
     * Date   : 2001.03.20, 2001.10.22
     */

    import java.util.*;
    import java.sql.*;
    import java.io.*;
    import java.text.SimpleDateFormat;

    public class ConnectionResource
    {
        private boolean DEBUG_MODE = true;
        private String DEFAULT_DATASOURCE = "idb";  // default db name
        private long GET_CONNECTION_TIMEOUT = 2000; // wait only 2 seconds if no
                                                    // avaiable connection in the pool
        private long WARNNING_MAX_ELAPSED_TIME = 3000;

        private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd/HHmmss");
        private db.DBConnectionManager manager = null;
        private Connection conn = null;
        private String datasource = DEFAULT_DATASOURCE;
        private String caller = "unknown";
        private long starttime = 0;

        private static int used_conn_count = 0;
        private static Object lock = new Object();

        // detault constructor
        public ConnectionResource()
        {
            manager = db.DBConnectionManager.getInstance();
        }

        // For debugging, get the caller object reference
        public ConnectionResource(Object caller_obj)
        {
            this();
            if ( caller_obj != null )
                caller = caller_obj.getClass().getName();
        }

        public Connection getConnection()  throws Exception
        {
            return getConnection(DEFAULT_DATASOURCE);
        }

        public Connection getConnection(String datasource)  throws Exception
        {
            if ( conn != null ) throw new Exception
                ("You must release the connection first to get connection again !!");

            this.datasource = datasource;
            // CONNECTION_TIMEOUT is very important factor for performance tuning
            conn = manager.getConnection(datasource, GET_CONNECTION_TIMEOUT);
            synchronized( lock ) { ++used_conn_count; }
            starttime = System.currentTimeMillis();
            return conn;
        }

        // you don't have to get "connection reference" as parameter,
        // because we already have the referece as the privae member variable.
        public synchronized void release() throws Exception {  
            if ( conn == null ) return;
            // The following is needed for some DB connection pool.
            boolean mode = true;
            try{
                mode = conn.getAutoCommit();
            }catch(Exception e){}
            if ( mode == false ) {
                try{conn.rollback();}catch(Exception e){}
                try{conn.setAutoCommit(true);}catch(Exception e){}
            }
            manager.freeConnection(datasource, conn);
            conn = null;
            int count = 0;
            synchronized( lock ) { count = --used_conn_count; }
            if ( DEBUG_MODE ) {
                long endtime = System.currentTimeMillis();
                if ( (endtime-starttime) > WARNNING_MAX_ELAPSED_TIME ) {
                    System.err.println(df.format(new java.util.Date()) +
                        ":POOL:WARNNING:" + count +
                        ":(" + (endtime-starttime) + "):" +
                        "\t" + caller
                    );
                }
            }
        }
        // finalize() method will be called when JVM's GC time.
        public void finalize(){
            // if "conn" is not null, this means developer did not release the "conn".
            if ( conn != null ) {
                System.err.println(df.format(new java.util.Date()) +
                    ":POOL:ERROR connection was not released:" +
                    used_conn_count + ":\t" + caller
                );
                release();
            }
        }
    }

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

    위의 Connection Adaptor 클래스를 Servlet 이나 JSP에서 사용할 때는 다음과 같이
    사용할 수 있습니다.


    사용법: DB Transaction 처리가 필요치 않을 때...


    ConnectionResource resource = null;
    Connection conn = null;
    Statement stmt = null;
    try{
        // For debugging and tracing, I recommand to send caller's reference to
        // the adapter's constructor.
        resource = new ConnectionResource(this); // <--- !!!
        //resource = new ConnectionResource();

        conn = resource.getConnection();
        // or you can use another database name
        //conn = resource.getConnection("other_db");

        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select ...");
        while(rs.next()){
            .....
        }
        rs.close();

    }
    //catch(Exception e){
    //    // error handling if you want
    //    ....
    //}
    finally{
        if ( stmt != null ) try{stmt.close();}catch(Exception e){}
        if ( conn != null ) resource.release(); // <--- !!!
    }

    -------------------------------------------------------------------------------
    사용법: Transaction 처리가 필요할 때.

    ConnectionResource resource = null;
    Connection conn = null;
    Statement stmt = null;
    try{
        // For debugging and tracing, I recommand to send caller's reference to
        // the adapter's constructor.
        resource = new ConnectionResource(this);
        //resource = new ConnectionResource();

        conn = resource.getConnection();
        // or you can use another database name
        //conn = resource.getConnection("other_db");

        conn.setAutoCommit(false); // <--- !!!

        stmt = conn.createStatement();
        stmt.executeUpdate("update ...");
        stmt.executeUpdate("insert ...");
        stmt.executeUpdate("update ...");
        stmt.executeUpdate("insert ...");
        stmt.executeUpdate("update ...");
        
        int affected = stmt.executeUpdate("update....");
        // depends on your business logic,
        if ( affected == 0 )
            throw new Exception("NoAffectedException");
        else if ( affected > 1 )
            throw new Exception("TooManyAffectedException:" + affected);

        conn.commit(); //<<-- commit() must locate at the last position in the "try{}"
    }
    catch(Exception e){
        // if error, you MUST rollback
        if ( conn != null ) try{conn.rollback();}catch(Exception e){}

        // another error handling if you want
        ....
        throw e; // <--- throw this exception if you want
    }
    finally{
        if ( stmt != null ) try{stmt.close();}catch(Exception e){}
        if ( conn != null ) resource.release(); // <-- NOTE: autocommit mode will be
                                                //           initialized
    }
    -----------------------------------------------------------------

    PS: 더 깊이있는 내용을 원하시면 다음 문서들을 참조 하세요...
        JDF 제4탄 - DB Connection Pool
        http://www.javaservice.net/~java/bbs/read.cgi?m=jdf&b=framework&c=r_p&n=945156790

        JDF 제5탄 - DB Connection Resource Framework
        http://www.javaservice.net/~java/bbs/read.cgi?m=jdf&b=framework&c=r_p&n=945335633

        JDF 제6탄 - Transactional Connection Resource Framework
        http://www.javaservice.net/~java/bbs/read.cgi?m=jdf&b=framework&c=r_p&n=945490586


    PS: IBM WebSphere의 JDBC Connection Pool 에 관심이 있다면 다음 문서도 꼭 참조
     하세요...
        Websphere V3 Connection Pool 사용법
        http://www.javaservice.net/~java/bbs/read.cgi?m=appserver&b=was&c=r_p&n=970209527
        WebSphere V3 DB Connection Recovery 기능 고찰
        http://www.javaservice.net/~java/bbs/read.cgi?m=appserver&b=was&c=r_p&n=967473008

    ------------------------
    NOTE: 2004.04.07 추가
    그러나, 2004년 중반을 넘어서는 이 시점에서는, ConnectionResource와 같은 Wapper의
    중요성이 별로 높이 평가되지 않는데, 그 이유는 Tomcat 5.0을 비롯한 대부분의 WAS(Web
    Application Server)가 자체의 Connection Poolinig기능을 제공하며, 그 사용법은 다음과
    같이 JDBC 2.0에 준하여 모두 동일한 형태를 띠고 있기 때문입니다.

    InitialContext ctx = new InitialContext();
    DataSource ds = (DataSoruce)ctx.lookup("java:comp/env/jdbc/ds");
    Connection conn = ds.getConnection();
    ...
    conn.close();

    결국 ConnectionResource의 release()류의 메소드는 Vendor별로, JDBC Connection Pool의
    종류가 난무하던 3-4년 전에는 어플리케이션코드의 Vendor종속성을 탈피하기 위해 의미를
    가졌으나, 지금은 굳이 필요가 없다고 보여 집니다.

    단지, caller와 callee의 정보, 즉, 응답시간을 추적한다거나, close() 하지 않은
    어플리케이션을 추적하는 의미에서의 가치만 남을 수 있습니다.  (그러나, 이것도,
    IBM WebSphere v5의 경우, 개발자가 conn.close() 조차 하지 않을 지라도 자동을 해당
    Thread의 request ending시점에 "자동반환"이 일어나게 됩니다.)

    ---------------------
    2005.01.21 추가
    JDBC Connection/Statement/ResultSet을 close하지 않은 소스의 위치를 잡아내는 것은
    실제 시스템 운영 중에 찾기란 정말 모래사장에서 바늘찾기 같은 것이었습니다.
    그러나, 제니퍼(Jennifer2.0)과 같은 APM을 제품을 적용하시면, 운영 중에, 어느 소스의
    어느 위치에서 제대로 반환시키지 않았는지를 정확하게 찾아줍니다.
    뿐만 아니라, 모든 SQL의 수행통계 및 현재 수행하고 있는 어플리케이션이 어떤 SQL을
    수행중인지 실시간으로 확인되니, 성능저하를 보이는 SQL을 튜닝하는 것 등, 많은 부분들이
    명확해져 가고 있습니다. 이젠 더이상 위 글과 같은 문서가 필요없는 세상을 기대해 봅니다.

    -------------------------------------------------------  
      본 문서는 자유롭게 배포/복사 할 수 있으나 반드시
      이 문서의 저자에 대한 언급을 삭제하시면 안됩니다
    ================================================
      자바서비스넷 이원영
      E-mail: javaservice@hanmail.net
      PCS:011-898-7904
    ================================================
    posted by 좋은느낌/원철
    2008. 6. 30. 17:46 개발/Java
    출처 : http://msinterdev.org/blog/archive/200804?TSSESSIONmsinterdevorgblog=7701d2cc7e6ea2d431e379532dd3888d

    자바서비스.넷  에 있는 예전 글 입니다.
    요즘엔 iBatis 니 Spring 이니 하는 것 들을 이용하기 때문에 별도로 커넥션을 관리 할 일이 없어지긴 하고 있지만, 기본 개념을 모른체로 하다보니 잘못 된 접근을 하는 경우가 발생하여 다시 한번 점검해 봅니다.


    최초작성일자: 2000/09/05 16:19:47
    최근 수정일 : 2001.01.27
    최근 수정일 : 2001.03.12(nested sql query issue)
    최근 수정일 : 2001.03.13(transaction)
    최근 수정일 : 2001.03.20(instance variables in JSP)
    최근 수정일 : 2001.04.03(문맥수정)
    최근 수정일 : 2002.02.06("close 할 땐 제대로..." 추가사항첨가)
    최근 수정일 : 2002.02.25("transaction관련 추가")
    최근 수정일 : 2002.06.11(PreparedStatement에 의한 ResultSet close 이슈)
    최근 수정일 : 2002.06.18(PreparedStatement관련 추가)
    최근 수정일 : 2002.12.30(Instance Variable 공유 1.2 추가)


    다들 아실법한 단순한 얘깁니다만, 아직 많은 분들이 모르시는 것 같아 다시한번
    정리합니다. 아래의 각각의 예제는 잘못 사용하고 계시는 전형적인 예들입니다.

    1. 서블렛에서 instance variable 의 공유

    1.1 서블렛에서 instance variable 의 공유 - PrintWriter -

      다음과 같은 코드를 생각해 보겠습니다.

     import java.io.*;
     import javax.servlet.*;
     import javax.servlet.http.*;

     public class CountServlet extends HttpServlet {
         private PrintWriter out = null; // <-------------- (1)
     
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException
         {
             res.setContentType("text/html");
             out = res.getWriter();
             for(int i=0;i<20;i++){
                 out.println("count= " + (i+1) + "<br>");  // <---- (2)
                 out.flush();
                 try{Thread.sleep(1000);}catch(Exception e){}
             }
        }
      }

     위의 CountServlet.java 를 컴파일하여 돌려 보면, 1초간격으로 일련의 숫자가 올라가는
     것이 보일 겁니다.(서블렛엔진의 구현방식에 따라 Buffering 이 되어 20초가 모두 지난
     후에서 퍽 나올 수도 있습니다.)
     혼자서 단일 Request 를 날려 보면, 아무런 문제가 없겠지만, 이제 브라우져 창을 두개 이상
     띄우시고 10초의 시간 차를 두시면서 동시에 호출해 보세요... 이상한 증상이 나타날
     겁니다. 먼저 호출한 창에는 10 까지 정도만 나타나고, 10초 뒤에 호출한 창에서는 먼저
     호출한 창에서 나타나야할 내용들까지 덤으로 나타나는 것을 목격할 수 있을 겁니다.

     이는 서블렛의 각 호출은 Thread 로 동작하여, 따라서, 각 호출은 위의 (1) 에서 선언한
     instance variable 들을 공유하기 때문에 나타나는 문제입니다.

     위 부분은 다음과 같이 고쳐져야 합니다.

      public class CountServlet extends HttpServlet {
         //private PrintWriter out = null;
     
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException
         {
             PrintWriter out = null; // <--- 이 쪽으로 와야죠 !!!
             res.setContentType("text/html");
             out = res.getWriter();
             for(int i=0;i<20;i++){
                 out.println("count= " + (i+1) + "<br>");  // <---- (2)
                 out.flush();
                 try{Thread.sleep(1000);}catch(Exception e){}
             }
        }
      }

     국내 몇몇 Servlet 관련 서적의 일부 예제들이 위와 같은 잘못된 형태로 설명한
     소스코드들이 눈에 띕니다. 빠른 시일에 바로 잡아야 할 것입니다.

     실제 프로젝트 환경에서 개발된 실무시스템에서도, 그러한 책을 통해 공부하신듯, 동일한
     잘못된 코딩을 하고 있는 개발자들이 있습니다. 결과적으로 테스트 환경에서는 나타나지
     않더니만, 막상 시스템을 오픈하고나니 고객으로 부터 다음과 같은 소리를 듣습니다.
     "내 데이타가 아닌데 남의 데이타가 내 화면에 간혹 나타나요. refresh 를 누르면 또,
     제대로 되구요" .....
     

    1.2 서블렛에서 instance variable 의 공유

     앞서의 경우와 의미를 같이하는데, 다음과 같이 하면 안된다는 얘기지요.

      public class BadServlet extends HttpServlet {
         private String userid = null;
         private String username = null;
         private int hitcount = 0;
     
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException
         {
             res.setContentType("text/html");
             PrintWriter out = res.getWriter();
             userid = request.getParameter("userid");
             username = request.getParameter("username");
             hitcount = hitcount + 1;
             ....
        }
      }

     새로운 매 HTTP 요청마다 userid/username변수는 새롭게 할당됩니다. 문제는 그것이 특정
     사용자에 한하여 그러한 것이 아니라, BadServlet의 인스턴스(instance)는 해당
     웹컨테이너(Web Container)에 상에서 (예외경우가 있지만) 단 하나만 존재하고, 서로 다른
     모든 사용자들의 서로 다른 모든 요청들에 대해서 동일한 userid/username 및 count 변수를
     접근하게 됩니다. 따라서, 다음과 같이 메소드 안으로 끌어들여 사용하여야 함을 강조합니다.

      public class BadServlet extends HttpServlet {
         //private String userid = null; // <---- !!
         //private String username = null; // <---- !!
         private int hitcount = 0;
     
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException
         {
             res.setContentType("text/html");
             PrintWriter out = res.getWriter();
             String userid = request.getParameter("userid"); // <---- !!
             String username = request.getParameter("username"); // <---- !!

             //또한, instance 변수에 대한 접근은 적어도 아래처럼 동기화를 고려해야...
             synchronized(this){ hitcount = hitcount + 1; }
             ....
        }
      }


    1.3 서블렛에서 instance variable 의 공유  - DataBase Connection -

     public class TestServlet extends HttpServlet {
         private final static String drv = "oracle.jdbc.driver.OracleDriver";
         private final static String url = "jdbc:orache:thin@210.220.251.96:1521:ORA8i";
         private final static String user = "scott";
         private final static String password = "tiger";

         private ServletContext context;
         private Connection conn = null;  <--- !!!
         private Statement stmt = null; <------ !!!
         private ResultSet rs = null; <------ !!!
     
         public void init(ServletConfig config) throws ServletException {
             super.init(config);
             context = config.getServletContext();
             try {
                 Class.forName(drv);
             }
             catch (ClassNotFoundException e) {
                 throw new ServletException("Unable to load JDBC driver:"+ e.toString());
             }
         }
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException, SQLException
         {
             String id = req.getParameter("id");
             conn = DriverManager.getConnection(url,user,password);   ---- (1)
             stmt = conn.createStatement();  ---------- (2)
             rs = stmt.executeQuery("select .... where id = '" + id + "'"); ----- (3)
             while(rs.next()) { ----------- (4)
                ......  --------- (5)
             }  
             rs.close();  -------- (6)
             stmt.close();  ---- (7)
             conn.close();  --- (8)
             .....
        }
      }

      위에서 뭐가 잘못되었죠? 여러가지가 있겠지만, 그 중에 하나가 java.sql.Connection과
      java.sql.Statment, java.sql.ResultSet을 instance variable 로 사용하고 있다는 것입니다.

      이 서블렛은 사용자가 혼자일 경우는 아무런 문제를 야기하지 않습니다. 그러나 여러사람이
      동시에 이 서블렛을 같이 호출해 보면, 이상한 증상이 나타날 것입니다.
      그 이유는 conn, stmt, rs 등과 같은 reference 들을 instance 변수로 선언하여 두었기
      때문에 발생합니다.  서블렛은 Thread로 동작하며 위처럼 instance 변수 영역에 선언해 둔
      reference 들은 doGet(), doPost() 를 수행하면서 각각의 요청들이 동시에 공유하게 됩니다.

      예를 들어, 두개의 요청이 약간의 시간차를 두고 비슷한 순간에 doGet() 안으로 들어왔다고
      가정해 보겠습니다.
      A 라는 요청이 순차적으로 (1), (2), (3) 까지 수행했을 때, B 라는 요청이 곧바로 doGet()
      안으로 들어올 수 있습니다. B 역시 (1), (2), (3) 을 수행하겠죠...
      이제 요청 A 는 (4) 번과 (5) 번을 수행하려 하는데, 가만히 생각해 보면, 요청B 로 인해
      요청A에 의해 할당되었던 conn, stmt, rs 의 reference 들은 바뀌어 버렸습니다.
      결국, 요청 A 는  요청 B 의 결과를 가지고 작업을 하게 됩니다. 반면, 요청 B 는
      요청 A 의 의해 rs.next() 를 이미 수행 해 버렸으므로, rs.next() 의 결과가 이미 close
      되었다는 엉뚱한 결과를 낳고 마는 거죠...
      다른 쉬운 얘기로 설명해 보면, A, B 두사람이 식탁에 앉아서 각자 자신이 준비해 온 사과를
      하나씩 깎아서 식탁 위의 접시에 올려 놓고 나중에 먹어려 하는 것과 동일합니다. A 라는
      사람이 열심히 사과를 깎아 접시에 담아둘 때, B 라는 사람이 들어와서 A가 깎아둔 사과를
      버리고 자신이 깎은 사과를 대신 접시에 담아 둡니다. 이제 A라는 사람은 자신이 깎아서
      담아 두었다고 생각하는 그 사과를 접시에서 먹어버립니다. 곧이어 B라는 사람이 자신의
      사과를 접시에서 먹어려 하니 이미 A 가 먹고 난 후 였습니다. 이는 접시를 두 사람이
      공유하기 때문에 발생하는 문제잖습니까.
      마찬가지로 서블렛의 각 Thread는 instance variable 를 공유하기 때문에 동일한 문제들을
      발생하게 됩니다.

      따라서 최소한 다음처럼 고쳐져야 합니다.

     public class TestServlet extends HttpServlet {
         private final static String drv = "...";
         private final static String url = "....";
         private final static String user = "...";
         private final static String password = "...";

         private ServletContext context;
     
         public void init(ServletConfig config) throws ServletException {
             super.init(config);
             context = config.getServletContext();
             try {
                 Class.forName(drv);
             }
             catch (ClassNotFoundException e) {
                 throw new ServletException("Unable to load JDBC driver:"+ e.toString());
             }
         }
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException, SQLException
         {
             Connection conn = null;  <----- 이곳으로 와야죠..
             Statement stmt = null; <-------
             ResultSet rs = null; <---------

             String id = req.getParameter("id");
             conn = DriverManager.getConnection(url,user,password);
             stmt = conn.createStatement();
             rs = stmt.executeQuery("select ..... where id = '" + id + "'");
             while(rs.next()) {
                ......  
             }  
             rs.close();
             stmt.close();
             conn.close();
             .....
         }
      }


    1.4 JSP에서 Instance Variable 공유

     JSP에서 아래처럼 사용하는 경우가 위의 경우와 동일한 instance 변수를 공유하는 경우가
     됩니다.
       ---------------------------------------------------------
       <%@ page session=.... import=.... contentType=........ %>
       <%!
           Connection conn = null;
           Statement stmt = null;
           ResultSet rs = null;
           String userid = null;
       %>
       <html><head></head><body>
       <%
           ........
           conn = ...
           stmt = .....

           uesrid = ......
       %>
       </body></html>
       ---------------------------------------------------------

       마찬가지로 위험천만한 일이며, 여러 Thread 에 의해 그 값이 변할 수 있는 변수들은
       <%! ... %> 를 이용하여 선언하시면 안됩니다. 이처럼 instance 변수로 사용할 것은
       다음 처럼, 그 값이 변하지 않는 값이거나, 혹은 공유변수에 대한 특별한 관리를
       하신 상태에서 하셔야 합니다.

       <%!  private static final String USERID = "scott";
            private static final String PASSWORD = "tiger";
       %>

       JSP에서의 이와 같은 잘못된 유형도, 앞선 서블렛의 경우처럼 일부 국내 JSP관련
       서적에서 발견됩니다.  해당 서적의 저자는 가능한 빨리 개정판을 내셔서 시정하셔야
       할 것입니다. 해당 책은 출판사나 책의 유형, 그리고 글자체로 추정건데, 초보자가
       쉽게 선택할 법한 책인 만큼 그 파급력과 영향력이 너무 큰 듯 합니다.
     
       이와 같은 부분이 실 프로젝트에서 존재할 경우, 대부분 시스템 오픈 첫날 쯤에
       문제를 인식하게 됩니다. Connection reference 가 엎어쳐지므로 Pool 에 반환이
       일어나지 않게 되고, 이는 "connection pool"의 가용한 자원이 부하가 얼마 없음에도
       불구하고 모자라는 현상으로 나타나며, 때론 사용자의 화면에서는 엉뚱한 다른
       사람의 데이타가 나타나거나, SQLException 이 나타납니다.

       NOTE: 어떻게하란 말입니까? 각 호출간에 공유되어서는 안될 변수들은 <%! ...%> 가
       아니라, <% ... %> 내에서 선언하여 사용하란 얘깁니다. JSP가 Pre-compile되어
       Servlet형태로 변환될 때, <%! ... %>는 서블렛의 instance variable로 구성되는 반면,
       <% ... %>는 _jspService() 메소드 내의 method variable로 구성됩니다.



    2. 하나의 Connection을 init()에서 미리 연결해 두고 사용하는 경우.

     public class TestServlet extends HttpServlet {
         private final static String drv = "oracle.jdbc.driver.OracleDriver";
         private final static String url = "jdbc:orache:thin@210.220.251.96:1521:ORA8i";
         private final static String user = "scott";
         private final static String password = "tiger";

         private ServletContext context;
         private Connection conn = null;  <--- !!!
     
         public void init(ServletConfig config) throws ServletException {
             super.init(config);
             context = config.getServletContext();
             try {
                 Class.forName(drv);
                 conn = DriverManager.getConnection(url,user,password);
             }
             catch (ClassNotFoundException e) {
                 throw new ServletException("Unable to load JDBC driver:"+ e.toString());
             }
             catch (SQLException e) {
                 throw new ServletException("Unable to connect to database:"+ e.toString());
             }
         }
         public void doGet(HttpServletRequest req, HttpServletResponse res)  
             throws ServletException, IOException, SQLException
         {
             Statement stmt = null;
             ResultSet rs = null;
             String id = req.getParameter("id");
             stmt = conn.createStatement();
             rs = stmt.executeQuery("select ..... where id = '" + id + "'");
             while(rs.next()) {
                ......  
             }  
             rs.close();
             stmt.close();
             .....
         }
         public void destroy() {
             if ( conn != null ) try {conn.close();}catch(Exception e){}
         }     
      }

     위는 뭐가 잘못되었을 까요?  서블렛당 하나씩 java.sql.Connection 을 init()에서 미리
     맺어 두고 사용하는 구조 입니다.

     얼핏 생각하면 아무런 문제가 없을 듯도 합니다. doGet() 내에서 별도의 Statement와
     ResultSet 을 사용하고 있으니, 각 Thread는 자신만의 Reference를 갖고 사용하게 되니까요.

     이 구조는 크게 세가지의 문제를 안고 있습니다. 하나는 DB 연결자원의 낭비를 가져오며,
     두번째로 수많은 동시사용자에 대한 처리한계를 가져오고, 또 마지막으로 insert, update,
     delete 와 같이 하나 이상의 SQL문장을 수행하면서 단일의 Transaction 처리를 보장받을
     수 없다는 것입니다.

     1) DB 자원의 낭비

       위의 구조는 서블렛당 하나씩 java.sql.Connection 을 점유하고 있습니다. 실 프로젝트에서
       보통 서블렛이 몇개나 될까요? 최소한 100 개에서 400개가 넘어 갈 때도 있겠죠?
       그럼 java.sql.Connection에 할당 되어야 할 "DB연결갯수"도 서블렛 갯수 많큼 필요하게
       됩니다. DB 연결 자원은 DB 에서 설정하기 나름이지만, 통상 maximum 을 셋팅하기
       마련입니다. 그러나 아무런 요청이 없을 때도 400 여개의 DB연결이 연결되어 있어야 한다는
       것은 자원의 낭비입니다.
        
     2) 대량의 동시 사용자 처리 불가.

       또한, 같은 서블렛에 대해 동시에 100 혹은 그 이상의 요청이 들어온다고 가정해 보겠습
       니다. 그럼 같은 java.sql.Connection 에 대해서 각각의 요청이 conn.createStatement() 를
       호출하게 됩니다.
       문제는 하나의 Connection 에 대해 동시에 Open 할 수 있는 Statement 갯수는 ( 이 역시
       DB 에서 셋팅하기 나름이지만 ) maximum 제한이 있습니다. Oracle 의 경우 Default는 50
       입니다. 만약 이 수치 이상을 동시에 Open 하려고 하면 "maximum open cursor exceed !"
       혹은 "Limit on number of statements exceeded"라는 SQLExceptoin 을 발생하게 됩니다.

       예를 들어 다음과 같은 프로그램을 실행시켜 보세요.

       public class DbTest {
         public static void main(String[] args) throws Exception {
            Class.forName("jdbc driver...");
            Connection conn = DriverManager.getConnection("url...","id","password");
            int i=0;
            while(true) {
               Statement stmt = conn.createStatement();
               System.out.println( (++i) + "- stmt created");
            }
         }
       }

       과연 몇개 까지 conn.createStement() 가 수행될 수 있을까요? 이는 DB에서 설정하기 나름
       입니다. 중요한 것은 그 한계가 있다는 것입니다.
       또한 conn.createStatement() 통해 만들어진 stmt 는 java.sql.Connection 의 자원이기
       때문에 위처럼 stmt 의 reference 가 없어졌다고 해도 GC(Garbage Collection)이 되지
       않습니다.


      3) Transaction 중복현상 발생

      예를 들어 다음과 같은 서비스가 있다고 가정해 보겠습니다.

      public void doGet(HttpServletRequest req, HttpServletResponse res)  
          throws ServletException, IOException, SQLException
      {
          Statement stmt = null;
          String id = req.getParameter("id");
          try {
              conn.setAutoCommit(false);
              stmt = conn.createStatement();
              stmt.executeUpdate("update into XXXX..... where id = " + id + "'");
              stmt.executeUpdate("delete from XXXX..... where id = " + id + "'");
              stmt.executeUpdate(".... where id = " + id + "'");
              stmt.executeUpdate(".... where id = " + id + "'");
              conn.commit();
          }
          catch(Exception e){
              try{conn.rollback();}catch(Exception e){}
          }
          finally {
             if ( stmt != null ) try{stmt.close();}catch(Exception e){}
             conn.setAutoCommit(true);
          }
          .....
      }

      아무런 문제가 없을 듯도 합니다. 그러나 위의 서비스를 동시에 요청하게 되면, 같은
      java.sql.Connection 을 갖고 작업을 하고 있으니 Transaction 이 중첩되게 됩니다.
      왜냐면, conn.commit(), conn.rollback() 과 같이 conn 이라는 Connection 에 대해서
      Transaction 이 관리되기 때문입니다. 요청 A 가 총 4개의 SQL문장 중 3개를 정상적으로
      수행하고 마지막 4번째의 SQL문장을 수행하려 합니다. 이 때 요청 B가 뒤따라 들어와서
      2개의 SQL 문장들을 열심히 수행했습니다.  근데, 요청 A에 의한 마지막 SQL 문장
      수행중에 SQLException 이 발생했습니다. 그렇담 요청 A 는 catch(Exception e) 절로
      분기가 일어나고 conn.rollback() 을 수행하여 이미 수행한 3개의 SQL 수행들을 모두
      rollback 시킵니다. 근데,,, 문제는 요청 B 에 의해 수행된 2개의 SQL문장들도 같이
      싸잡아서 rollback() 되어 버립니다. 왜냐면 같은 conn 객체니까요. 결국, 요청B 는
      영문도 모르고 마지막 2개의 SQL문장만 수행한 결과를 낳고 맙니다.

      따라서 정리하면, Connection, Statement, ResultSet 는 doGet() , doPost() 내에서
      선언되고 사용되어져야 합니다.

      public void doGet(HttpServletRequest req, HttpServletResponse res)  
          throws ServletException, IOException, SQLException
      {
          Connection conn = null;  <----- 이곳으로 와야죠..
          Statement stmt = null; <-------
          ResultSet rs = null; <---------
          .....
      }




     3. Exception 이 발생했을 때도 Connection 은 닫혀야 한다 !!

      public void doGet(HttpServletRequest req, HttpServletResponse res)  
           throws ServletException, IOException, SQLException
      {
          String id = req.getParameter("id");

          Connection conn = DriverManager.getConnection("url...","id","password");
          Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("ssselect * from XXX where id = '" + id + "'");
          while(rs.next()) {
             ......  
          }  
          rs.close();
          stmt.close();
          conn.close();
          .....
      }

      위에선 뭐가 잘못되었을까요? 네, 사실 특별히 잘못된 것 없습니다. 단지 SQL문장에 오타가
      있다는 것을 제외하곤.... 근데, 과연 그럴까요?
      SQLException 이라는 것은 Runtime 시에 발생합니다. DB 의 조건이 맞지 않는다거나
      개발기간 중에 개발자의 실수로 SQL문장에 위처럼 오타를 적을 수도 있죠.
      문제는 Exception 이 발생하면 마지막 라인들 즉, rs.close(), stmt.close(), conn.close()
      가 수행되지 않는다는 것입니다.
      java.sql.Connection 은 reference 를 잃더라도 JVM(Java Virtual Machine)의 GC(Garbage
      Collection) 대상이 아닙니다. 가뜩이나 모자라는 "DB연결자원"을 특정한 어플리케이션이
      점유하고 놓아 주지 않기 때문에 얼마안가 DB Connection 을 더이상 연결하지 못하는
      사태가 발생합니다.

      따라서 다음처럼 Exception 이 발생하든 발생하지 않든 반드시 java.sql.Connection 을
      close() 하는 로직이 꼭(!) 들어가야 합니다.

      public void doGet(HttpServletRequest req, HttpServletResponse res)  
           throws ServletException, IOException, SQLException
      {
          Connection conn = null;
          Statement stmt = null;
          ResultSet rs = null;
          String id = req.getParameter("id");
          try {
            conn = DriverManager.getConnection("url...","id","password");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("sselect * from XXX where id = '" + id + "'");
            while(rs.next()) {
             ......  
            }
            rs.close();
            stmt.close();
          }
          finally {
             if ( conn != null ) try {conn.close();}catch(Exception e){}
          }
          .....
      }

      참고로, 실프로젝트의 진단 및 튜닝을 나가보면 처음에는 적절한 응답속도가 나오다가
      일정한 횟수 이상을 호출하고 난 뒤부터 엄청 응답시간이 느려진다면, 십중팔구는 위처럼
      java.sql.Connection 을 닫지 않아서 생기는 문제입니다.
      가용한 모든 Connection 을 연결하여 더이상 연결시킬 Connection 자원을 할당할 수 없을
      때, 대부분 timewait 이 걸리기 때문입니다. 일단 DB관련한 작업이 들어오는 족족
      timewait에 빠질 경우, "어플리케이션서버"에서 동시에 처리할 수 있는 최대 갯수만큼
      호출이 차곡차곡 쌓이는 건 불과 몇분 걸리지 않습니다. 그 뒤부터는 애궂은 dummy.jsp
      조차 호출이 되지 않게 되고,   누군가는 "시스템 또 죽었네요"라며 묘한 웃음을 짓곤
      하겠죠....



    4. Connection 뿐만 아니라 Statement, ResultSet 도 반드시 닫혀야 한다 !!

    4.1  3번의 예제에서 Connection 의 close() 만 고려하였지 Statement 나 ResultSet 에 대한
      close는 전혀 고려 하지 않고 있습니다. 무슨 문제가 있을까요? Statement 를 닫지 않아도
      Connection 을 닫았으니 Statement 나 ResultSet 은 자동으로 따라서 닫히는 것 아니냐구요?
      천만의 말씀, 만만의 콩깎지입니다.

      만약, DB Connection Pooling 을 사용하지 않고 직접 JDBC Driver 를 이용하여 매번 DB
      연결을 하였다가 끊는 구조라면 문제가 없습니다.
      그러나 DB Connection Pooling 은 이젠 보편화되어 누구나 DB Connection Pooling 을 사용
      해야한다는 것을 알고 있습니다. 그것이 어플리케이션 서버가 제공해 주든, 혹은 작은
      서블렛엔진에서 운영하고 있다면 직접 만들거나, 인터넷으로 돌아다니는 남의 소스를 가져다
      사용하고 있을 겁니다.

      이처럼 DB Connection Pooling 을 사용하고 있을 경우는 Conneciton 이 실제 close()되는
      것이 아니라 Pool에 반환되어 지게 되는데, 결국 reference가 사리지지 않기 때문에 GC시점에
      자동 close되지 않게 됩니다.
      특정 Connection 에서 열어둔 Statement 를  close() 하지 않은채 그냥 반환시켜 놓게 되면,
      언젠가는 그 Connection 은 다음과 같은   SQLException 을 야기할 가능성을 내포하게 됩니다.

      Oracle :
        java.sql.SQLException : ORA-01000: maximum open cursor exceeded !!
                                (최대열기 커서수를 초과했습니다)
      UDB DB2 :
        COM.ibm.db2.jdbc.DB2Exception: [IBM][JDBC 드라이버] CLI0601E  유효하지 않은
          명령문 핸들 또는 명령문이 닫혔습니다. SQLSTATE=S1000
        COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver] CLI0129E  핸들(handle)이
          더이상 없습니다. SQLSTATE=HY014        
        COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0954C  응용프로그램
          힙(heap)에 명령문을 처리하기 위해 사용 가능한 저장영역이 충분하지 않습니다.
          SQLSTATE=57011

      이유는 앞 2)번글에서 이미 언급드렸습니다. 보다 자세한 기술적 내용은 아래의 글을
      참고하세요.
      Connection/Statement 최대 동시 Open 수
      http://www.javaservice.net/~java/bbs/read.cgi?m=devtip&b=jdbc&c=r_p&n=972287002

      따라서 또다시 3번의 소스는 다음과 같은 유형으로 고쳐져야 합니다.

      public void doGet(HttpServletRequest req, HttpServletResponse res)  
           throws ServletException, IOException, SQLException
      {
          Connection conn = null;
          Statement stmt = null;
          ResultSet rs = null;
          String id = req.getParameter("id");
          try {
            conn = ...<getConnection()>...; // (편의상 생략합니다.)
            stmt = conn.createStatement();
            rs = stmt.executeQuery("sselect * from XXX where id = '" + id + "'");
            while(rs.next()) {
             ......  
            }
            // rs.close();
            // stmt.close();
          }
          finally {
            if ( rs != null ) try {rs.close();}catch(Exception e){}
            if ( stmt != null ) try {stmt.close();}catch(Exception e){} // <-- !!!!
            if ( conn != null ) ...<releaseConnection()>...; // (편의상 생략)

          }
          .....
      }

     4.2 사실 위와 같은 구조에서, java.sql.Statement의 쿼리에 의한 ResultSet의 close()에
      대한 것은 그리 중요한 것은 아닙니다. ResultSet은 Statement 가 close() 될 때 함께
      자원이 해제됩니다. 따라서 다음과 같이 하셔도 됩니다.

      public void doGet(HttpServletRequest req, HttpServletResponse res)  
           throws ServletException, IOException, SQLException
      {
          Connection conn = null;
          Statement stmt = null;
          String id = req.getParameter("id");
          try {
            conn = ...<getConnection()>...;
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("sselect * from XXX where id = '" + id + "'");
            while(rs.next()) {
             ......  
            }
            rs.close(); //<--- !!!
          }
          finally {
            // if ( rs != null ) try {rs.close();}catch(Exception e){}
            if ( stmt != null ) try {stmt.close();}catch(Exception e){}
            if ( conn != null ) ...<releaseConnection()>...;
          }
          .....
      }


     4.3  가장 대표적으로 잘못 프로그래밍하고 있는 예를 들라면 다음과 같은 유형입니다.

      Connection conn = null;
      try {
          conn = ...<getConnection()>....;
          Statement stmt = conn.createStatement();
          stmt.executeUpdate("....");  <--- 여기서 SQLException 이 일어나면...
          .....
          .....
          .....  <-- 만약,이쯤에서 NullPointerException 이 일어나면 ?
          .....
          stmt.close(); <-- 이것을 타지 않음 !!!
      }
      finally{
         if ( conn != null ) ...<releaseConnection()>...;
      }


     4.4  Statement 가 close() 되지 않는 또 하나의 경우가 다음과 같은 경우입니다.

      Connection conn = null;
      Statement stmt = null;
      try {
        conn = .....
        stmt = conn.createStatement(); // ....(1)
        rs = stmt.executeQuery("select a from ...");
        .....
        rs.close();

        stmt = conn.createStatement(); // ....(2)
        rs = stmt.executeQuery("select b from ...");
        ....
      }
      finally{
        if ( rs != null ) try {rs.close();}catch(Exception e){}
        if ( stmt != null ) try{stmt.close();}catch(Exception e){}
        if ( conn != null ) ....
      }

      즉, 두번 stmt = conn.createStatement() 를 수행함으로써, 먼저 생성된 stmt 는
      (2)번에 의해 그 reference 가 엎어쳐버리게 되어 영원히 close() 되지 않은채
      남아 있게 됩니다.
      이 경우, (2)번 문장을 주석처리하여야 겠지요. 한번 생성된 Statement 로 여러번
      Query 를 수행하면 됩니다.

      Connection conn = null;
      Statement stmt = null;
      try {
        conn = .....
        stmt = conn.createStatement(); // ....(1)
        rs = stmt.executeQuery("select a from ...");
        .....
        rs.close();

        // stmt = conn.createStatement(); // <--- (2) !!!
        rs = stmt.executeQuery("select b from ...");
        ....
      }
      finally{
        if ( rs != null ) try {rs.close();}catch(Exception e){}
        if ( stmt != null ) try{stmt.close();}catch(Exception e){}
        if ( conn != null ) ....
      }


     4.5  Statement 뿐만 아니라 PreparedStatement 를 사용할 때로 마찬가지 입니다.
      ....
      PreparedStatement pstmt = conn.prepareStatement("select ....");
      ....
      이렇게 만들어진  pstmt 도 반드시 pstmt.close() 되어야 합니다.

      예를 들면, 다음과 같은 코드를 생각할 수 있습니다.

      Connection conn = null;
      try {
        conn = ...<getConnection()>...;
        PreparedStatement pstmt = conn.prepareStatement("select .... ?...?");
        pstmt.setString(1,"xxxx");
        pstmt.setString(2,"yyyy");
        ResultSet rs = pstmt.executeQuery(); <--- 여기서 SQLException 이 일어나면
        while(rs.next()){
          ....
        }
        rs.close();
        pstmt.close();  <-- 이것을 타지 않음 !!!
      }
      finally{
         if ( conn != null ) ...<releaseConnection()>...;
      }

      따라서 같은 맥락으로 다음과 같이 고쳐져야 합니다.
     
      Connection conn = null;
      PreparedStatement pstmt = null; // <-------- !!
      ResultSet rs = null;
      try {
        conn = ...<getConnection()>...;
        pstmt = conn.prepareStatement("select .... ?...?");
        pstmt.setString(1,"xxxx");
        pstmt.setString(2,"yyyy");
        rs = pstmt.executeQuery(); <--- 여기서 SQLException 이 일어나더라도...
        while(rs.next()){
          ....
        }
        //rs.close();
        //pstmt.close();
      }
      finally{
        if ( rs != null ) try {rs.close();}catch(Exception e){}
        if ( pstmt != null ) try {pstmt.close();}catch(Exception e){} // <-- !!!!
        if ( conn != null ) ...<releaseConnection()>...;
      }


     4.6  PreparedStatement 에 관련해서 다음과 같은 경우도 생각할 수 있습니다.

     4.6.1 앞서의 4.4에서 Statement를 createStatement() 연거푸 두번 생성하는 것과
      동일하게 PreparedStatement에서도 주의하셔야 합니다. 예를 들면 다음과 같습니다.

      Connection conn = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      try {
        conn = .....
        pstmt = conn.prepareStatement("select a from ..."); // ....(1)
        rs = pstmt.executeQuery();
        .....
        rs.close();

        pstmt = conn.prepareStatement("select b from ..."); // <--- (2) !!!
        rs = pstmt.executeQuery();
        ....
      }
      finally{
        if ( rs != null ) try {rs.close();}catch(Exception e){}
        if ( pstmt != null ) try{pstmt.close();}catch(Exception e){} // <--- (3)
        if ( conn != null ) ...<releaseConnection()>...;
      }

      Statement의 인스턴스는 conn.createStatement() 시에 할당되어 지는 반면,
      PreparedStatement는 conn.prepareStatement("..."); 시에 할당되어 집니다. 위의 경우에서
      설령 마지막 finally 절에서 pstmt.close() 를 하고 있기는 하지만, (1)번에서 할당되어진
      pstmt 는 (2)에서 엎어쳤기 때문에 영원히 close() 되지 않게 됩니다. 따라서, 다음과
      같이 코딩되어야 한다는 것은 자명합니다.

      Connection conn = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      try {
        conn = .....
        pstmt = conn.prepareStatement("select a from ..."); // ....(1)
        rs = pstmt.executeQuery();
        .....
        rs.close();
        pstmt.close(); // <------- !!!!! 이처럼 여기서 먼저 close() 해야지요.

        pstmt = conn.prepareStatement("select b from ..."); // <--- (2)
        rs = pstmt.executeQuery();
        ....
      }
      finally{
        if ( rs != null ) try {rs.close();}catch(Exception e){}
        if ( pstmt != null ) try{pstmt.close();}catch(Exception e){} // <--- (3)
        if ( conn != null ) ...<releaseConnection()>...;
      }

      혹은 다음과 같이 서로 다른 두개의 PreparedStatement를 이용할 수도 있습니다.
     
      Connection conn = null;
      PreparedStatement pstmt1 = null;
      ResultSet rs1 = null;
      PreparedStatement pstmt2 = null;
      ResultSet rs2 = null;
      try {
        conn = .....
        pstmt1 = conn.prepareStatement("select a from ..."); // ....(1)
        rs1 = pstmt1.executeQuery();
        .....
        pstmt2 = conn.prepareStatement("select b from ..."); // <--- (2)
        rs2 = pstmt2.executeQuery();
        ....
      }
      finally{
        if ( rs1 != null ) try {rs1.close();}catch(Exception e){}
        if ( pstmt1 != null ) try{pstmt1.close();}catch(Exception e){} // <--- (3)
        if ( rs2 != null ) try {rs2.close();}catch(Exception e){}
        if ( pstmt2 != null ) try{pstmt2.close();}catch(Exception e){} // <--- (4)
        if ( conn != null ) ...<releaseConnection()>...;
      }


     4.6.2 아래는 앞서의 4.6.1과 같은 맥락인데, for loop 안에서 사용된 경우입니다.

      Connection conn = null;
      PreparedStatement pstmt = null;
      try {
        conn = ...<getConnection()>...;
        for(int i=0;i<10;i++){
          pstmt = conn.prepareStatement("update .... ?... where id = ?"); //... (1)
          pstmt.setString(1,"xxxx");
          pstmt.setString(2,"id"+(i+1) );
          int affected = pstmt.executeUpdate();
          if ( affected == 0 ) throw new Exception("NoAffected");
          else if ( affedted > 1 ) throw new Exception("TooManyAffected");
        }
      }
      finally{
         if ( pstmt != null ) try {pstmt.close();}catch(Exception e){} // ...(2)
         if ( conn != null ) ...<releaseConnection()>...;
      }

      이 경우가 실제 프로젝트 performace 튜닝을 가 보면 종종 발견되는 잘못된
      유형 중의 하나입니다. 핵심은 pstmt.prepareStatement("update..."); 문장을
      수행할 때 마다 내부적으로 pstmt 가 새로 할당된다는 것에 있습니다.
      결국, (1)번 문장이 for loop 을 돌면서 9개는 pstmt.close()가 되지 않고, 마지막
      하나의 pstmt 만  finally 절의 (2)번에서 close 되지요...
      따라서 다음처럼 고쳐져야 합니다.

      Connection conn = null;
      PreparedStatement pstmt = null;
      try {
        conn = ...<getConnection()>...;
        pstmt = conn.prepareStatement("update .... ?... where id = ?");
        for(int i=0;i<10;i++){
          pstmt.clearParameters();      
          pstmt.setString(1,"xxxx");
          pstmt.setString(2,"id"+(i+1) );
          int affected = pstmt.executeUpdate();
          if ( affected == 0 ) throw new Exception("NoAffected");
          else if ( affedted > 1 ) throw new Exception("TooManyAffected");
        }
      }
      finally{
         if ( pstmt != null ) try {pstmt.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }

      PreparedStatement 라는 것이, 한번 파싱하여 동일한 SQL문장을 곧바로 Execution할 수
      있는 장점이 있는 것이고, 궁극적으로 위와 같은 경우에 효과를 극대화 할 수 있는
      것이지요.

      어느 개발자의 소스에서는 위의 경우를 다음과 같이 for loop 안에서 매번
      conn.prepareStatement(...)를 하는 경우를 보았습니다.

      Connection conn = null;
     
      try {
        conn = ...<getConnection()>...;
        for(int i=0;i<10;i++) {
            PreparedStatement pstmt = null;
            try{
                pstmt = conn.prepareStatement("update .... ?... where id = ?");
                pstmt.clearParameters();      
                pstmt.setString(1,"xxxx");
                pstmt.setString(2,"id"+(i+1) );
                int affected = pstmt.executeUpdate();
                if ( affected == 0 ) throw new Exception("NoAffected");
                else if ( affedted > 1 ) throw new Exception("TooManyAffected");
            }
            finally{
                if ( pstmt != null ) try {pstmt.close();}catch(Exception e){}
            }
        }
      }
      finally{
         if ( conn != null ) ...<releaseConnection()>...;
      }

      위 경우는 장애관점에서 보면 사실 별 문제는 없습니다. 적어도 닫을 건 모두 잘 닫고
      있으니까요. 단지 효율성의 문제가 대두될 수 있을 뿐입니다.

     4.7 생각해 보면, Statement 나 PreparedStatement 가 close() 되지 않는 유형은
      여러가지가 있습니다. 그러나 열려진 Statement는 반드시 close()되어야 한다라는
      단순한 사실에 조금만 신경쓰시면 어떻게 프로그래밍이 되어야 하는지 쉽게
      감이 오실 겁니다. 단지 신경을 안쓰시니 문제가 되는 것이지요...

      Statement 를 닫지 않는 실수를 한 코드가 400-1000여개의 전 어플리케이션을 통털어
      한두군데에 숨어 있는 경우가 제일 찾아내기 어렵습니다. 한두번 Statement 를
      close 하지 않는다고 하여 곧바로 문제로 나타나지 않기 때문입니다.
      하루나 이틀, 혹은 며칠지나서야, Oracle 의 경우, "maximum open cursor exceed"
      에러를 내게 됩니다. oracle 의 경우, 위와 같은 에러를 conn.createStatement()시에
      발생하므로 (경우에 따라) 큰 문제로 이어지지는 않습니다. 찾아서 고치면 되니까요.

      반면, DB2 의 경우는 메모리가 허용하는 한도까지 지속적인 메모리 증가를 야기합니다.
      급기야 "핸들(handle)이 더이상 없습니다", "응용프로그램 힙(heap)에 명령문을
      처리하기 위해 사용 가능한 저장영역이 충분하지 않습니다", "유효하지 않은 명령문
      핸들 또는 명령문이 닫혔습니다" 등과 같은 에러를 내지만, 여기서 그치는 것이 아니라
      새로운 connection 을 맺는 시점에 SIGSEGV 를 내면 crashing 이 일어납니다.
      java.lang.OutOfMemoryError 가 발생하기 때문이지요.

      Oracle 의 경우도 사실 상황에 따라 심각할 수 있습니다. 예를 들어, 어떤 개발자가
      "maximum open cursor exceed"라는 Oracle SQL 에러 메세지를 만나고는 자신이
      코딩을 잘못한 것은 염두에 두지 않고, 무조건 DBA에게 oraXXX.ini 파일에서
      OPEN_CURSORS 값을 올려달라고 요청하고, DBA는 그 조언(?)을 충실히 받아들여
      Default 50 에서 이를 3000 으로 조정합니다. 여기서 문제는 깊숙히(?) 숨겨집니다.
      close() 안된 Statement 가 3000 회에 도달하지 전까진 아무도 문제를 인식하지
      못하기 때문이죠. 그러나, Statement가 하나씩 close()되지 않은 갯수에 비례하여
      Oracle 엔진의 메모리 사용은 자꾸만 증가하고, 전체적인 성능저하를 야기하지만,
      이를 인식하기란 막상 시스템을 오픈하고 나서 3-4일이 지난 후에 "DB성능이 이상하네,
      응답속도가 느리네" 하면서 또 한번의 "maximum open cursor exceed" 메세지를
      확인하고 난 뒤의 일이 되곤 합니다.

      에러가 없는 정상적인 로직 flow 에서는 대부분 Statement가 잘 닫힐 겁니다. 그러나,
      어떤 이유에서건 아주 드물게 Runtime Exception 이 발생하여 exception throwing으로
      인해 "stmt.close()"를 타지 않는 경우가 제일 무섭지요. 정말 무섭지요...

      Statement, PreparedStatement, CallableStatement 모두 마찬가지 입니다.



    5. close() 를 할 땐 제대로 해야 한다!!

     5.1 다음과 같은 프로그램 형식을 생각할 수 있습니다.

      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;
      try{
         conn = ...<getConnection()>...; //.......(1)
         stmt = conn.createStatement();    //.............(2)
         rs = stmt.executeQuery("select .....");  // .....(3)
         while(rs.next()){
           ......
         }
      }
      finally {
         try {
            rs.close(); //........(4)
            stmt.close(); //......(5)
            ...<releaseConneciton()>...; //......(6)
         }catch(Exception e){}
      }

      위에선 뭐가 잘못되었을까요? 다 제대로 한듯 한데....
      finally 절에서 rs, stmt, conn 을 null check 없이, 그리고 동일한 try{}catch 절로
      실행하고 있습니다.
      예를 들어, (1), (2) 번을 거치면서 conn 과 stmt 객체까지는 제대로 수행되었으나
      (3)번 Query문장을 수행하는 도중에 SQLException 이 발생할 수 있습니다. 그러면,
      finally  절에서 (4) 번 rs.close()를 수행하려 합니다. 그러나, executeQuery()가
      실패 했기 때문에 rs 의 reference 는 null 이므로 rs.close() 시에
      NullPointerException 이 발생합니다.  결국 정작 반드시 수행되어야할 (5)번, (6)번이
      실행되지 않습니다. 따라서 반드시(!) 다음과 같은 형식의 코딩이 되어야 합니다.

      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;
      try{
         conn = ...<getConnection()>...;
         stmt = conn.createStatement();
         rs = stmt.executeQuery("select .....");
         while(rs.next()){
           ......
         }
      }
      catch(Exception e){
         ....
      }
      finally {
         if ( rs != null ) try{rs.close();}catch(Exception e){}
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }

     같은 맥락으로 PreparedStatement 를 사용할 경우도, 다음과 같은 코딩은 잘못되었습니다.

      Connection conn = null;
      PreparedStatement pstmt = null;
      try{
         conn = ...<getConnection()>...; //.......(1)
         pstmt = conn.prepareStatement("ddelete from EMP where empno=7942"); //...(2)
         int k = pstmt.executeUpdate();  // .....(3)
         ......
      }
      finally {
         try {
            pstmt.close(); //......(4)
            ...<releaseConneciton()>...; //......(5)
         }catch(Exception e){}
      }
      왜냐면, SQL문장에 오타가 있었고, 이는 prepareStatement("ddelete..")시점에 에러가
      발생하여 pstmt 가 여전히 null 인 상태로 finally 절로 분기되기 때문인 것이죠.

     5.2.0 앞서 4.2에서도 언급했지만, java.sql.Statement의 executeQuery()에 의한 ResultSet은
      Statement 가 close 될때 자원이 같이 해제되므로 다음과 같이 하여도 그리 문제가 되진
      않습니다.
         
      Connection conn = null;
      Statement stmt = null;
      //ResultSet rs = null;
      try{
         conn = ...<getConnection()>...;
         stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("select .....");
         while(rs.next()){
           ......
         }
         rs.close(); // <---- !!!
      }
      catch(Exception e){
         ....
      }
      finally {
         //if ( rs != null ) try{rs.close();}catch(Exception e){}
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }


    5.2.1  그러나 PreparedStatement에 의한 ResultSet close()는 얘기가 다를 수 있습니다.
      (2002.06.11 추가 사항)
     
      많은 분들이, "아니 설령 ResultSet를 close하지 않았더라도 Statement/PreparedStatement를
      close하면 함께 ResultSet로 close되는 것 아니냐, JDBC 가이드에서도 그렇다고
      나와 있다, 무슨 개뿔같은 소리냐?" 라구요.

      그러나, 한가지 더 이해하셔야 할 부분은, 웹스피어, 웹로직과 같은 상용 웹어플리케이션
      서버들은 성능향상을 위해 PreparedStatement 및 심지어 Statement에 대한 캐싱기능을
      제공하고  있습니다. pstmt.close() 를 하였다고 하여 정말 해당 PreparedStatement가
      close되는 것이 아니라, 해당 PreparedeStatement가 생겨난 java.sql.Connection당 지정된
      개수까지 웹어플리케이션서버 내부에서 reference가 사라지지 않고 캐시로 남아 있게 됩니다.
      결국, 연관된 ResultSet 역시 close()가 되지 않은 채 남아있게 되는 것이지요. 명시적인
      rs.close()를 타지 않으면, 웹어플리케이션서버의 JVM내부 힙영역 뿐만아니라, 쿼리의 결과로
      데이타베이스에서 임시로 만들어진 메모리데이타가 사라지지 않는 결과를 낳게 됩니다.
      특히 ResultSet이 닫히지 않으면 DB에서의 CURSOR가 사라지지 않습니다.
      또한, CURSOR를 자동으로 닫거나 닫지 않는 등의 옵션은 WAS마다 WAS의 DataSource설정에서
      CORSOR 핸들링에 대한 별도의 옵션을 제공하게 되며 특히 아래 [항목6]에서 다시 언급할
      nested sql query 처리시에 민감한 반응을 하게 됩니다.

      따라서, 앞서의 코딩 방법을 반드시 다음처럼 ResultSet도 close하시기를 다시금 정정하여
      권장 드립니다.

      Connection conn = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null; // <---- !!!
      try{
         conn = ...<getConnection()>...;
         pstmt = conn.prepareStatement("select .....");
         rs = pstmt.executeQuery(); // <----- !!!
         while(rs.next()){
           ......
         }
         //rs.close(); // <---- !!!
      }
      catch(Exception e){
         ....
      }
      finally {
         if ( rs != null ) try{rs.close();}catch(Exception e){} // <---- !!!
         if ( pstmt != null ) try{pstmt.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }

      PS: 웹어플리케이션서버에서의 PreparedStatement 캐싱기능에 관한 부분은 아래의 글들을
      참조하세요.
      Connection Pool & PreparedStatement Cache Size
      http://www.javaservice.net/~java/bbs/read.cgi?m=appserver&b=was&c=r_p&n=995572195
      WebLogic에서의 PreparedStatement Cache -서정희-
      http://www.javaservice.net/~java/bbs/read.cgi?m=dbms&b=jdbc&c=r_p&n=1023286823



     5.3 간혹, 다음과 같은 코딩은 문제를 야기하지 않을 것이라고 생각하는 분들이 많습니다.

     finally{
        try{
          if ( stmt != null ) stmt.close();
          if ( conn != null ) conn.close();
        }catch(Exception e){}
     }
     저명한 많은 책에서도 위처럼 코딩되어 있는 경우를 종종봅니다. 맞습니다. 특별히 문제성이
     있어보이지는 않습니다. 그러나, 간혹 웹어플리케이션서버의 Connection Pool과 연계하여
     사용할 땐 때론 문제가 될 때도 있습니다. 즉, 만약, stmt.close()시에 Exception이 throw
     되면 어떻게 되겠습니까?
     아니 무슨 null 체크까지 했는데, 무슨 Exception이 발생하느냐고 반문할 수도 있지만,
     오랜 시간이 걸리는 SQL JOB에 빠져 있다가 Connection Pool의 "Orphan Timeout"이 지나
     자동으로 해당 Connection을 Pool에 돌려보내거나 혹은 특별한 marking처리를 해 둘 수
     있습니다. 이 경우라면 stmt.close()시에 해당 웹어플리케이션서버에 특화된 Exception이
     발생하게 됩니다. 그렇게 되면 conn.close()를 타지 못하게 되는 사태가 벌어집니다.
     따라서, 앞서 하라고 권장한 형식으로 코딩하세요.


    6. Nested (Statemet) SQL Query Issue !!

     6.1 아래와 같은 코딩을 생각해 보겠습니다.

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("select deptno ...where id ='"+ id +"'");
         while(rs.next()){
           String deptno = rs.getString("deptno");
           stmt.executeUpdate(
               "update set dept_name = ... where deptno = '"+ deptno +"'"
           );
           ......
         }
         rs.close();
      }
      catch(Exception e){
         ....
      }
      finally {
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }

      위 코드는 사실 실행하자 말자 다음과 같은 에러를 만나게 됩니다.

      DB2 : -99999: [IBM][CLI Driver] CLI0115E 커서 상태가 유효하지 않습니다.
            SQLSTATE=24000
      Oracle :

      에러는 두번째 while(rs.next()) 시에 발생합니다. 왜냐면, Statement가 nested하게
      실행된 executeUpdate() 에 의해 엎어쳐 버렸기 때문입니다. ResultSet 은
      Statement와 밀접하게 관련이 있습니다. ResultSet은 자료를 저장하고 있는 객체가
      아니라, 데이타베이스와 step by step으로 상호 통신하는 Interface 일 뿐이기 때문입니다.
      따라서 위 코드는 다음처럼 바뀌어져야 합니다.

      Connection conn = null;
      Statement stmt1 = null;
      Statement stmt2 = null;
      try{
         conn = ...<getConnection()>...;
         stmt1 = conn.createStatement();
         stmt2 = conn.createStatement();
         ResultSet rs = stmt1.executeQuery("select deptno ...where id ='"+ id +"'");
         while(rs.next()){
           String deptno = rs.getString("deptno");
           stmt2.executeUpdate(
               "update set dept_name = ... where deptno = '"+ deptno +"'"
           );
           ......
         }
         rs.close();
      }
      catch(Exception e){
         ....
      }
      finally {
         if ( stmt1 != null ) try{stmt1.close();}catch(Exception e){}
         if ( stmt2 != null ) try{stmt2.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }

      즉, ResultSet에 대한 fetch 작업이 아직 남아 있는 상태에서 관련된 Statement를
      또다시 executeQuery()/executeUpdate() 를 하면 안된다는 것입니다.

      PS: IBM WebSphere 환경일 경우, 아래의 글들을 추가로 확인하시기 바랍니다.
      349   Re: Function sequence error  (Version 3.x)
      http://www.javaservice.net/~java/bbs/read.cgi?m=appserver&b=was&c=r_p&n=991154615
      486   WAS4.0x: Function sequence error 해결  
      http://www.javaservice.net/~java/bbs/read.cgi?m=appserver&b=was&c=r_p&n=1015345459



    7. executeUpdate() 의 결과를 비즈니스 로직에 맞게 적절히 활용하라.

     7.1 아래와 같은 코딩을 생각해 보겠습니다.

      public void someMethod(String empno) throws Exception {
          Connection conn = null;
          Statement stmt = null;
          try{
             conn = ...<getConnection()>...;
             stmt = conn.createStatement();
             stmt.executeUpdate(
                 "UPDATE emp SET name='이원영' WHERE empno = '" + empno + "'"
             );
          }
          finally {
             if ( stmt != null ) try{stmt.close();}catch(Exception e){}
             if ( conn != null ) ...<releaseConnection()>...;
          }
      }

      사실 흔히들 이렇게 하십니다. 별로 잘못된 것도 없어보입니다. 근데, 만약
      DB TABLE에 해당 empno 값이 없으면 어떻게 될까요? SQLException 이 발생
      하나요? 그렇지 않죠? 아무런 에러없이 그냥 흘러 내려 옵니다. 그러면, Update를
      하러 들어 왔는데, DB에 Update할 것이 없었다면 어떻게 해야 합니까? 그냥 무시하면
      되나요? 안되죠..  따라서, 다음 처럼, 이러한 상황을 이 메소드를 부른 곳으로
      알려 줘야 합니다.

      public void someMethod(String empno) throws Exception {
          Connection conn = null;
          Statement stmt = null;
          try{
             conn = ...<getConnection()>...;
             stmt = conn.createStatement();
             int affected = stmt.executeUpdate(
                 "UPDATE emp SET name='이원영' WHERE empno = '" + empno + "'"
             );
             if ( affected == 0 ) throw new Exception("NoAffectedException");
             else if ( affected > 1 ) throw new Exception("TooManyAffectedException");
          }
          finally {
             if ( stmt != null ) try{stmt.close();}catch(Exception e){}
             if ( conn != null ) ...<releaseConnection()>...;
          }
      }

      물론 이러한 부분들은 해당 비즈니스로직이 뭐냐에 따라서 다릅니다. 그것을 무시케
      하는 것이 비즈니스 로직이었다면 그냥 무시하시면 되지만, MIS 성 어플리케이션의
      대부분은 이처럼 update 나 delete 쿼리의 결과에 따라 적절한 처리를 해 주어야
      할 것입니다.



    8. Transaction 처리를 할 땐 세심하게 해야 한다.

     단, 아래는 웹어플리케이션서버의 JTA(Java Transaction API)기반의 트렌젝션처리가 아닌,
     java.sql.Connection에서의 명시적인 conn.setAutoCommit(false) 모드를 통한 트렌젝션처리에
     대해서 언급 하고 있습니다.

     8.1 Non-XA JDBC Transaction(명시적인 java.sql.Connection/commit/rollback)

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         stmt = conn.createStatement();
         stmt.executeUpdate("UPDATE ...."); // -------- (1)
         stmt.executeUpdate("DELETE ...."); // -------- (2)
         stmt.executeUpdate("INSERT ...."); // -------- (3)
      }
      finally {
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         if ( conn != null ) ...<releaseConnection()>...;
      }

      위와 같은 코딩은 아무리 비즈니스적 요구가 간소하더라도, 실 프로젝트에서는
      있을 수가 없는 코딩입니다.(JTS/JTA가 아닌 명시적인 Transaction 처리시에..)

      다들 아시겠지만, (1), (2) 번까지는 정상적으로 잘 수행되었는데, (3)번문장을
      수행하면서 SQLException 이 발생하면 어떻게 되나요? (1),(2)은 이미 DB에 반영된
      채로 남아 있게 됩니다. 대부분의 비즈니스로직은 그렇지 않았을 겁니다.
     
      "(1),(2),(3)번이 모두 정상적으로 수행되거나, 하나라도 잘못되면(?) 모두 취소
      되어야 한다"
     
      가 일반적인 비즈니스적 요구사항이었을 겁니다. 따라서, 다음처럼 코딩 되어야
      합니다.

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         conn.setAutoCommit(false);
         stmt = conn.createStatement();
         stmt.executeUpdate("UPDATE ...."); // -------- (1)
         stmt.executeUpdate("DELETE ...."); // -------- (2)
         stmt.executeUpdate("INSERT ...."); // -------- (3)

         conn.commit(); // <-- 반드시 try{} 블럭의 마지막에 와야 합니다.
      }
      catch(Exception e){
         if ( conn != null ) try{conn.rollback();}catch(Exception ee){}
         // error handling if you want
         
         throw e;  // <--- 필요한 경우, 호출한 곳으로 Exception상황을 알려줄
                   //      수도 있습니다
      }
      finally {
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         // in some connection pool, you have to reset commit mode to "true"
         if ( conn != null ) ...<releaseConnection()>...;
      }


     8.2 auto commit mode 를 "false"로 셋팅하여 명시적인 Transaction 관리를 할 때,
      정말 조심해야 할 부분이 있습니다. 예를 들면 다음과 같은 경우입니다.

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         conn.setAutoCommit(false);
         stmt = conn.createStatement();
         stmt.executeUpdate("UPDATE ...."); // ----------------------- (1)
         ResultSet rs = stmt.executeQuery("SELECT ename ..."); // ---- (2)
         if ( rs.next() ) {
            conn.commit(); // ------------------- (3)
         }
         else {
            conn.rollback(); // ----------------- (4)
         }
      }
      finally {
         if ( rs != null ) try{rs.close();}catch(Exception e){}
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         // in some connection pool, you have to reset commit mode to "true"
         if ( conn != null ) ...<releaseConnection()>...;
      }

      코드가 왜 위처럼 됐는지는 저도 모르겠습니다.  단지 비즈니스가 그러했나보죠..

      문제는 만약, (2)번 executeQuery()문장을 수행하면서 SQLException 이나 기타의
      RuntimeException 이 발생할 때 입니다.
      commit() 이나 rollback()을 타지 않고, finally 절로 건너 뛰어 Statement를
      닫고, connection 은 반환됩니다. 이때, commit() 이나 rollback()이 되지 않은채
      (1)번 UPDATE 문이 수행된채로 남아 있게 됩니다.  이는 DB LOCK을 점유하게
      되고, 경우에 따라 다르겠지만, 다음번 요청시에 DB LOCK으로 인한 hang현상을
      초래할 수도 있습니다.
      일단 한두개의 어플리케이션이 어떠한 이유였든, DB Lock 을 발생시키면, 해당
      DB에 관련된 어플리케이션들이 전부 응답이 없게 됩니다. 이 상황이 조금만
      지속되면, 해당 waiting 을 유발하는 요청들이 어플리케이션서버의 최대 동시
      접속처리수치에 도달하게 되고, 이는 전체 시스템의 hang현상으로 이어지게
      되는 것이죠..


      따라서, 비즈니스 로직이 어떠했든, 반드시 지켜져야할 사항은 다음과 같습니다.

      "conn.setAutoComm(false); 상태에서 한번 실행된 Update성 SQL Query는 이유를
       막론하고 어떠한 경우에도 commit() 이나 rollback() 되어야 한다."

      위의 경우라면 다음처럼 catch 절에서 rollback 시켜주는 부분이 첨가되면 되겠네요.

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         conn.setAutoCommit(false);
         stmt = conn.createStatement();
         stmt.executeUpdate("UPDATE ....");
         ResultSet rs = stmt.executeQuery("SELECT ename ...");
         if ( rs.next() ) {
            conn.commit();
         }
         else {
            conn.rollback();
         }
      }
      catch(Exception e){  // <---- !!!!!
         if ( conn != null ) try{conn.rollback();}catch(Exception ee){}
         throw e;
      }
      finally {
         if ( rs != null ) try{rs.close();}catch(Exception e){}
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         // in some connection pool, you have to reset commit mode to "true"
         if ( conn != null ) ...<releaseConnection()>...;
      }


     8.3 모든 경우의 수를 생각하라.

      다음과 같은 경우를 생각해 보겠습니다.

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         conn.setAutoCommit(false);
         stmt = conn.createStatement();
         stmt.executeUpdate("UPDATE ....");
         String idx = name.substring(3);
         ResultSet rs = stmt.executeQuery("SELECT ename ... where idx=" + idx);
         if ( rs.next() ) {
            .....
         }
         rs.close(); rs = null;

         stmt.executeUpdate("UPDATE ....");
         conn.commit();
      }
      catch(SQLException e){
         if ( conn != null ) try{conn.rollback();}catch(Exception ee){}
         throw e;
      }
      finally {
         if ( rs != null ) try{rs.close();}catch(Exception e){}
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         // in some connection pool, you have to reset commit mode to "true"
         if ( conn != null ) ...<releaseConnection()>...;
      }

      잘 찾아 보세요. 어디가 잘못되었습니까? 잘 안보이시죠?

      Connection conn = null;
      Statement stmt = null;
      try{
         conn = ...<getConnection()>...;
         conn.setAutoCommit(false);
         stmt = conn.createStatement();
         stmt.executeUpdate("UPDATE ...."); //---- (1)
         String idx = name.substring(3); //<------ (2) NullPointerExceptoin ?
         ResultSet rs = stmt.executeQuery("SELECT ename ... where idx=" + idx);
         if ( rs.next() ) {
            .....
         }
         rs.close(); rs = null;

         stmt.executeUpdate("UPDATE ....");
         conn.commit();
      }
      catch(SQLException e){ //<------ (3) 이 부분을 탈까?
         if ( conn != null ) try{conn.rollback();}catch(Exception ee){}
         throw e;
      }
      finally {
         if ( rs != null ) try{rs.close();}catch(Exception e){}
         if ( stmt != null ) try{stmt.close();}catch(Exception e){}
         // in some connection pool, you have to reset commit mode to "true"
         if ( conn != null ) ...<releaseConnection()>...;
      }

      위 코드를 보듯, 만약 (1)을 수행 후 (2)번 에서 NullPointerException 이나
      ArrayIndexOutOfBoundException이라도 나면 어떻게 되죠? catch(SQLException ...)에는
      걸리지 않고 곧바로 finally 절로 건너띄어 버리네요. 그럼 (1)에서 update 된 것은
      commit()이나 rollback() 없이 connection 이 반환되네요... ;-)
      어떻게 해야 합니까? SQLException만 잡아서 되는 것이 아니라, catch(Exception ...)과
      같이 모든 Exception 을 catch해 주어야 합니다.


     8.4 위 주석문에서도 언급해 두었지만, Hans Bergsteins 의 DBConnectionManager.java
      와 같은 Connection Pool 을 사용할 경우에, 개발자의 코드에서 transaction auto
      commit mode 를 명시적으로 "false"로 한 후, 이를 그냥 pool 에 반환하시면,
      그 다음 사용자가 pool 에서 그 connection 을 사용할 경우, 여전히 transaction
      mode 가 "false"가 된다는 것은 주지하셔야 합니다. 따라서, DBConnectionManger의
      release method를 수정하시든지, 혹은 개발자가 명시적으로 초기화한 후 pool 에
      반환하셔야 합니다. 그렇지 않을 경우, DB Lock 이 발생할 수 있습니다.
      반면, IBM WebSphere 나 BEA WebLogic 과 같인 JDBC 2.0 스펙에 준하는 Connection
      Pool을 사용할 경우는 반환할 당시의 transaction mode 가 무엇이었든 간에,
      pool 에서 꺼내오는 connection 의 transaction mode는 항상 일정합니다.
      (default 값은 엔진의 설정에 따라 달라집니다.)
      그렇다고 commit 시키지 않은 실행된 쿼리가 자동으로 commit/rollback 되는 것은
      아닙니다. 단지 auto commit 모드만 자동으로 초기화 될 뿐입니다.

      PS:WAS의 JTS/JTA 트렌젝션 기반으로 운영될 경우는 명시적으로 commit/rollback되지
       않은 트렌젝션은 자동으로 rollback되거나 commit됩니다. default는 WAS 설정에 따라
       다를 수 있습니다.

      ---------------
      NOTE: 자바서비스컨설팅의 WAS성능관리/모니터링 툴인 제니퍼(Jennifer 2.0)를 적용하면,
      어플리케이션에서 명시적으로 commit/rollback시키지 않고 그대로 반환시킨 어플리케이션의
      소스 위치를 실시간으로 감지하여 알려줍니다. 이를 만약 수작업으로 한다면, 수많은 코드
      중 어디에서 DB lock을 유발 시키는 코드가 숨어있는지를 찾기가 경우에 따라 만만치 않은
      경우가 많습니다.

    8.5 XA JDBC Driver, J2EE JTS/JTA
      JDBC 2.0, 표준 javax.sql.DataSource를 통한 JDBC Connection을 사용할 경우에,
      대부분의 상용WAS제품들은 J2EE의 표준 JTS(Java Transaction Service)/JTA(Java Transaction
      API)를 구현하고 있습니다. 특별히, 하나 이상의 데이타베이스에서 2 phase-commit과
      같은 XA Protocol를 지원하고 있지요(사실 WAS에서 2PC가 지원되기 시작한 것은 몇년
      되지 않습니다. 2PC를 사용하려면 반드시 XA-JDBC Driver가 WAS에 설치되어야 합니다)

      샘플 예제는 다음과 같습니다.

        ...
        javax.transaction.UserTransaction tx = null;
        java.sql.Connection conn1 = null;
        java.sql.Statement stmt1 = null;

        java.sql.Connection conn2 = null;
        java.sql.Statement stmt2 = null;
        java.sql.CallableStatement cstmt2 = null;
        
        try {
            javax.naming.InitialContext ctx = new javax.naming.InitialContext();
            tx = (javax.transaction.UserTransaction) ctx.lookup("java:comp/UserTransaction");
            // 트렌젝션 시작
            tx.begin();

            // -------------------------------------------------------------------------
            // A. UDB DB2 7.2 2PC(XA) Test
            // -------------------------------------------------------------------------
            javax.sql.DataSource ds1 =
                (javax.sql.DataSource)ctx.lookup("java:comp/env/jdbc/DB2");
            conn1 = ds1.getConnection();

            stmt1 = conn1.createStatement();
            stmt1.executeUpdate(
                "insert into emp(empno,ename) values(" + empno + ",'Name" + empno + "')"
            );
            stmt1.executeUpdate(
                "update emp set ename = 'LWY" + count + "' where empno = 7934"
            );
            java.sql.ResultSet rs1 = stmt1.executeQuery("select empno,ename from emp");
            while(rs1.next()){
                ...
            }
            rs1.close();
            
            // -------------------------------------------------------------------------
            // B. Oracle 8.1.7 2PC(XA) Test
            // -------------------------------------------------------------------------
            javax.sql.DataSource ds2 =
                (javax.sql.DataSource)ctx.lookup("java:comp/env/jdbc/ORA8i");
            conn2 = ds2.getConnection();
            
            stmt2 = conn2.createStatement();
            stmt2.executeUpdate(
                "update emp set ename = 'LWY" + count + "' where empno = 7934"
            );
            java.sql.ResultSet rs2 = stmt2.executeQuery("select empno,ename from emp");
            while(rs2.next()){
                ...
            }
            rs2.close();


            // -------------------------------------------------------------------------
            // 트렌젝션 commit
            tx.commit();
        }
        catch(Exception e){
            // 트렌젝션 rollback
            if ( tx != null ) try{tx.rollback();}catch(Exception ee){}
            ...
        }
        finally {
            if ( stmt1 != null ) try { stmt1.close();}catch(Exception e){}
            if ( conn1 != null ) try { conn1.close();}catch(Exception e){}

            if ( stmt2 != null ) try { stmt2.close();}catch(Exception e){}
            if ( conn2 != null ) try { conn2.close();}catch(Exception e){}
        }

     

    NOTE: 위에서 설명한 하나하나가 제 입장에서 보면 너무나 가슴깊이 다가오는
      문제들입니다. 개발하시는 분의 입장에서 보면, 위의 가이드에 조금 어긋났다고
      뭐그리 문제겠느냐고 반문하실 수 있지만, 수백본의 소스코드 중에 위와 같은 규칙을
      준수하지 않은 코드가  단 하나라도 있다면, 잘 운영되던 시스템이 며칠에 한번씩
      에러를 야기하거나 응답이 느려지고 급기야 hang 현상을 초래하는 결과를 가져 옵니다.
      정말(!) 그렇습니다.

    NOTE: 위에서 사용한 코딩 샘플들은 JDBC Connection Pooling 은 전혀 고려치 않고
      설명드렸습니다. 그러했기 때문에 <getConnection()>, <releaseConnection()> 이란
      Pseudo 코드로 설명했던 것입니다.
      반드시 "서블렛 + JDBC 연동시 코딩 고려사항 -제2탄-" 을 읽어 보세요.
      http://www.javaservice.net/~java/bbs/read.cgi?m=devtip&b=servlet&c=r_p&n=968522077


    -------------------------------------------------------  
      본 문서는 자유롭게 배포/복사 할 수 있으나 반드시
      이 문서의 저자에 대한 언급을 삭제하시면 안됩니다
    ================================================
      자바서비스넷 이원영
      E-mail: javaservice@hanmail.net
      PCS:010-6239-6498
    ================================================
    posted by 좋은느낌/원철
    2008. 6. 30. 17:44 개발/Java
    출처 : http://msinterdev.org/blog/archive/200804?TSSESSIONmsinterdevorgblog=7701d2cc7e6ea2d431e379532dd3888d

    초록(abstract)
    개발자가 놓치기 쉬운 자바의 기본 원리에 대하여 기본적이긴 하지만 개발하면서 느끼고 경험한 내용을 정리하였다.

    목차

    1 객체지향의 구멍 static
    1.1 Java는 객체지향 언어이다?
    1.2 전역변수
    2 Java는 Pointer언어이다? (Java에는 Pointer밖에 없다?)
    2.1 Java는 primitive형을 제외하곤 모두 Pointer이다
    2.2 null은 객체인가?
    2.3 String에 대하여
    2.4 객체지향의 캡슐화 파괴 주의
    2.5 배열에 대하여
    2.5.1 배열은 object 인가?
    2.5.2 배열의 length는 왜 field(member variable)인가?
    2.5.3 final과 배열에 대하여...
    2.5.4 "Java에서의 다차원 배열은 존재하지 않는다."
    2.6 인수(parameter/argument)전달의 개념
    2.6.1 "Java에서 parameter(argument) 전달은 무조건 'call by value' 이다"
    2.6.2 "C와 같은 언어는 static linking이지만, Java는 dynamic linking이다."
    2.7 GC 에 대하여 잠깐!
    2.7.1 "Garbage Collection은 만능이 아니다."
    2.8 Java Pointer 결론
    2.8.1 "결국 Java에는 pointer가 있는 것인가, 없는 것인가?"
    3 상속과 interface의 문제점
    3.1 상속
    3.1.1 상속에 있어서의 생성자(constructor)
    3.1.2 "down cast는 본질적으로 매우 위험하다"
    3.1.3 "추상클래스에 final이 있으면 compile error이다"
    3.2 interface
    3.2.1 "interface는 interface일뿐 다중 상속의 대용품이 아니다."
    3.3 상속 제대로 사용하기
    4 package와 access 제어에 관한 이해
    4.1 package
    4.1.1 "package는 '계층구조' 인가?"
    4.1.2 "compiler 가 인식하는 class검색 순서(소스코드내 클래스가 발견될 경우 그 클래스의 위치를 찾는 순서)"
    4.2 access 제어
    4.2.1 "interfacde member의 access 제어"
    4.2.2 그렇다면 interface를 다른 package에 대하여 숨기고 싶으면 어떻게 하는가?
    5 기타 Java 기능
    5.1 Thread
    5.1.1 "Multi Thread에서는 흐름은 복수이지만 data는 공유될 수 있다."
    5.1.2 "Thread는 객체와 직교하는 개념이다."
    5.1.3 "Synchronized 의 이해"
    5.1.4 "Thread 사용법의 정석은?"
    5.2 Exception
    5.2.1 "finally 절은 반드시 어떠한 경우에도 실행되는가?"
    5.2.2 "예외의 종류 3가지 (Error, RuntimeException, 그밖의 Exception)"
    5.2.2.1 Error
    5.2.2.2 RuntimeException
    5.2.2.3 그밖의 Exception
    5.2.3 "OutOfMemoryError는 어떻게 처리해야 하는가?"
    5.3 Object Serialize
    5.3.1 "Serialize를 위해서는 marker interface인 java.io.Serializable interface를 implements해야한다."
    5.3.2 "super class는 Serializable이 아닌데 sub class만 Serializable인 경우의 문제점"
    5.3.3 "transient field의 복원(?)관련"
    5.3.4 "Stack Overflow에 주의하라!"
    5.4 "nested class / inner class / 중첩클래스"
    5.4.1 "중첩클래스의 개념"
    5.4.2 "내부클래스는 부모의 참조를 몰래 보유하고 있다."
    5.4.3 "local inner class에 대하여"
    5.4.4 "anonymous class(무명클래스)에 대하여"
    6 이래도 Java가 간단한가?
    6.1 method overload 에서의 혼란?
    6.1.1 "overload란 이름이 가고 인수가 다른 method에 compiler가 다른 이름을 붙이는 기능"
    6.1.2 "그렇다면 overload에서 실제로 혼동되는 부분은 무엇인가?"
    6.1.3 (참고) 또다른 혼동, overload한 method를 override 하면?
    6.2 상속/override/은폐 에서의 복잡함
    6.2.1 "Java class의 member 4 종류"
    6.2.2 "override시 method 이름에 대한 함정"
    6.2.3 "또다른 나의(?) 실수 - 말도 안되는 오타"
    6.2.4 "static member를 instance를 경유하여 참조해서는 안 된다."
    6.2.5 "super keyword는 부모의 this"
    6.3 상속에 관한 또 다른 문제
    6.4 그밖의 함정
    6.4.1 "생성자에 void 를 붙인다면?"
    6.4.2 "if / switch 의 함정"
    7 Java 기능 적용 몇가지
    7.1 대규모 개발에서 interface 분리하기
    7.1.1 "interface 분리의 필요성"
    7.2 Java에서의 열거형
    7.3 Debug write
    8 Java 5.0 Tiger 에 대하여
    8.1 Working with java.util.Arrays
    8.2 Using java.util.Queue interface
    8.3 java.lang.StringBuilder 사용하기
    8.4 Using Type-Safe Lists
    8.5 Writing Generic Types
    8.6 새로운 static final enum
    8.7 Using java.util.EnumMap
    8.8 Using java.util.EnumSet
    8.9 Convert Primitives to Wrapper Types
    8.10 Method Overload resolution in AutoBoxing
    8.11 가변적인 argument 개수 ...
    8.12 The Three Standard Annotation
    8.13 Creating Custom Annotation Types
    9 The for/in Statement
    9.1 for/in 의 자주 사용되는 형태
    10 Static Import
    10.1 static member/method import
    11 References

    1 객체지향의 구멍 static #

    1.1 Java는 객체지향 언어이다? #

    "Java는 완전한 객체지향 언어이다" 라는 주장을 자주 접하게 된다. 만일 이것이 사실이라면 Java를 사용하는 한 "기존의 절차지향 프로그래밍을 전혀 할수 없을것 같지만 그렇지 않다. 빠져나갈 구멍이 있는 것이다. static을 이용하면 비 객체지향 언어처럼 코딩할 수 있다.
    static method는 instance가 아닌 클래스에 속하는 method로, class method라고 부른다. 반대로 static이 아닌 method는 instance method라고 부른다.
    static method는 this가 없다. instance method에는 숨겨진 파라미터로 this가 건네진다. (아래 "객체지향에 흔희 있는 오해" 참고) 하지만 static method는 절차지향의 함수와 동일하므로 숨겨진 파라미터 this는 없다. 그래서 static method에서는 전달한 this가 없으므로 instance method를 호출하거나 instance field를 참조할 수 없는 것이다.
    (참고) 객체지향에 흔히 있는 오해
    • 오해1. "객체지향에서는 객체끼리 서로 메세지를 주고 받으며 동작한다." 라는 말을 듣고 다음과 같이 생각할 수 있다. "객체지향에서는 객체가 각각 독립하여 움직인다는 것인가, 그러면 각 객체에 독립된 thread가 할당되어 있단 말인가?" 그렇지 않다. "메세지를 보낸다"라는 것은 단순히 각 객체의 함수 호출에 불과하다.
    • 오해2. "객체지향에서는 method가 class에 부속되어 있다"는 말을 듣고 다음과 같이 생각할 수 있다. "그러면 instance별로 method의 실행코드가 복제되고 있는 것이 아닌가?" 물론 이것도 오해다. method의 실행코드는 종래의 함수와 동일한 어딘가 다른곳(JVM의 class area)에 존재하며 그 첫번째 파라미터로 객체의 포인터 this가 건네질 뿐이다.
    • 오해3. "그렇다면 각 instance가 method의 실행코드를 통째로 갖고 있지 않는 것은 확실하지만, method의 실행 코드의 포인터는 각 instance별로 보관하고 있는것이 아닌가?" 이것은 약가 애매한 오해이긴 하다. JVM 스펙에서는 class영역에 실행코드를 갖고 있으며, method 호출시 별도의 stack frame이 생성되어 실행되고 실행 완료시 복귀 주소를 전달한다.

    1.2 전역변수 #

    static에서 public field는 전역변수(global variable, 글로벌 변수)이다. 여기서 "글로벌 변수는 왜 안 되는가"에 대해 잠깐 생각해 본다. 우리는 흔히 "글로벌 변수는 될수있는한 사용하지 않는 것이 좋다"라고 한다. 그 이유는 글로벌 변수는 어디서든 참조할 수 있고 값을 변경할 수 있기 때문이다.
    또한 파라미터나 리턴값으로 교환해야 할 정보를 글로별 변수를 경유(사용)하여 건네주면 함수의 역할이 불분명 해지고 흐름도 애매해 진다. 마지막 이유로는 "글로벌 변수는 하나밖에 없다"는 것이다. 이는 어디서 이값을 변경했는지 알 수 없게 하는 지름길이고 실무에서도 간혹 발생하긴 하지만, 이 하나밖에 없는 변수가 버전업으로 두개가 필요하게 되었을때 확장도 대형 프로젝트에서는 힘들어진다.
    따라서 static에서 public은 final을 붙여 상수로 사용해야지 그 외의 용도는 자제하는 것이 좋을 것이다.
    • (참고) final 초기화에서의 주의점. 예를 들어 다음과 같은 코드를 보았을때 우려되는 점은 무엇인가?
    public final static Color WHITE = new Color(255, 255, 255);
    위의 코드는 java.awt.Color에서 발췌한 것인데, final 변수는 한번 초기화 되면 변경이 불가능한데 object로 초기화 할 경우 WHITE라는 필드가 변경될 수 없는 것이지 그것이 가리키는 객체는 아니라는 점이다.
    과거 신규 서비스 개발시 final 변수 필드에 설정파일을 읽어 cache하는 singleton class의 특정 member 를 이용하여 초기화 할 경우 이 멤버값이 변경되면 final 변수의 값이 변경되었는데 프로그램에서는 이상한 짓을 하는 원인을 찾기가 상당히 어려웠던 경험을 하고 난 후 부터 이런 코드는 냄새나는 코드로 여겨지게 되었다.
    static은 글로벌변수와 동일하므로 남발해서는 안된다. static을 사용할 경우 다음 두가지는 최소한 기억한다.
    1. static field는 final의 경우와 달리 정말 "하나여도 되는지" 여부를 잘 생각해야 한다.
    2. static method는 주저하지 말고 쓰되 다음 두가지의 경우 매우 활용적이다.
      1. 다른 많은 클래스에서 사용하는 Utility Method 군을 만드는 경우. (주로 Utility Class의 method)
      2. 클래스 안에서만 사용하는 "하청 메소드(private method)". 이유를 예를 들어 설명하면, 아래와 같은 조금은 과장된 클래스가 있다고 하자.
                    public class T ..
    private int a;
    private int b;
    private int c;
    private int calc(){
    c = a + b;
    return c * c;
    }
    ....other method or getter/setter...
    위의 클래스 T의 경우 내부에서 calc라는 instance 함수를 사용하게 되면 c 의 값이 매번 변하게 된다. 이는 무심코 하는 실수로 클래스내에서 private method는 모든 멤버 instance 변수에 접근 가능하게 되면서 발생한다. c의 값이 변하지 않기를 바랄수 있다. 이때 안전한 방법은 다음과 같이 calc 하청 메소드를 static method로 수정하면 안전하다.
                private static int calc(int a, int b){
    int c = a + b;
    return c * c;
    }
    여기서 a와 b는 멤버 변수를 접근할수 없어 전달해야한다.(static에는 this가 없어 instance field를 참조할 수 없다는 것은 이미 위에서 설명했다.) 또한 c도 같은 이유로 사용할 수 없어 로컬 변수로 선언하고 사용하고 있다. 이럴 경우 메소드가 약간 커질수 있지만 instance member 변수를 안전하게 사용할 수 있다는 장점이 있다. 이것은 static을 다시한번 생각하게 하는 좋은 예가 되었을 것이다.

    2 Java는 Pointer언어이다? (Java에는 Pointer밖에 없다?) #

    2.1 Java는 primitive형을 제외하곤 모두 Pointer이다 #

    "Java에는 포인터가 없다" 라고 Java의 장점 이라고 생각하는 것은 입문자도 외우고 있다. 하지만 이 부분은 의외로 Java를 혼란스럽게 하는 주범이라고 생각한다. Java에 포인터가 없기는 커녕 primitive(int, short, char, long...등 JVM의 Heap에 object로 생성되지 않는것들)를 제외하면 "포인터 밖에 없는 언어이다"라는 명제가 성립되게 된다. 사실 여기서 포인터라고 함은 C 의 그것과는 조금 다른 reference(참조)이긴 하지만...
    "즉, 자바의 클래스형의 변수는 모두 포인터이다."

    2.2 null은 객체인가? #

    Java에서 공참조(힙에 실제로 참조되는 object가 없는 참조)의 경우는 당연히 객체가 붙어 있지 않다. 그러나, Java API 레퍼런스의 NullPointerException 항에는 다음과 같이 기술되어 있다.
    "object가 필요한 경우 application이 null을 사용하려고 하면 throw된다. 가령 다음과 같은 경우이다."
    • null object의 instance method 호출
    • null object의 field(member variables)에 대한 액세스 또는 그 값의 변경
    • null의 길이를 배열처럼 취득할 경우
    • null의 slot을 배열처럼 액세스 또는 수정
    • null을 Throwable처럼 throw 할 경우
    위에서 null object라는 말이 등장하는데 이는 공참조에 객체가 붙어 있지 않은 것이 아니라 null을 가리키는 객체라고 볼수 있다. 즉, 공참조라는 것은 JVM에서 봤을때 아무것도 참조하지 않는것이 아니라 null이라고 하는 object를 참조하고 있는것이다. 그러나 JSL 4.3.1에서는 다음과 같이 나와있다.
    "참조값(reference)은 이러한 객체의 포인터나 어떤 객체도 참조하지 않는 특수한 null참조가 된다"
    즉, 공참조는 어떤 객체도 참조하지 않는다고 단정하고 있다. 하지만 '==' 연산에 있어 두개의 객체가 모두 null이거나 동일한 객체 또는 배열 참조의 경우 true라고 되어있는것으로 봐서 서로 다른 두 객체가 동일한 null을 참조하고 있으므로 true가 된것이 아닌가 하는 생각을 할 수 있다.
    즉, null이 Object의 instance 형태는 아니지만 개념적으로 봤을때 null도 object라고 봐야 하지 않을까?

    2.3 String에 대하여 #

    String Object에 대한 생각.
                String str = "111222";
    String a = "111";
    String b = "222";
    String c = "111";
    String d = b;
    String t = str.substring(0,3); //111
    위의 소스를 보고 다음이 참인지 생각해 보자. (==연산자는 포인터의 비교이지 값의 비교가 아님)
    1. str == (a + b) ==> 이것은 두개의 참조와 하나의 참조를 비교했으므로 당연히 false이다.
    2. a == b ==> 이것은 당연히 false
    3. d == b ==> 이것은 동일한 reference이므로 true
    4. a == t ==> a 와 t 는 둘다 값이 "111"이다. 하지만 이것은 서로 다른 참조를 가져 false이다. 그렇다면 다음 5번도 false일까?
    5. a == c ==> 이것은 true이다. 아.. 4번과 혼란스럽다. 이것이 참인 이유는? ==> 이것의 해답은 JSR 3.10.5에 다음과 같이 나와 있기 때문이다.
    "동일한 내용의 문자열 리터럴에 관해서는 인스턴스를 하나밖에 생성하지 않는다."
    즉, 위의 a와 c 는 '=' 를 이용하여 문자열 리터럴을 생성하게 되는데 a 에서 이미 만들어 놓았으므로 c에서는 그것을 참조한다.

    2.4 객체지향의 캡슐화 파괴 주의 #

    "object pointer를 반환하는 getter method는 객체지향의 캡슐화가 파괴될 가능성이 있다." 이는 object형의 field(member variable)의 getter에서 이 object를 그냥 반환하면 이 object를 받은쪽이나 참조하고 있는 다른쪽에서 이 object의 내용을 변경하게 되므로 사실 캡슐화(은닉)는 이루어 지지 않았다고 봐야한다.
    "이럴 경우 object를 clone(복제) 하여 반환하지 않아도 되는지를 반드시 생각해 본다."
    object의 복사에는 shallow copy와 deep copy가 있다.
            //(참고)Member에는 두개의 field(Identity Class 형의 ID와 Family Class 형의 family)가 있다. 
    /** shallow copy */
    Member shallowCopy(){
    Member newer = new Member();
    newer.id = this.id;
    newer.family = this.family;
    return newer;
    }
    /** deep copy */
    Member deepCopy(){
    Member newer = new Member();
    newer.id = new Idetity(this.id.getId(), this.id.getName());
    newer.family = new Family(this.family.getFamilyName(), this.family.getFamilyInfo());
    return newer;
    }
    위 소스에서 보듯이 shallowCopy 는 object를 복사하여 반환한것 처럼 보이지만, 사실은 Member object만 새로 생성되었을뿐 Member의 field는 newer와 this 둘다 서로같은 힙의 id와 family를 참조한다. 하지만 두번째 method인 deepCopy의 경우 Member의 field를 새로 생성하여 복사하므로 서로 다른 id와 family이다.
    "Java에서는 clone이라는 method가 준비되어 사용되는데 이는 기본이 shallow copy임을 명심해야 한다. deep copy를 사용하기 위해서는 clone method를 overload하거나 따로 만들어 직접 기술해야 한다." (참고) object를 immutable(변하지 않는, 불변의 객체)로 만드는 요령
    1. 모든 field(member variable)를 생성자(constructor)를 이용하여 초기화 한다.
    2. 모든 field는 private으로 선언하고, getter method는 만들되 setter는 기술하지 않는다.
    즉, 값을 변경하기 위해서는 object를 다시 만들어야만 하는 불편은 있지만 안전하게 사용하려 할때 유용하다.

    2.5 배열에 대하여 #

    2.5.1 배열은 object 인가? #

    JVM에서 배열은 object로 취급되어 object와 같이 aload, astore와 같이 bytecode로 기술되어 진다. int[] iarr = new int10; 에서 보는것과 같이 new로 Heap 영역에 object를 생성하므로 object임을 알 수 있다.

    2.5.2 배열의 length는 왜 field(member variable)인가? #

    String의 길이를 구할때는 length()와 같이 method를 이용하는데 배열은 object임에도 불구하고 legth와 같이 필드로 되어있다. '이래도 Java가 완전한 객체지향 언어인가' 라는 의심이 들게 한다. 그렇다면 length가 public이므로 array.length = 100; 과 같이 하면 배열 크기가 변경되나?
    이것은 컴파일 오류가 난다. length는 final이라 값을 변경 할 수 없다는 것이다. 그렇다면 final field로 한 이유는 무엇이냐는 Java News Group에 찾아보면 대부분이 "효율을 위해서"라고 되어 있다. JIT compiler를 사용하지 않는한은 method보다는 field가 빠른건 당연한 것이다.
    그런데 정말 알수 없는것은 byte code에서는 arraylength라는 전용명령으로 컴파일 된다. 즉, length는 Java의 문법이 어찌되었든 JVM레벨에서는 field가 아닌것이 분명하다. 그렇다면 효율을 위해서 field로 했다는 것은 도데체 무슨 소리인가?
    전문가들의 대답에는 이것은 Java의 수수께끼 중 하나라고 대답하는 사람이 많다고 한다.^^;

    2.5.3 final과 배열에 대하여... #

    우리가 흔희 앞에서도 나온바 있지만 final은 값을 변경할 수 없는 것이라고만 생각하지 object로 되어 있을 경우 그 object는 변경 가능하다는 것을 잊곤한다. 배열도 object이므로 마찬가지다.
    final int[] iarr = new int[5]; 일경우 iarr = null; 은 에러가 나지만 iarr[3] = 5; 는 에러가 나지 않는다. 즉, final이 지정되어 있는것은 iarr이지 iarr이 가리키는 곳 배열의 요소가 아닌 것이다.

    2.5.4 "Java에서의 다차원 배열은 존재하지 않는다." #

    가령 2차원 배열 처럼 보이는 int[][] iarr 또는 int[] iarr[] 은 일차원 배열 두개이지 2차원 행열 구조가 아닌것이다. 즉, 두개의 배열은 각각이 배열로 되어 있는 것이지 테이블(행열)형태가 아니다.

    2.6 인수(parameter/argument)전달의 개념 #

    2.6.1 "Java에서 parameter(argument) 전달은 무조건 'call by value' 이다" #

    primitive type의 경우 호출한 쪽의 변수값은 호출 받은 method내에서 값이 변경되어도 변경되지 않는다. reference type의 경우도 reference되는 object에 대해서는 함께 변경되지만 reference pointer는 call by value이다. object를 가리키는 pointer는 call by value로 변경되지만 Heap의 실제 object내용은 변경되지 않는다.

    2.6.2 "C와 같은 언어는 static linking이지만, Java는 dynamic linking이다." #

    따라서 Java는 Class 파일이 처음에 한꺼번에 memory에 읽혀지는 것이 아니라 런타임시에 그것이 필요해 졌을때 읽혀지고 링킹된다. static field의 영역도 Class가 읽혀지는 시점에 비로서 확보된다. 이렇게 되면 최초 가동시간이 단축되고 끝까지 사용하지 않는 Class의 경우 신경쓸 필요가 없어지게 된다.
    따라서 static field는 프로그램이 시작되어 해당 Class가 필요해 졌을때 JVM이 알아서 load/link 해 준다. 즉, static field는 프로그램이 실행되기 시작할 때부터 끝날때까지 계속해서 존재하는 것이라고 보면 된다. (참고) 링킹(linking)의 의미
    link된다는 것은 Class가 memory에 loading될 때 특정 메모리 번지에 loading되는데 이 메모리 번지는 loading될때 마다 다른 번지수에 loading된다. 이때의 메모리 주소값(Java에서는 실제 메모리 값이 아닐 수 있다)을 현재 실행중인 프로그램에서 알 수 있도록 하여 해당 Class에 대한 참조가 가능하도록 연결하는 과정이다.
    정적(static) link라는 것은 이러한 메모리에 대한 주소 정보를 컴파일 시에 compiler가 미리 결정하는 것이고, 동적(dynamic) link라는 것은 프로그램 수행 중 결정되는 것을 의미한다. 정적인 link의 경우 직접적으로 메모리의 번지값이 할당 되는 것이 아니라 offset값(기준위치로 부터의 index값)으로 연결시킨다.

    2.7 GC 에 대하여 잠깐! #

    2.7.1 "Garbage Collection은 만능이 아니다." #

    Java에는 free가 없다. GC가 알아서 해준다. 하지만 GC 수행중에는 프로그램이 멈추는 것과 동일한 증상이 나타나기 때문에 GC가 자주 발생하지 않도록 프로그램 해야 한다. 서비스 되고 있는 시스템에서도 가끔 시스템이 응답이 늦어지는 시점이 있는데, 이는 GC가 수행되고 있는 중이 대부분이다.
    그렇다면 GC가 자주 발생하지 않도록 해야 하는데 가장좋은 방법은 무엇일까? 그것은 바로 불필요한 객체를 생성하지 않는 것이 아닐까?
    개인적으로 Java에 free가 없는것이 너무나 든든하게 느껴진다. 이유는 두개의 변수가 Heap내의 하나의 object를 reference하고 있을 경우 실수로 하나의 변수만 free해 버리면 나머지 하나는 dangling pointer라하여 reference pointer가 모르는 사이데 사라져 버려 곤경에 처하는 것을 예방해 주기 때문이다.
    참고로 Object class에는 finalizer라는 method가 있어 GC 수행시점에 호출되는 method가 있지만 이것은 GC가 언제 수행될지 알 수 없으므로 과신하지 말아야 할 것이다.

    2.8 Java Pointer 결론 #

    2.8.1 "결국 Java에는 pointer가 있는 것인가, 없는 것인가?" #

    Java는 Heap내의 Object를 참조(reference)하고 있고, 참조는 결국 개념이 포인터와 같은 것이므로, "Java에는 pointer가 없다"는 것은 어불성설이다.
    // 이부분에 대해 Object를 이해하시면 족히 이런 문제는 사라질것으로 봅니다.
    // 클래스에 대한 인스턴스(object)들은 reference로 밖에 가질(참조될)수 없기 때문입니다.
    // 컴파일러 입장이 아닌 언어 자체의 사상을 가지고 쉽게 이해시키는 것이 좋을것 같습니다.
    JSR 4.3.1을 보면 다음과 같은 말이 나온다.
    "참조값(reference)은 객체의 pointer이거나, 또는 어떠한 객체도 참조하지 않는 특수한 null 참조가 된다"
    또한 java.sun.com의 Java programmer's FAQ에 "Java는 pointer가 없다고 하는데, linked list는 어떻게 만들어야 하나?"라는 질문에 다음과 같이 답변이 나와있다.
    (답변) Java에 관한 많은 오해중에서 이것이 가장 심각한 것이다. 포인터가 없기는 커녕 Java에 있어 객체지향 프로그래밍은 오로지 pointer에 의해 행해진다. 다시 말새 객체는 항상 포인터를 경유해서만 access되며 결코 직접적으로 access되지 않는다. pointer는 reference(참조)라고 불리며 당신을 위해 자동으로 참조된다.
    "Java에는 pointer가 없고 주장하는 모든 서적과 글들은 Java의 reference사양에 모순된다고 봐야 할 것이다."

    3 상속과 interface의 문제점 #

    3.1 상속 #

    3.1.1 상속에 있어서의 생성자(constructor) #

    "child의 default 생성자가 있으면 그 생성자에는 parent의 생성자(super()) 호출이 compile시 자동 삽입된다." 따라서 super() 이전에 다른 코드가 있으면 object가 생성되기 이전이므로 오류를 발생하게 된다.

    3.1.2 "down cast는 본질적으로 매우 위험하다" #

    down cast - child의 type으로 parent를 casting - 는 parent 형태의 type이 정말 child type인지 compile시에는 알 수 없다. 실행시에 type check가 이루어 지므로 runtime시에 ClassCastException이 발생할 가능성이 커진다.
    "프로그래밍시 오류는 가능한한 compile시에 처리하는것이 좋다."

    3.1.3 "추상클래스에 final이 있으면 compile error이다" #

    abstract method가 있는 클래스는 추상 클래스이고 추상클래스는 상속되지 않으면 아무런 의미가 없기 때문이다.

    3.2 interface #

    3.2.1 "interface는 interface일뿐 다중 상속의 대용품이 아니다." #

    interface를 method signature - 추상클래스와 같이 구현부는 없이 선언부만 있는 method - 의 용도로 생각하는것이 Java에서는 옳다. 즉, interface는 final field와 abstract method가 있는 클래스와 동일하긴 하지만 상속의 의미와는 그 용도가 다르다. 공통된 type을 정의하는것으로 보는것이 맞는 의미일 것이다.
    또한 interface는 클래스를 재이용하기 위해 상속을 사용하여 캡슐화의 파괴를 수반하는 것을 방지하는 기능이있다. 상속을 사용하면 모두 구현후 마치 소스 코드가 여기저기 천 조각을 주워 모아 만든 '누더기'같이 보이는 것에 한숨을 쉰 경험이 있을 것이다. 이 부분을 interface로 구현하면 보다 깔끔한 코드가 나오게 된다. 물론 public과 protected를 적절히 잘 사용해도 되긴 하지만 말이다.
    하지만 상속은 메소드 오버라이드한 경우 클래스를 마음대로 개조해 버린 셈이 되므로 어디선가 묘한 모순이 발생하게 될 가능성도 높아질뿐 아니라 추상클래스의 경우 실제 구현부가 어디에 위치하는지도 에매하게 느껴질 수 있어 불안한 코드가 되고 만다.

    3.3 상속 제대로 사용하기 #

    "그렇다면 제대로 된 상속은 어떻게 판단할 수 있을까?"
    상속은 'is a'관계가 성립해야 올바르다. 즉 '서브클래스(자식) is a 슈퍼클래스(부모)'가 성립해야 한다. 예를 들면 Red is a Color는 올바른 명제이지만 Engine is a Car는 'has a'관계이므로 상속이라고 볼 수 없다. "따라서 'has a'관계는 상속이 아니므로 composition과 delegation을 이용하면 된다."
    composition은 '객체를 field가 갖게 하는 방법'을 의하므로 'has a'관계가 정확히 성립한다. "상속 대신 composition과 delegation(조작이나 처리를 다른 객체에 위임)을 사용하면 다음과 같은 이점이 있다."
    1. 상속에서는 슈퍼클래스가 허용하고 있는 조작을 서브클래스에서 모두 허용해야 하지만, composition과 delegation에서는 조작을 제한할 수 있다.
    2. 클래스는 결코 변경할 수 없지만, composition하고 있는 객체는 자유롭게 변경할 수 있다. 예를 들면 학생 클래스가 영원이 학생이 아니라 나중에 취직을 하여 직장인 클래스가 될수 있다.
    상속을 composition과 delegation으로 변경하는 요령은? 여기서 Shape를 상속한 Polyline과 Circle을 변경한다면 다음과 같다.
    1. Shape(부모)의 공통된 내용을 구현한 구현 클래스(ShapeImpl)를 만든다.
    2. Polyline과 Circle 클래스에서 ShapeImpl을 composition하고 부모와 공통되지 않는 method를 각각 위임 받는다.
    3. ShapeImpl 클래스의 method를 추출한 ShapeIF interface를 작성하고 Polyline과 Circle에서는 implements 한다.

    4 package와 access 제어에 관한 이해 #

    4.1 package #

    4.1.1 "package는 '계층구조' 인가?" #

    처음 Java를 접하면서 package에 대해 이해할때 마치 파일시스템과 같은 계층구조라고 이해하게 되어 ' import /test/*.class '는 왜 안되는지 의아해 했던 기억이 있다. 그리고 부모 directory에 있는 클래스에서 왜 자식 directory에 있는 Class를 import없이 사용할 수 없는지도 이상했다.
    즉, package에서 동일 부모라도 서로 다른 package는 완전히 별개의 package였던 것이다. 이 부분에 관해서는 JLS 7.1 에서 다음과 같이 기술되어 있다고 한다.
    "package가 계층적인 이름 구조로 되어 있는 것은 관련된 package를 일정 규약에 따라 체계화하기 위해서이고, package 안에서 선언되어 있는 top-level형과 동일한 이름을 가진 서브 package를 갖는 것이 금지되어 있는 점을 제외하면 특별한 의미는 없다."
    즉, Java에서는 package이름을 계층적으로 명명할 수 있을뿐 package구조 자체에는 어떤 계층적인 의미 부여도 할 수 없는 것이다. 다시 말해서 Java에서는 package이릉을 계층적으로 명명할 수 있을 뿐 구조자체는 평평한 것이다. 실제로 바이트 코드의 내용을 보면 깨어진 내용중에 java/lang/String과 같이 완전한 한정이름을 class이름으로 사용됨을 알 수 있다.

    4.1.2 "compiler 가 인식하는 class검색 순서(소스코드내 클래스가 발견될 경우 그 클래스의 위치를 찾는 순서)" #

    1. 그 class자신
    2. 단일형식으로 임포트된 class
    3. 동일한 패키지에 존재하는 다른 class
    4. 온디멘드 형식(..* 형태) 임포트 선언된 class

    4.2 access 제어 #

    public은 다른 package에서 참조 가능하고, 무지정할 경우 동일한 package내에서만 참조 가능하다.

    4.2.1 "interfacde member의 access 제어" #

    interface의 member field/method는 모두 public이다. interface member에 protected나 private을 지정할 수는 없다. 또한 public을 지정할 필요도 없다. 지정해도 상관없지만 JLS 9.4에서는 다음과 같이 명시되어 있다.
    "interface의 method에 대하여 public 수식자를 지정하는 것이 허용되고 있지만, style로서는 전혀 권장할 수 없다."
    즉, interface member는 모두 public이라 되어 있는 것이다. 또한 James Gosling도 집필에 참가한 '프로그래밍 언어 Java 3판'에서는 다음과 같이 기술되어 있다고 한다.
    "public이 아닌 member를 interface에게 갖게 하는 것은 아무런 의미가 없다. interface의 member에 대한 access제어에 interface 자신의 access 제한을 적용하는 것이므로 이것은 아무런 의미가 없다."

    4.2.2 그렇다면 interface를 다른 package에 대하여 숨기고 싶으면 어떻게 하는가? #

    그것은 interface 자체 선언에 public이 아닌 것을 적용하면 되는 것이다. member별로 제어할 수 없어 불편한 면도 있지만, 나름대로 그럴 듯한 규칙이다. 하지만 이것은 정말 이상한 논리가 아닐수 없다. public이 아닌 interface에 public method가 무슨 의미가 있는지 알 수 없기 때문이다. 이 interface를 구현한 클래스에서도 method는 모두 public이 되어야 하는데, 이것도 아무래도 이상하다.

    5 기타 Java 기능 #

    5.1 Thread #

    5.1.1 "Multi Thread에서는 흐름은 복수이지만 data는 공유될 수 있다." #

    Multi processing에서는 흐름은 복수이지만 data는 독립되어 있다. 하지만 Multi Thread에서는 Heap과 static영역에 관한 한 2개 이상의 Thread 사이에 공유가 이루어 진다. 따라서 2개 이상의 Thread에서는 동일한 static field를 참조할 수 있고, 동일한 객체에 접근할 수도 있다. 그러나 stack만은 Thread별로 독립되어 있다. stack은 method에 들어가는 시점에 확보되고 빠져 나오는 시점에 확보되고 빠져 나오는 시점에 Free 되므로 2개 이상의 Thread에서 공유할 수는 없는 것이다.

    5.1.2 "Thread는 객체와 직교하는 개념이다." #

    Multi Thread는 어디까지나 Thread라는 처리 흐름이 여러 개 존재할 수 있다는 의미이다. 요약하면 다음 3가지 이다.
    1. Multi Thread에서는 Thread라는 처리 흐름이 2개 이상 존재할 수 있다.
    2. 어떤 Thread에서 움직이기 시작한 method가 다른 method를 호출 했을때 호출된 측의 method는 호출한 측의 method와 동일한 Thread에서 동작한다.
    3. Thread의 경계와 객체의 경계는 전혀 관계가 없다. 즉, Thread와 객체는 직교하고 있다.

    5.1.3 "Synchronized 의 이해" #

    Multi Thread 기반의 programming시에 synchronized를 놓쳐 자주는 일어나지 않으나 뭔가 잘못되어 가는것을 경험한 적이 있다. 즉, 이것이 원인이 되어 버그가 발생한 경우 그 버그는 재현성이 지극히 낮아지기 때문에 꽤 고생을 하게 된다. 이런 사태가 발생하게 되면 버그의 원인을 찾기가 어렵게 되고 해당 application은 언제 발생할지도 모르는 오류가 있는 상태 그대로 운영되기 때문에 심각성이 내포되어 있다고 할 수 있다.
    이러한 사태를 방지하기 위해서는 critical section을 2개 이상의 Thread가 동시에 실행되지 않도록 '배타 제어'를 해야한다. 그 키워드가 바로 synchronized이다.
    synchronized에는 synchronized(obj){} 형태와 method에 synchronized 를 붙이는 두가지 방법이 있는데, 이 둘은 범위만 같다면 같은 의미이다. 예를 들어 설명하면, 아래의 소스에서 method1()과 method2()는 동일하다.
            synchronized void method1(){
    ...
    }
    void method2(){
    synchronized(this){
    ...
    }
    }
    이렇게 동일한 의미를 두가지로 만든것은 method단위로 synchronized를 걸 일이 그만큼 많다는 것을 의미한다. 많이들 오해하고 있는 부분이 위의 소스에서 알수 있듯이 method에 synchronized를 사용한다는 것은 '그 객체에 해한 조작은 동시에 하나의 Thread라는 것이지 method 호출이 하나의 Thread가 아닌것이다'
    그렇다면, Thread A가 obj의 Lock을 설정하고 있는 상태에서 다시 한번 Thread A 자신이 obj의 Lock을 설정하면 어떻게 될까? 이 경우 Thread A는 이미 이 obj에 대하여 Lock을 보유하고 있으므로 기다리지는 않아도 된다. 위의 소스에서 method1에서 method2를 호출한다면?
    method1에서 이미 obj의 Lock을 보유 했으므로 method2의 synchronized(this) 부분에서는 Lock을 기다리지 않아도 된다.
    즉, Lock의 기준이 특정Thread에 있어서 Lock의 기준이 method가 아닌 object인 것이다. 이 규칙 덕분에 synchronized method도 재귀호출이 가능해지고, synchronized method가 동일한 instance의 synchronized method를 호출할 수 있는 것이다.
    주의할 점은 static method에 synchronized가 있다면 static은 this참조가 없다고 위에서 설명하였으므로, 이 클래스의 Class 객체를 Lock하게 된다. 기준이 xx.Class가 되는 것이다.

    5.1.4 "Thread 사용법의 정석은?" #

    Thread 사용법에는 다음 두가지의 정석이 있다.
    1. Runnable을 implements하고 Thread의 참조를 보유(composition) 하는 방법. 이경우는 단지 Runnable만 implement함으로서 해결되는 경우가 대부분이긴 하지만, 그 class 내에서 해당 class의 Thread를 조작하게 된다면 composition한 Thread 객체에 delegation하면 된기 때문이다.
    2. Thread class를 상속하는 방법. JDK의 소스를 보면 Thread class에는 Runnable을 implements 하고 있다. 그리고 run method는 native method이다. 따라서 Thread를 상속한 모든 클래스는 사실 Runnable을 implements하고 있는 것이다. run method는 abstract가 아니므로 구현되어 있고 우리는 이를 오버라이드하여 사용하고 있다. 이 방식을 사용하면 Thread의 method를 안팍으로 자유롭게 호출할 수 이지만, 이미 다른 class를 상속하고 있다면 이 방식을 사용할 수는 없다.
    JDK API Reference의 Runnable에 과한 설명중에 다음과 같은 내용이 있다.
    "Thread class의 method중 run method만을 오버라이드하여 사용하는 경우는 Runnable interface만 implements하여 사용하면 된다. 왜냐하면, class의 기본적인 동작을 수정 또는 확장하지 않는한 그 class를 sub class화 하는 것은 바람직하지 않기 때문이다."
    그렇다면 위에서 언제나 1)번 방식을 사용하면 되는 것 아닌가 라는 의문이 생기게 된다. 왜 귀찮게 2)의 방법을 고민하는 것인가, 극단적이긴 하지만 만일에 사태에 이 클래스가 다른 클래스를 상속받게 되는 경우도 있을수 있는데.
    하지만 이것은 아닐것이다. 만약 이렇다면 Thread class가 Runnable을 implements할 필요가 없었을 것이기 때문이다. 또한 Thread는 생성자의 인수로 Runnable의 reference를 취득한 후 계속해서 그것을 보유한다는 것도 이상하다. Thread에 있어 Runnable이 필요한 것은 start() 때 뿐이므로 start()의 인수로 Runnable을 건네줘도 좋을 것이다.
    그럼에도 불구하고 굳이 Thread에서 계속적으로 Runnable을 보유하고 있는 것은 Runnable객체와 Thread를 강하게 결합시키려는 의도 때문이다. 이것은 의도적으로 위의 2)의 방법을 권장하는 듯한 느낌을 받게 하는듯 하다.
    그렇다면 API Reference의 말은 단지 상속을 피하라는 의미만 있는 것인가? 마지막으로 한가지 추정이 되는 부분은 Thread에는 suspend()나 stop()등과 같은 method가 현재 모두 deprecate되었다. 또한 sleep()이나 yield()는 모두 static method이므로 굳이 Thread 객체를 보유할 필요가 없다.
    그렇다면 위의 1)의 방법에서 Thread객체를 composition할 필요가 없어진다.
    "그렇다면 Thread를 아무도 보유하지 않고 Runnable만 implements한 방식이 최선인가?"
    무엇이 정답인지 도무지 알길이 없다. ^^;

    5.2 Exception #

    5.2.1 "finally 절은 반드시 어떠한 경우에도 실행되는가?" #

    try ~ catch 문의 finally 절은 'loop라면 break, method라면 return 절'을 만나도 뒤에 있는 finally절은 수행된다. 하지만 다음의 경우는 그렇지 않다.
            try{
    ...
    System.exit(1);
    }catch(...){
    }finally{
    ... //이 부분은 실행되지 않는다.
    }

    5.2.2 "예외의 종류 3가지 (Error, RuntimeException, 그밖의 Exception)" #

    5.2.2.1 Error #
    이에 관해선 JLS 11.2.1에 다음과 같이 기술되어 있다. "체크되지 않는 예외 클래스(Error와 그 Sub class)는 프로그램안의 다양한 위치에서 발생할 가능성이 있으며, 회복이 불가능하기 때문에 컴파일시 체크되지 않는 것이다. 이러한 예외를 프로그램에서 선언한다고 해도 난잡하고 무의미한 것이 될 뿐이다."
    Java의 클래스 librury에서 Error의 sub class를 살펴봐도 AWTError, LinkageError, ThreadDeath, VirtualMachineError 등 'catch해도 소용 없을 것' 들 뿐이다. (OutOfMemoryError는 VirtualMachineError 아래에 위치한다.)
    5.2.2.2 RuntimeException #
    위의 Error 이외의 Exception들은 application에서 catch할 가능성이 있는 예외들이다.(버그가 없으면 발생하지 않는 예외들) 그리고 RuntimeException은 '어디서든 발생할 가능성이 있는 예외'이다. RuntimeException의 sub class로는 NullPointerException, ArrayIndexOutOfBoundException, ClassCastException 등을 들 수 있다. '이러한 예외는 버그가 없는 한 발생하지 않으므로 일일이 throws 를 작성하지 않아도 된다.'
    프로그램에 버그가 없는 한 발생할 수 없는 예외가 발생한 경우 C 언어와 같이 영역 파괴가 일어나기 쉬운 언어라면 프로그램 전체를 종료시키는 것이 정답이겠지만, Java와 같이 영역파괴가 일어나지 않도록 실행시 체크(JVM Classloader의 formal verification process)를 하고 동적으로 프로그램을 load하는 언어에서는 국소적인 NullPointerException 때문에 프로그램 전체를 중지시켜서는 안 될 것이다.
    따라서, RuntimeException은 catch하지 않는 것이 바람직하다고 볼 수 있다. 버그가 있는 프로그램은 신속히 종료시키는 것이 대부분의 경우 최선의 방책이라 생각하기 때문이다.
    5.2.2.3 그밖의 Exception #
    위의 RuntimeException이외의 Exception의 sub class는 사용자의 잘못된 조작 등으로 인해 프로그램에 버그가 없어도 발생할 가능성이 있고 그에 대하여 프로그램이 확실히 대응해야 하는 경우에 사용된다. 예를 들면 FileNotFoundException등이다.
    그런데 개발하다 보면 이상하고 의아한 것이 하나 있다. 숫자 부분에 문자를 넣었을때 발생하는 NumberFormatException이다. 이것은 이상하게도 RuntimeException의 sub class이다. 이것은 RuntimeException이 아니었으면 하는데 NumberFormat체크는 Runtime시에만 가능한 모양이다.

    5.2.3 "OutOfMemoryError는 어떻게 처리해야 하는가?" #

    예전에 Swing에서 Tree구조를 이용하는 프로젝트를 한적이 있다. 이때 Tree에 branch와 node가 무수히 생기자 JVM은 OutOfMemoryError를 내뱉었다. 이에 급한 마음에 OutOfMemoryError를 catch하여 사용자에게 재시작을 요청하는 Dialog를 띄우도록 수정하였다면 이 Dialog가 과연 떳을까? 현재 메모리가 부족한 판에 Dialog를 띄울 메모리가 남아있질 않았던 것이다. 다행히 Dialog가 떴어도 작업은 계속되지 못했을 것이다. NullPointerException가 나기 때문이다.
    원인은 나중에 찾았는데, Tree구조에서 부모부터 자식들을 붙이는 순으로 Tree를 구성하는데 자식들을 줄줄이 붙여나가다가 메모리 부족현상이 발생하였고 NullPointerException은 자식이 없으니 클릭하는 순간 null을 반환하여 발생하였던 것이다.
    OutOfMemoryError의 가장 좋은 해결책은 불필요한 객체를 만들지 않는 것이었다. 그리고 Tree생성시에도 자식부터 만들고 부모를 만드는 순서로 프로그램을 수정하여 프로젝트를 정상적으로 마칠수 있었다.
    마지막에 드는 심정은 프로그램이 OutOfMemoryError를 일으키는 원인이 과연 이렇게 구성되어 발생했는지 어떻게 알수 있을까 하는 의문이다.

    5.3 Object Serialize #

    Java에서는 ObjectOutputStream의 writeObject() method에 데이타 구조 저장소의 참조만 건네주기만 하면 그 안에 있는 모든 객체를 1차원 stream으로 출력해 준다. (파일이나 ByteArrayOutputStream을 이용한 메모리로) 단, static field는 Serialize되지 않는데 이는 Serialize의 대상이 instance 객체뿐이기 때문이다.

    5.3.1 "Serialize를 위해서는 marker interface인 java.io.Serializable interface를 implements해야한다." #

    여기서 marker interface는 java.lang.Cloneable과 같이 method와 field의 정의는 없지만 객체 Type을 위한 interface이다. 예전에 Serialize를 이용하여 데이타를 유지하는 프로젝트를 한 적이 있는데 그때 생각했던것이 '모든 class들이 기본적으로 Serializable을 implements하고 있으면 편할텐데..'라는 생각이었다. 하지만 이것은 상당히 위험한 발상이었다.
    Serializable이 기본으로 implements되어 잇으면 엉뚱한 객체까지 Serialize되고 그것을 알아채지도 못하는 사태가 일어날 가능성이 높다. Serializable이 optional인 이유는 이러한 이유 때문이리라..

    5.3.2 "super class는 Serializable이 아닌데 sub class만 Serializable인 경우의 문제점" #

    Serialize을 이용하여 프로젝트를 할때 한번쯤 실수할 수 있는 부분이 상속된 class의 Serialize이다. 컴파일 에러도 없고 Deserialize도 잘 되었다. 하지만 키가 되는 값이 null과 0이었다. 영문을 몰라 다른곳을 헤매여도 보다가 결국 찾은 원인은 부모의 field는 Serialize되지 않는다는 것을 알게 되었다. transient와 마찬가지로 형식별 default 값으로 채워졌었다. 이는 컴파일과 실행시 아무런 오류없이 실행되어 나를 힘들게 하였기에 Java가 원망스러웠던 기분좋은 추억이다. ^^;

    5.3.3 "transient field의 복원(?)관련" #

    Serialize를 이용한 프로젝트를 할때는 writeObject와 readObject를 이용하여 기본적으로 제공하는 Serialize를 customizing할수있다.
    Serializable에 대한 API reference에도 다음과 같이 나와있다.
    "Serialize와 Deserialize에 대한 특별한 handling을 위해서는 다음 두개의 특별한 메소드를 구현하면 된다."
    private void writeObject(java.io.ObjectOutputStream out) throws IOException;
    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
    이 두 method가 private으로 되어 있는 것을 보고 처음에는 의아해 했었던 기억이 있다. 이를 protected나 public으로 하면 제대로 동작하지 않는다. 이는 override가 이니기 때문이다. 사실은 속에서 reflectiond을 이용하여 강제적으로 호출되고 있는것이다. reflection에서는 private method까지 찾을 수 있기 때문이다.
    또한 private으로 한 가장 큰 이유는 Serialize를 객체자신이 직접 해야 안전하다는 의미도 있지 않을까 하는 생각도 든다. 다시 본론으로 들어가서 transient를 복원하는 것에 얘기를 하자면, 사실 transient는 Serialize대상에서 제외되는 것인데 복원을 할 수 있다는 말이 안된다. 하지만 프로젝트를 진행하다 보면 logic상 가능한 경우가 많이 있다.
    즉, 모든 field를 Serialize하지 않고 필요한 것만 하고 특정 field는 Serialize한 field들을 이용하여 복원하는 방법이다. 또한 Serialize당시의 객체 상태와 Deserialize시의 객체상태가 서로 다를 수 있는 field도 그것에 해당된다. cafeid만으로 나머지 field는 DB에서 읽어오게 한다면 나머지 field는 transient로 처리하고 Deserialize시 readObject()에서 복원하는 것이다.

    5.3.4 "Stack Overflow에 주의하라!" #

    Serialize를 하다보면 참조로 연결된 객체를 recursive하게 거슬러 올라가며 이것이 너무 깊어지면 Stack Overflow가 발생한다. 가령 linked list같은 경우이다. 이것을 Serialize하면 그 요소수만큼 recursive 호출이 발생한다. 과거(JDK1.3.0시절) 프로젝트 당시 JVM이 5111에서 Stack Overflow가 발생했던 기억이 있다.
    물론 실행시 java option에 -Xss 를 이용하여 statck 크키를 조절할 수 있지만 이것은 개발자가 아닌 실행하는 사람들에게 부담이었다. JDK의 LinkedList class의 소스를 보면 writeObject()와 readObject()를 다음과 같이 변경하고 있다.
            private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException {
    s.defaultWrtieObject(); //이 코드는 무조건 들어가게 되는데 이곳 소스의 System.arraycopy()에서 overflow발생한다.
    s.writeInt(size); //이부분이 실제 추가되어 Stack Overflow를 예방한다.
    for(Entry e = ...)
    s.writeObject(e.element);
    }
    ...
    }
    //readObject()도 이와 같은 개념으로 변경되어 있다.

    5.4 "nested class / inner class / 중첩클래스" #

    5.4.1 "중첩클래스의 개념" #

    개인적으로 중첩클래스를 어떠한 경우는 사용하지 않으려 한다. 사용하기가 만만치 않고 코드 읽기가 힘들어 지기때문이다. 하지만 '어떤 클래스 내에서 은폐할 목적으로 사용하는 클래스가 있다면 이것을 사용해야 한다' 실제로 Java의 AWT 클래스 Event Handler를 비롯하여 많은 클래스에서 중첩클래스를 사용하고 있다. 또한 내부 class는 그것을 둘러싸는 class의 instance(enclosing object라고 하는)의 field를 참조 할수 있는것도 장점이다. 하지만 이는 내부클래스가 아닐경우 부부 클래스를 new해서 사용하는것과 별반 다를께 없지 않은가.

    5.4.2 "내부클래스는 부모의 참조를 몰래 보유하고 있다." #

    내부 클래스의 instance는 부모의 instance에 대한 참조를 몰래 보유하고 있기 대문에 위에서 얘기한 부모의 field를 참조할 수 있는 것이다. 그러므로 static method에서는 내부클래스를 생성할 수 없다. 다음 예를 보면 바로 알수 있다.
            class Test{
    class InnerClass {
    int i;
    ...
    }
    public static void main(String[] args){
    InnerClass icls = new InnerClass();
    ...
    }
    }
    이 소스를 compile하면 다음의 오류가 발생한다. "non-static variable this cannot be referenced from a static context..." main method는 static이므로 this를 참조할수 없다는 것이다. 이는 InnerClass가 new 되면서 외부 클래스 Test의 this를 보유해야 하는데 여기서 static을 만나니 오류를 표출시킨것이다. 물론 일반 instance method에서는 오류가 나지 않는다.

    5.4.3 "local inner class에 대하여" #

    local inner class라 함은 method내에서 선언된 inner class이다.
            public class OuterClass {
    public int get(){
    int i = 9;
    int id = 99;
    int id2 = 99;
    final int id3 = 100000;
    class LocalInnerClass {
    int id = 100;
    LocalInnerClass(){
    System.out.println("LocalInnerClass");
    }
    int getId(){
    return id3 + id;
    }
    }
    LocalInnerClass lic = new LocalInnerClass();
    return id + lic.getId();
    }
    public static void main(String[] args){
    OuterClass outer = new OuterClass();
    System.out.println("id = " + outer.get());
    //결과 값은 "100000(id3) + 100(LocalInnerClass.id) + 99(OuterClass.get())" 인 100199가 나온다.
    }
    }
    위 소스의 LocalInnerClass는 get() 이라는 method에서만 보이는 class이다. 그리고 특이할 만한 부분이 OuterClass의 get() method에서 final로 선언된 id3이 LocalInnerClass에서 참조 가능해 진다. id2를 참조하면 compile error가 나지만 final로 선언된 것은 오류가 나지 않는다.
    이는 local variable은 method에서 나오는 순간 사라지는데, local inner class는 local variable보다 수명이 조금더 길기 때문에 final만 허용한 것이다.

    5.4.4 "anonymous class(무명클래스)에 대하여" #

    무명 클래스는 말그대로 이름이 없는 클래스이다.
            class AnonymousTest {
    private interface Printable {
    void print();
    }
    static void doPrint(Printable p){
    p.print();
    }
    public static void main(String[] args){
    doPrint( new Printable(){
    public void print(){
    System.out.println("this is new Printable print()");
    }
    });
    }
    }
    위 소스의 "doPrint( new Printable(){" 부분이 무명클래스 이다. compile을 수행하면 AnonymousTest$Printable.class, AnonymousTest$1.class, AnonymousTest.class 세개의 클래스가 생긴다. 여기서 AnonymousTest$Printable.class는 Printable interface이고 AnonymousTest$1.class이 무명클래스이다.
    이 소스를 보면 처음에 드는 의심이 Printable interface를 new 했다는 것이다. 여기서 굳이super class(이 소스에서는 interface)를 저정해야 하는 이유는 아무것도 상속하지 않는 무명 클래스의 instance를 만들어 봐야 의미가 없기 때문에 이렇게 한듯하다.
    "무명클래스는 어떤 class나 interface를 상속/구현 해야만 그 instance를 사용할 수 있는 것이다" 이처럼 무명 클래스를 사용하면 어떤 절차(수행)를 다른 method의 인수로 건네줄 수 있게 된다. 하지만 간단한 로직만 구현처리해야 한다.
    "무명클래스는 조금만 복잡해져도 급격히 소스의 가독성이 떨어지게 되므로 남용하지 않는 것이 바람직하다"

    6 이래도 Java가 간단한가? #

    6.1 method overload 에서의 혼란? #

    6.1.1 "overload란 이름이 가고 인수가 다른 method에 compiler가 다른 이름을 붙이는 기능" #

    overload를 구현하면 bytecode로 변환시 다른 이름으로 method가 변환되어 별개의 method로 처리된다. 이를 JVM에서 method descripter라 하여 Oolong asembler로 변화시 다른 형태의 method가 된다. 예를 들어 "void get(double d, long l)" 은 "get(DJ)V"로 변경된다. 여기서 D는 double, J는 long, V는 void를 의미한다.
    그런데 여기서 "get(DJ)" 부분만 method 이름이므로 return type이 다른 동일 method는 overload 할 수 없다. 따라서 overload는 정적(compile시 결정)이라는 명제가 성립니다. 그래서 동적으로 사용되면 compile시 오류를 표출한다. 아래의 소스를 보자. 여기에는 IFS라는 interface와 이를 implements한 Impl1, Impl2 라는 class가 있다.
            //IFS.java
    interface IFS {
    public String getName();
    }
    //Impl1.java
    class Impl1 implements IFS {
    public String getName(){
    return "Impl1";
    }
    }
    //Impl2.java
    class Impl2 implements IFS {
    public String getName(){
    return "Impl2";
    }
    }
    //main이 있는 OverloadTest.java
    public class OverloadTest {
    static void pr(int i){
    System.out.println("pr_int : " + i);
    }
    static void pr(String s){
    System.out.println("pr_string : " + s);
    }
    static void pr(IFS ifs){
    System.out.println("pr_string : " + ifs.getName());
    }
    static void pr_run(Impl1 i1){
    System.out.println("pr_run : " + i1.getName());
    }
    static void pr_run(Impl2 i2){
    System.out.println("pr_run : " + i2.getName());
    }
    public static void main(String[] args){
    OverloadTest test = new OverloadTest();
    test.pr(10);
    test.pr("Jeid");
    IFS ifs1 = new Impl1();
    test.pr(ifs1);
    IFS ifs2 = new Impl2();
    test.pr(ifs2);
    //pr_run(ifs1);
    //pr_run(ifs2);
    }
    }
    위의 소스를 수행하면 정상적으로 compile이 될것인가?
    당연히 잘 된다. pr()은 overload를 잘 구현했다. 하지만 소스 하단의 두 주석문을 풀면 어떻게 될까? 이는 compile오류를 낸다.
            OverloadTest.java:36: cannot resolve symbol
    symbol : method pr_run (IFS)
    location: class OverloadTest
    pr_run(ifs1);
    ^
    OverloadTest.java:37: cannot resolve symbol
    symbol : method pr_run (IFS)
    location: class OverloadTest
    pr_run(ifs2);
    ^
    2 errors
    실제 위 둘의 pr_run method는 bytecode로 변환시 "pr_run(Lpackage_name.IFS)V"로 동일하게 생성된다. 따라서 compile시에 오류를 표출한다. 이 소스를 보면 알 수 있듯이 "method overload는 정적(compile시)으로 미리 결정되며, 동적(실행시판단)으로 사용할수 없다."

    6.1.2 "그렇다면 overload에서 실제로 혼동되는 부분은 무엇인가?" #

    다음 소스를 보고 실제로 수행되는 method를 찾아보라.
            class OverloadTest2 {
    static int base(double a, double b){ ... } //method A
    static int count(int a, int b){ ... } //method B
    static int count(double a, double b){ ... } //method C
    static int sum(int a, double b){ ... } //method D
    static int sum(double a, int b){ ... } //method E
    }
    • base(3,4) 를 호출했을때 수행되는 method는? => 당연히 method A (3과 4는 정수라도 double이 되므로 정상적으로 수행됨)
    • count(3,4) 를 호출했을때 수행되는 method는? => B와 C중 갈등이 생긴다. 이럴경우 JVM은 가장 한정적(more specific)한 method를 찾는다. 여기서 3과 4는 정수형에 가까우므로 method B 가 호출된다.
    • count(3, 4.0) 을 호출했을때 수행되는 method는? => 이것은 4.0 이 double이므로 method C 가 더 한정적이므로 method C 가 호출된다.
    • sum(3,4.0) 을 호출했을때 수행되는 method는? => 이것은 당연히 type이 일치하는 method D.
    • sum(3,4) 를 호출했을때 수행되는 method는?? => 이런 코드가 소스내에 있으면 다음과 같은 compile 오류를 표출한다.
                 OverloadTest.java:48: reference to sum is ambiguous, both method sum(int,double)
    in OverloadTest and method sum(double,int) in OverloadTest match
    System.out.println("sum(3,4) = " + sum(3,4));
    ^
    1 error
    method D와 method E가 애매하다는 compile 오류이다. 이것은 둘중 어느것이 더 한정적인지 찾을 수 없으므로 bytecode 를 생성 할 수 없다는 것이다.
    "이렇듯 compiler에게 불필요한 오해(혼동)를 초래하는 overload는 사용하지 않는 것이 좋다. 개인적으로 overload를 가능한 사용하지 않으려 하고 필요하다면 인수의 개수가 다른 overload를 사용하는 편이다."

    6.1.3 (참고) 또다른 혼동, overload한 method를 override 하면? #

    overload란 compiler가 bytecode변환시 다른 이름을 붙이는 기능이라는 것을 위에서 설명했다. 따라서 super class에서 overload한 method를 상속하여 override하면 완전 별개의 method를 override한것처럼 JVM은 판단한다. 즉, overload와 override는 직교(전혀상관없는)하는 개념이다.

    6.2 상속/override/은폐 에서의 복잡함 #

    6.2.1 "Java class의 member 4 종류" #

    1. instance field
    2. instance method
    3. static field
    4. static method
    여기서 상속을 하였을 경우 runtime시 객체의 형식에 따라 선택되는 것은? 2번 instance method 뿐이다. 즉, 동명의 member를 sub class에서 선언했을 때 instance method만 override 되고 나머지는 완전 별개의 member가 된다. 따라서 위의 1,3,4는 sub class에서 동일하게 선언했을 경우 별개의 것으로 인식되며 compile시에 무엇을 access 할지 결정된다.
    즉, instance method는 override되지만 instance field/static field는 은폐된다. override는 실행시 객체의 형식에 따라 처리 할당되지만, 은폐의 경우는 compile시에 결정되고 만다.

    6.2.2 "override시 method 이름에 대한 함정" #

    과거에 코딩을 하던중 정말이지 어처구니 없는 경우를 당했다. override 하는 method이름을 잘못써서 황당한(?) 고생을 한적이 있다. super class의 writable()이라는 method를 writeable()이라고 override(?)하였는데 프로그램 수행 중에 writable()이 항상 false가 나오는 것이 아닌가? 그래서 소스를 추적추적 하다 몇시간을 허비했었던 기억이 있다.
    java를 접한지 얼마되지 않았고 요즘같이 eclipse같은 에디터도 없이 메모장에서 코딩하던 시절이라 더욱 고생했던것 같다. 한참 후에야 우연히 스펠링이 잘못된걸 알고 얼마나 황당했던지... 지금 생각하면 이것도 좋은 추억이리라.
    무조건 override 잘 되었을거라 생각 했던 나의 불찰도 있었지만 compile때나 runtime시 아무런 반응을 보이지 않던 Java도 원망스러웠다. 2003년도에 C#으로 프로젝트를 했는데 C#은 상속의 override에 대하여 "override void writalbe().."과 같이 정의시 override를 명시해야 된다는 것을 보고 상당히 마음에 들어 했던 기억이 있다. 가독성도 뛰어날 뿐더러 나의 몇시간동안의 헤메임도 없을 것이기 때문다. Java도 이렇게 확실한 명세였으면 정말 좋겠다.

    6.2.3 "또다른 나의(?) 실수 - 말도 안되는 오타" #

    위의 method이름을 잘못써서 고생하기 이전에 아주 비슷한 고생을 한적이 있다.
    '난 정말 바보인가'라는 생각을 들게 했던 문제였다. 초보 시절에는 왜이리도 오타가 많이 나던지... 요즘은 대충 키보드 두드려도 오타가 잘 안나는데 그 시절에 오타 때문에 느린 CPU에서 컴파일을 몇번을 했는지... 기억을 되살리면 소스는 다음과 같다.
            public class Member {
    private int memberNo;
    public int getMemberNo(){
    return this.memberNo;
    }
    public void setMemberNo(int menberNo){
    this.memberNo = memberNo;
    }
    ......
    }
    위 소스의 Member에는 다른 여러가지 member field가 있는데 DB의 member table에 memberid 컬럼이 memberno로 변경되면서 Member class의 memberId를 memberNo로 변경하게 되었다. 위와 같이 수정하여 배포해놓고 테스트를 하는데 시스템이 완전히 뒤죽박죽으로 돌아버리는 것이 아닌가. 이 경우도 method 이름처럼 몇시간을 헤매었다.
    이번에 argument의 오타로 인한 어처구니 없는 실수였다. setMemberNo(int menberNo)에서 문제가 발생되었던 것이다. 인수의 memberNo를 menberNo로 잘못친것이다. 그래서 memberNo에는 해당 member의 memberno가 아닌 0이 모두 들어갔어던 것이다. 시스템은 memberno를 기준으로 도는 부분이 너무나 많았기에 오류나는 부분도 많았으며 DB에서는 제대로 된 memberno을 읽어 왔으며, compile과 runtime시 아무런 반응도 없었기에, 초보자를 그렇게도 고생시켰나 보다.
    이것도 member field면 무조건 this를 붙이도록 하던지 Java가 인수는 'm_'와 prefix를 붙이도록 Coding Style을 정의- SUN사이트의 Java Coding 규약에는 "Variable names should not start width underscore_ or dollar sign $ characters, even though both are allowed." 와 같이 명시되어 있다 - 했더라면 발생하지 않았을 문제이다.
    또한 C언어나 C#에서 처럼 compile 경고레벨을 높여놓으면 "menberNo는 어디서도 사용하지 않습니다."와 같은 메세지를 보여 줬더라면 고생을 덜 하지 않았을까?

    6.2.4 "static member를 instance를 경유하여 참조해서는 안 된다." #

    예를 들어 ClassA 에 public static int AA 라는 static field가 있을 경우 ClassA.AA 로 접근해야 하는데, 다음과 같이 사용하는 실수를 범한다.(물론 오류는 없지만)
            ClassA a = new ClassA(); 
    int i = a.AA; //instance를 경유하여 접근
    int j = ClassA.AA; //올바르게 접근
    그럼 왜 굳이 ClassA.AA와 같이 instance가 아닌 class이름을 붙여야 할까?
    static member(static field/static method)는 compile시에 이미 어느것을 호출할 지 결정하기 때문에 위의 a.AA와 같은 것은 static이 아닌것 같은 오해와 혼란만 가져오기 때문이다. 심지어 개인적으로는 동일 class 내 - 위 소스에서 ClassA의 member method - 에서 ClassA.AA라고 사용하는 편이다.
    이는 local variable과 혼동될 염려도 없을뿐더러 AA라는 변수가 static이라는 것도 확실히 알 수 있기 때문이다. 물론 private static 의 경우는 ClassA.BB 와 같이 하지 않고 BB 라고 해도 무방하겠지만 말이다.

    6.2.5 "super keyword는 부모의 this" #

    Java 개발자 대부분은 'super' 에 대하여 그렇게 민감하지 않을 것이다. 그거 super() 나 super.method1() 과 같이 사용되지 그 이상에 대해선 깊이 생각하지 않게 된다. super를 한마디로 정리하면 다음과 같다.
    "super keyword는 instance method등에서 this를 사용할 수 있는 곳에서만 쓸 수 있다. this의 자리에 super라고 쓰면 현재 class의 member가 참조되는 대신 부모 class의 member가 참조되는 것이다."

    6.3 상속에 관한 또 다른 문제 #

    6.4 그밖의 함정 #

    6.4.1 "생성자에 void 를 붙인다면?" #

    생성자에 void를 붙인다면 그 class가 new 될때 그 생성자(?)가 실행될까?? 아래의 'Constuctor'라는 문자열은 출력될까?
            public class ConstructorTest{
    void ConstructorTest(){
    System.out.println("Constuctor");
    }
    .....
    }
    출력되지 않는다. 물론 compile시 아무런 경고도 없었다. 즉, void가 붙은 ConstructorTest()는 생성자가 아니라 instance method일 뿐이었고 new시에는 default constructor가 실행 되었던 것이다.

    6.4.2 "if / switch 의 함정" #

    Java 개발자라면 대부분이 초보시절에 if 조건절에 '==' 대신 '='을 써본 기억이 있을것이다. 예를 들어 "if( isListenLecture == Student.STUDENT )" 를 "if( isListenLecture = Student.STUDENT )" 로 잘못 쓴 경우이다. 여기서 Student.STUDENT는 boolean type이다. 여기서 isListenLecture는 항상 Student.STUDENT 값을 갖게 되는 버그가 생긴다. 이는 compile시에 아무런 경고도 없다. 이렇게 한번 당하고 나면 앞으로는 '=='를 정확히 쓰게 되거나 아니면 다음과 같이 쓴다.
    "if( isListenLecture )" 또는 "if( !isListenLecture )" 라고 말이다. 이것이 더욱 간결하고 의미도 분명해 지기 때문이다. 또한 다음 소스와 같은 오류도 범하는 경우가 있다. 이는 잘못된 indentation으로 빚어지는 초보의 함정이다.
    이글을 읽는 분께 한가지 당부드리고 싶은것은 여기서 초보라고 다 그런건 아니라는 것이다.
            ....
    if( a < 5 )
    b = 3;
    c = 10; //이부분은 나중에 추가된 라인이다.
    if( isStudent )
    if( isFemale )
    sayHello("Hi~~");
    else
    sayHello("Hello Professor~");
    위의 소스중 c = 10; 이 if( a < 5 )의 참일때 수행된다고 오해할 수도 있고, sayHello("Hello Professor~"); 부분이 if( isStudent )의 else 부분이라고 오해 할 수도 있다. 이것은 전적으로 indentation(들여쓰기)의 불찰로 개발자가 잘못 읽을 수 있는 부분이다. Java Coding Style에서는 if문 다음에 한줄의 코드가 있더라도 {} 를 사용하길 권고한다. 그러면 첫번째 if문과 같은 오류를 방지할 수 있고 두번째 if문에서도 보다 가독성이 생길 것이다.
    이와 유사한 것으로 switch문의 case 절에서 break를 쓰지 않아 항상 동일하게 처리되는 버그도 경험해 보았을 것이다.

    7 Java 기능 적용 몇가지 #

    7.1 대규모 개발에서 interface 분리하기 #

    7.1.1 "interface 분리의 필요성" #

    Java와 같은 객체지향언어에서는 공개해야 할 method만을 public으로 하고, 공개할 필요가 없는 것은 private으로 하여 class의 상세한 내용을 은폐할 수 있게 되어 있다. 그런데 private 부분이 은폐되어 있는것 처럼 보이는가?
    소스를 보면 훤히 들여다 보이는데?
    대규모 개발은 하부 class부터 bottom-up으로 진행하는 것이 이상적인 형태일 것이다. 그런 형태로 개발하면 임의의 시점에서 테스트를 할 수도 있다. 그러나 현실적으로 단기간에 많은 수의 개발자가 붙어서 단시간에 개발을 진행하는 경우가 많다. 또한 서로 호응하는 관계에 있는 class들은 어느쪽이 하부인지 정의하기가 난감할때가 많다. 이런경우 우리는 흔히 package단위로 나누어 개발한다. 하지만 이럴경우 어느정도 코딩이 종료될때까지 테스트하기가 상당히 힘들어 진다. Java에서는 private member와 method 구현까지 하나의 파일에 코딩하는데 개발 중간에 공개하여 다른 개발자가 이용해야 하는 class를 배포할 수 없으므로 동시 개발이 까칠해 진다.
    이 상황에서 다른 package(개발자)에 공개해야 하는 class 부분을 interface로 공개하면 많은 부분 유연하게 된다. 이 interface를 다른 개발자는 개발을 하고 테스트가 필요하다면 TestImpl class를 만들어 하면된다. RMI나 CORBA에서도 Stub은 이런식으로 IDL을 정의한다.

    7.2 Java에서의 열거형 #

    Java에서는 열거형-C의 구조체, 공용체-이 없다. 열거형이 왜 필요하냐고 반문하는 개발자도 있을 것이다.
    하지만 열거형이 없어 곤란을 경험한 개발자도 꽤 있으리라 본다. 최근언어(특히 객체지향 언어) - Java, Eiffel, Oberon등 - 에는 열거형은 포함되어 있지 않다. C#에는 있긴 하지만.
    이런 이유로 Java AWT의 Label class는 다음과 같이 구현되어 있다.(텍스트의 정렬값관련)
            public static final int LEFT = 0;
    public static final int CENTER = 1;
    public static final int RIGHT = 2;
    ...
    label.setAlignment(Label.CENTER);
    ...
    하지만 위의 소스에는 문제가 있다. setAlignment() method의 인자가 int인 것이다. 만약 위에 정의한 0, 1, 2가 아닌 다른 int 값이 들어가도 compile/runtime시 알수가 없다. 그래서 주석을 달게 되는데, 주석이라 함은 정말이지 최후의 수단이라고 봐야 한다.
    실제로 우리가 개발해 놓은 소스에도 이런부분이 있으리라 예상된다. 이 문제를 어떻게 하면 해결할 수 있을까? Java에서 열거형을 한번 만들어 보자.
            //LabelAlignment.java
    public class LabelAlignment {
    private LabelAlignment() {} //이는 생성자를 private으로 하여 다른데서는 만들지 못하도록 하기위함이다.
    public static final LabelAlignment LEFT = new LabelAlignment():
    public static final LabelAlignment CENTER = new LabelAlignment():
    public static final LabelAlignment RIGHT = new LabelAlignment():
    }
    //변형된 Label.java 의 일부..
    public synchronized void setAlignment(LabelAlignment alignment){
    if( alignment == LabelAlignment.LEFT ){
    ...//왼쪽으로 맞추기..
    }else if( ...
    ...
    }
    }
    ...
    위에서 작성한 소스는 잘 작동한다. 서로 다른 3개의 instance이므로 reference가 달라 '==' 연산도 가능하고, 훌륭하다.
    하지만 한가지 문제가 있다. LabelAlignment가 Serializable한 class에서 serialize되었다 deserialize 된다면?
    LabelAlignment alignment 는 새로운 instance가 되고 serialize전의 reference와 다른 참조 위치를 갖게 되어 '==' 연산은 버그를 발생시킨다. 그럼 이것만 해결하면 되겠는데, 어떻게 refactoring하면 될 것인가? '==' 연산 대신 equals로 변형하면 되겠는데.
            //LabelAlignment.java
    public class LabelAlignment {
    private int flag;
    private LabelAlignment(int flag){
    this.flag = flag;
    }
    public static final LabelAlignment LEFT = new LabelAlignment(0):
    public static final LabelAlignment CENTER = new LabelAlignment(1):
    public static final LabelAlignment RIGHT = new LabelAlignment(2):
    public boolean equals(Object obj){
    return ((LabelAlignment)obj).flag == this.flag;
    }
    }
    //변형된 Label.java 의 일부..
    public synchronized void setAlignment(LabelAlignment alignment){
    if( LabelAlignment.LEFT.equals(alignment) ){
    ...//왼쪽으로 맞추기..
    }else if( ...
    ...
    }
    }
    ...
    하하, Serialize까지 잘 작동한다. ^^;
    여기서 Debug를 고려한다면 0, 1, 2 대신 문자열로 "LEFT", "CENTER", "RIGHT"로 한다면 더욱 명확하지 않을까?
    (주의) 위에서처럼 LabelAlignment.LEFT 라고 쓰기 싫어서 상수 interface를 만들어 그걸 implements 하여 그냥 LEFT 라고 쓰는 것을 뿌듯해 하며 쓰는 개발자들이 있다. 물론 Swing의 소스들을 보다보면 SwingConstants라는 interface에 LEFT를 비롯하여 온갖 잡다한 상수를 집어넣어놓고 여기 저기서 implements해서 사용하고 있다. 이런 코딩 스타일은 '내 스타일이야~' 가 아니라 냄새나는 코드이다.
    LEFT라는 것이 구현한 class에 이미 있을 수 있을 수 있을뿐아니라 구현한 모든 클래스에서 LEFT를 보유하여 SwingConstants.LEFT뿐 아니라 Impl.LEFT로도 사용되게 되어 온갖 혼란을 초래하게 된다. 입력량을 줄이기 위해 interface를 implements 해서는 안되지 않을까?

    7.3 Debug write #

    C에서는 다음과 같이 pre-process로 정의하면 DEBUG라는 식별자를 #define하지 않으면 컴파일후 해당 소스의 부분이 삭제된다.
            #ifdef DEBUG
    fprintf(stderr, "error...%d\n", error);
    #endif /* DEBUG */
    그럼 Java에서는?
    Java에서는 Pre-process가 없지만 다음과 같이 작성했을때 Debug.isDebug 가 final로 선언되어 있으면 compile후 아래 3줄 모두 삭제 된다.(단 Debug.isDebug 가 false 로 초기화 되었다면 제거된다.)
            if( Debug.isDebug ){
    System.out.println("error..." + error);
    }
    Java는 compile시 byte code 생성시 final은 정적으로 판단하여 미리 정의하기 때문에 위의 3줄은 삭제될 수 있다. if문과 함께 없어지게 되므로 처리 속도에 피해를 주지 않는다. 단, 주의해야 할 점은 Debug.isDebug 값이 변경되면 이 것을 사용하고 있는 측도 모두 함께 다시 compile해야 한다. bytecode를 다시 만들어야 하기 때문이다.
    그런데, 이 소스를 Debug.write()와 같이 static 으로 하여 이 method내에서 판단하게 하면 편리할텐데. 그리고 class별로 ON/OFF 처리를 할 수 있으면 좋을텐데, 어찌 하면 가능할 것인가?
    그럼 먼저 호출한 쪽의 class이름을 찾아보자. 접근은 Exception의 printStackTrace()로 부터 시작되었다. 하지만 이 소스에는 Exception 객체를 new한 시점에 결정되어 있다. 그래서 부모인 Throwable의 생성자를 확인해 보니 fillInStackTrace() 로 되어있는데 이 method는 native method였다.
    API Reference를 보면 Thread class에서는 dumpStackTrace()라는 method가 있었다. 소스를 보니, 그것도 생성시점이었다. 아무래도 예외방면에서 찾는건 무리인듯 했다.
    그래서 class의 호출계층을 나타내는 java.lang.SecurityManager의 getClassContext() method로 접근하였다. sample 소스는 다음과 같다.
            // 1. GetCallerSecurityManager.java
    public final class GetCallerSecurityManager extends SecurityManager {
    public Class[] getStackTrace(){
    return this.getClassContext();
    }
    }
    // 2. GetCallerClass.java
    public final class GetCallerClass {
    private static GetCallerSecurityManager mgr;
    static{
    mgr = new GetCallerSecurityManager();
    System.setSecurityManager(mgr);
    }
    public static void writeCaller(String str){
    Class[] stk = mgr.getStackTrace();
    int size = stk.length;
    for(int i = 0; i < size; i++){
    System.out.println("stk[" + i + "] = " + stk[i]);
    }
    String className = stk[2].getName();
    System.out.println("className is " + className + " : " + str);
    }
    }
    // 3. GetCallerClassMain1 : 호출하는 클래스 예제 1
    public class GetCallerClassMain1 {
    public static void main(String[] args){
    GetCallerClass.writeCaller(", real is 1.");
    }
    }
    // 4. GetCallerClassMain1 : 호출하는 클래스 예제 2
    public class GetCallerClassMain2 {
    public static void main(String[] args){
    GetCallerClass.writeCaller(", real is 2.");
    }
    }
    위의 3번 주석과 4번 주석 부분을 수행하면 다음과 같은 결과가 나온다.
        className is GetCallerClassMain1 : , real is 1.
    className is GetCallerClassMain2 : , real is 2.
    정확히 호출한 클래스를 표현하고 있다. 이것을 비교해서 클래스별 ON/OFF를 구현하면 된다.

    8 Java 5.0 Tiger 에 대하여 #

    Tiger에서는 새로운 개념의 적용이 많은 부분 시도 되었다. 이중 가장 기본이 되는 몇가지를 살펴보자.

    8.1 Working with java.util.Arrays #

    Tiger에서는 무엇보다도 Collection class들에 대해 많은 부분 정비하였다. 예를 들면 for/in 구문 지원과 Generic Type member와 Arrays Utility class 등이다. 그럼 Collection에 대한 static method들을 담고 있는 Arrays 에 대해 다음 example로 한눈에 살펴보자.
    package com.jeid.tiger;
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    public class ArraysTester {
    private int[] arr;
    private String[] strs;
    public ArraysTester(int size) {
    arr = new int[size];
    strs = new String[size];
    for (int i = 0; i < size; i++) {
    if (i < 10) {
    arr[i] = 100 + i;
    } else if (i < 20) {
    arr[i] = 1000 - i;
    } else {
    arr[i] = i;
    }
    strs[i] = "str" + arr[i];
    }
    }
    public int[] getArr() {
    return this.arr;
    }
    public String[] getStrs() {
    return this.strs;
    }
    public static void main(String[] args) {
    int size = 50;
    ArraysTester tester = new ArraysTester(size);
    int[] testerArr = tester.getArr();
    int[] cloneArr = tester.getArr().clone();
    String[] testerStrs = tester.getStrs();
    String[] cloneStrs = tester.getStrs().clone();
    // clone test
    if (Arrays.equals(cloneArr, testerArr)) {
    System.out.println("clonse int array is same.");
    } else {
    System.out.println("clonse int array is NOT same.");
    }
    if (Arrays.equals(cloneStrs, testerStrs)) {
    System.out.println("clonse String array is same.");
    } else {
    System.out.println("clonse String array is NOT same.");
    }
    // 2부터 10까지 값 셋팅
    Arrays.fill(cloneArr, 2, 10, new Double(Math.PI).intValue());
    testerArr[10] = 98;
    testerStrs[10] = "corea";
    testerStrs[11] = null;
    List<String> listTest = Arrays.asList(testerStrs);
    System.out.println("listTest[10] = " + listTest.get(10));
    System.out.println("------- unsorted arr -------");
    System.out.println("Arrays.toString(int[]) = " + Arrays.toString(testerArr));
    System.out.println("Arrays.toString(String[]) = " + Arrays.toString(testerStrs));
    Arrays.sort(testerArr);
    // Arrays.sort(testerStrs); //NullPointerException in sort method..(null이 없더라도 길이에 대한 크기 체크는 못함)
    Arrays.sort(testerStrs, new Comparator<String>() {
    public int compare(String s1, String s2) {
    if (s1 == null && s2 == null) {
    return 0;
    } else if (s1 == null && s2 != null) {
    return -1;
    } else if (s1 != null && s2 == null) {
    return 1;
    } else if (s1.length() < s2.length()) {
    return -1;
    } else if (s1.length() > s2.length()) {
    return 1;
    } else if (s1.length() == s2.length()) {
    return 0;
    } else {
    return s1.compareTo(s2);
    }
    }
    });
    System.out.println("------- sorted arr -------");
    System.out.println("Arrays.toString(int[]) = " + Arrays.toString(testerArr));
    System.out.println("Arrays.toString(String[]) = " + Arrays.toString(testerStrs));
    System.out.println("------------------------------------------------");
    String[][] mstrs1 = { { "A", "B" }, { "C", "D" } };
    String[][] mstrs2 = { { "a", "b" }, { "c", "d" } };
    String[][] mstrs3 = { { "A", "B" }, { "C", "D" } };
    System.out.println("Arrays.deepToString(mstrs1) = " + Arrays.deepToString(mstrs1));
    System.out.println("Arrays.deepToString(mstrs2) = " + Arrays.deepToString(mstrs2));
    System.out.println("Arrays.deepToString(mstrs3) = " + Arrays.deepToString(mstrs3));
    if( Arrays.deepEquals(mstrs1, mstrs2)) {
    System.out.println("mstrs1 is same the mstrs2.");
    }else {
    System.out.println("mstrs1 is NOT same the mstrs2.");
    }
    if( Arrays.deepEquals(mstrs1, mstrs3)) {
    System.out.println("mstrs1 is same the mstrs3.");
    }else {
    System.out.println("mstrs1 is NOT same the mstrs3.");
    }
    System.out.println("mstrs1's hashCode = " + Arrays.deepHashCode(mstrs1));
    System.out.println("mstrs2's hashCode = " + Arrays.deepHashCode(mstrs2));
    System.out.println("mstrs3's hashCode = " + Arrays.deepHashCode(mstrs3));
    }
    }

    8.2 Using java.util.Queue interface #

    Queue를 이용하여 First In First OutOrdering한 Queue를 구현 가능하다.
    package com.jeid.tiger;
    import java.util.LinkedList;
    import java.util.PriorityQueue;
    import java.util.Queue;
    public class QueueTester {
    public static void main(String[] args) {
    System.out.println("---------- testFIFO ----------");
    testFIFO();
    System.out.println("---------- testOrdering ----------");
    testOrdering();
    }
    private static void testFIFO() {
    Queue<String> q = new LinkedList<String>();
    q.add("First");
    q.add("Second");
    q.add("Third");
    String str;
    while ((str = q.poll()) != null) {
    System.out.println(str);
    }
    }
    private static void testOrdering() {
    int size = 10;
    Queue<Integer> qi = new PriorityQueue<Integer>(size);
    Queue<String> qs = new PriorityQueue<String>(size);
    for (int i = 0; i < size; i++) {
    qi.offer(10 - i);
    qs.offer("str" + (10 - i));
    }
    for (int i = 0; i < size; i++) {
    System.out.println("qi[" + i + "] = " + qi.poll() + ", qs[" + i + "] = " + qs.poll());
    }
    }
    }

    8.3 java.lang.StringBuilder 사용하기 #

    StringBuffer가 synchronize하지 않은 method들로 구성된 듯한 StringBuilder를 사용하므로 성능 향상을 도모할수 있다. 사용법은 StringBuffer와 동일하다.
    package com.jeid.tiger;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    public class StringBuilderTester {
    public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("str1");
    list.add("str2");
    list.add("str3");
    String ret = appendItems(list);
    System.out.println("ret = " + ret);
    }
    private static String appendItems(List<String> list) {
    StringBuilder sb = new StringBuilder();
    for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
    sb.append(iter.next()).append(" ");
    }
    return sb.toString();
    }
    }

    8.4 Using Type-Safe Lists #

    Collection에 type을 명시하여 type-safe 하게 처리 가능. 아래에서 type을 명시하지 않을 경우 compile error가 남을 보여준다. tip으로 Number를 이용하여 byte, short, int, long, double, float 동시 사용하는 부분 참조.
    package com.jeid.tiger;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    public class ListTester {
    public static void main(String[] args) {
    List<String> list = new LinkedList<String>();
    list.add("str1");
    list.add("str2");
    list.add(new Integer(123)); // <-- String이 아니므로 compile error!!
    //Iterator에 String type을 명시하므로 정삭작동됨.
    for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
    String str = iter.next();
    System.out.println("srt = " + str);
    }
    //Iterator에 String type을 명시하지 않았으므로 아래 A 부분에서 compile 오류 발생!!
    for (Iterator iter = list.iterator(); iter.hasNext();) {
    String str = iter.next(); //A
    System.out.println("srt = " + str);
    }
    //byte, short, int, long, double, float 동시 사용
    List<Number> lstNum = new LinkedList<Number>();
    lstNum.add(1);
    lstNum.add(1.2);
    for (Iterator<Number> iter = lstNum.iterator(); iter.hasNext();) {
    Number num = iter.next();
    System.out.println("num = " + num);
    }
    }
    }

    8.5 Writing Generic Types #

    class 나 interface keyword에 type을 명시하여 동일 타입 명시 가능. 주의 할 점은 any type은 static 일 수 없다.(동적으로 type이 정해지므로)
    class AnyTypeList<T> {
    //class AnyTypeList<T extends Number> { // <-- 이는 Number를 상속한 type은 허용하겠다는 의미.
    private List<T> list;
    //private static List<T> list; // <-- 이는 정적이므로 compile error 발생!!!
    public AnyTypeList(){
    list = new LinkedList<T>();
    }
    public boolean isEmpty(){
    return list == null || list.size() == 0;
    }
    public void add(T t){
    list.add(t);
    }
    public T grap(){
    if (!isEmpty() ) {
    return list.get(0);
    } else {
    return null;
    }
    }
    }

    8.6 새로운 static final enum #

    예제를 통해 알아보자.
    package com.jeid.tiger;
    import com.jeid.BaseObject;
    import com.jeid.MyLevel;
    public class EnumTester extends BaseObject {
    private static long start = System.currentTimeMillis();
    public static void main(String[] args) {
    try {
    test();
    enum1();
    } catch (Exception e) {
    e.printStackTrace();
    }
    printEllapseTime();
    }
    private static void test() throws Exception {
    byte[] b = new byte[0];
    System.out.println(b.length);
    }
    private static void enum1() {
    //enum TestEnum { A, B }; //enum cannot be local!!!
    for(MyVO.TestEnum te: MyVO.TestEnum.values()){
    System.out.println("Allow TestEnum value : " + te);
    }
    System.out.println("---------------------------------------");
    MyVO vo = new MyVO();
    vo.setName("enum1");
    vo.setLevel(MyLevel.A);
    System.out.println(vo);
    System.out.println("isA = " + vo.isA() + ", isGradeA = " + vo.isLevelA()+ ", isValueOfA = " + vo.isValueOfA());
    System.out.println("getLevelInKorean = " + vo.getLevelInKorean());
    }
    private static void printEllapseTime() {
    System.out.println("==> ellapseTime is " + (System.currentTimeMillis() - start) + " ms.");
    }
    }
    package com.jeid.tiger;
    import com.jeid.BaseObject;
    import com.jeid.MyLevel;
    public class MyVO extends BaseObject {
    enum TestEnum {
    A, B
    }; // this is same public static final
    private int id;
    private String name;
    private MyLevel grade;
    // private List<T> list;
    public MyLevel getLevel() {
    return grade;
    }
    public void setLevel(MyLevel grade) {
    this.grade = grade;
    }
    public boolean isA() {
    return "A".equals(this.grade);
    }
    public boolean isValueOfA() {
    return MyLevel.valueOf("A").equals(grade);
    }
    public boolean isLevelA() {
    return MyLevel.A.equals(this.grade);
    }
    //A,B,C..대신 0,1,2... 도 동일함.
    public String getLevelInKorean() {
    switch(this.grade){
    case A:
    return "수";
    case B:
    return "우";
    case C:
    return "미";
    case D:
    return "양";
    case E:
    return "가";
    default:
    return "없음";
    }
    }
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }

    8.7 Using java.util.EnumMap #

    java.util.Map과 동일하나 key가 enum type이어 한다. 예제로 살펴보자.
    package com.jeid.tiger;
    import java.util.EnumMap;
    public class EnumMapTester {
    private enum MyEnum {
    A, B, C
    }; // this is same the static final..
    public static void main(String[] args) {
    MyEnum[] enums = MyEnum.values();
    System.out.println("MyEnum is " + enums[0] + ", " + enums[1] + ", " + enums[2]);
    EnumMap<MyEnum, String> em = new EnumMap<MyEnum, String>(MyEnum.class);
    em.put(MyEnum.A, "수");
    em.put(MyEnum.B, "우");
    em.put(MyEnum.C, "미");
    em.put(MyEnum.B, "가"); //key 중복은 HashMap과 동일하게 overwrite임.
    for (MyEnum myEnum : MyEnum.values()) {
    System.out.println(myEnum + " => " + em.get(myEnum));
    }
    }
    }

    8.8 Using java.util.EnumSet #

    java.util.Set과 동일하나 value가 enum type이어 한다. 예제로 살펴보자.
    package com.jeid.tiger;
    import java.util.EnumSet;
    public class EnumSetTester {
    private enum MyEnum {
    A, B, C, a, b, c
    }; // this is same the static final..
    public static void main(String[] args) {
    MyEnum[] enums = MyEnum.values();
    System.out.println("MyEnum is " + enums[0] + ", " + enums[1] + ", " + enums[2]);
    EnumSet<MyEnum> es1 = EnumSet.of(MyEnum.A, MyEnum.B, MyEnum.C);
    EnumSet<MyEnum> es2 = EnumSet.of(MyEnum.a, MyEnum.b, MyEnum.c);
    EnumSet<MyEnum> es3 = EnumSet.range(MyEnum.a, MyEnum.c);
    if (es2.equals(es3)) {
    System.out.println("e2 is same e3.");
    }
    for (MyEnum myEnum : MyEnum.values()) {
    System.out.println(myEnum + " contains => " + es1.contains(myEnum));
    }
    }
    }

    8.9 Convert Primitives to Wrapper Types #

    int, short, char, long, double등 primitive와 이들의 Object Wrapper 인 Integer, Shrt, Char등 간의 converting에 있어 자동으로 처리해주는 boxing과 unboxing이 지원 됨에 따라 type에 대한 유연한 처리가 가능해졌다. 예제로 살펴보자.
    package com.jeid.tiger;
    public class AutoBoxingTester {
    public static void main(String[] args) {
    int i = 0;
    Integer ii = i; // boxing. JDK 1.4에서는 incompatible type error가 발생 했었으나 Tiger에서는 괜찮다.
    int j = ii; // unboxing
    for (ii = 0; ii < 5; ii++) { // Integer인데도 ++ 연산자 지원.
    }
    i = 129;
    ii = 129;
    if (ii == i) {
    System.out.println("i is same ii.");
    }
    // -128 ~ 127 사이의 수는 unboxing이 되어 == 연산이 허용되지만,
    // 그 범위 외의 경우 Integer로 boxing된 상태므로 equals를 이용해야함.
    // 이는 버그가 발생했을 경우 찾기 쉽지 않은 단점도 내포하고 있다.!!
    checkIntegerSame(127, 127); // same
    checkIntegerSame(128, 128); // Not same
    checkIntegerEquals(128, 128); // equals
    checkIntegerSame(-128, -128); // same
    checkIntegerSame(-129, -129); // Not same
    checkIntegerEquals(-129, -129); // equals
    System.out.println("--------------------------------------------");
    Boolean arriving = false;
    Boolean late = true;
    String ret = arriving ? (late ? "도착했지만 늦었네요." : "제시간에 잘 도착했군요.") :
    (late ? "도착도 못하고 늦었군요." : "도착은 못했지만 늦진 않았군요.");
    System.out.println(ret);
    StringBuilder sb = new StringBuilder();
    sb.append("appended String");
    String str = "just String";
    boolean mutable = true;
    CharSequence chSeq = mutable ? sb : str;
    System.out.println(chSeq);
    }
    private static void checkIntegerSame(Integer ii, Integer jj) {
    if (ii == jj) {
    System.out.println("ii = " + ii + ", jj = " + jj + " ==> jj is same ii.");
    } else {
    System.out.println("ii = " + ii + ", jj = " + jj + " ==> jj is NOT same ii!!");
    }
    }
    private static void checkIntegerEquals(Integer ii, Integer jj) {
    if (ii.equals(jj)) {
    System.out.println("ii = " + ii + ", jj = " + jj + " ==> jj is equals ii.");
    } else {
    System.out.println("ii = " + ii + ", jj = " + jj + " ==> jj is NOT equals ii!!");
    }
    }
    }

    8.10 Method Overload resolution in AutoBoxing #

    int가 127을 초과할 경우 boxing이 이루어 질듯 하지만, method overload에 있어서는 boxing이 이루어 지지 않아 JDK1.4와 동일한 결과를 얻는다. 예제로 살펴보자.
    package com.jeid.tiger;
    public class OverloadTester {
    public static void main(String[] args) {
    double d = 10;
    Integer ii = new Integer(10);
    doSomething(10);
    doSomething(1000);
    doSomething(ii);
    doSomething(d);
    }
    private static void doSomething(Integer ii) {
    System.out.println("This is doSomething(Integer)");
    }
    private static void doSomething(double d) {
    System.out.println("This is doSomething(double)");
    }
    }

    8.11 가변적인 argument 개수 ... #

    인수가 가변적일 경우 인수의 개수가 없는것 부터 다수개까지 모두 지원. 예제로 살펴보자.
    package com.jeid.tiger;
    public class VarArgsTester {
    public static void main(String[] args) {
    setNumbers(1, 2);
    setNumbers(1, 2, 3, 4);
    setNumbers(1);
    // setNumbers(); //해당 되는 method가 없어 compile error!!
    System.out.println("==============================================");
    setNumbers2(1, 2, 3, 4);
    setNumbers2(1);
    setNumbers2();
    }
    // this is same setNumbers(int first, int[] others)
    private static void setNumbers(int first, int... others) {
    System.out.println("-----------setNumbers()----------- : " + first);
    for (int i : others) {
    System.out.println("i = " + i);
    }
    }
    // this is same setNumbers(int[] others)
    private static void setNumbers2(int... others) {
    System.out.println("-----------setNumbers2()----------- : "
    + (others != null && others.length > 0 ? others[0] : "null"));
    for (int i : others) {
    System.out.println("i = " + i);
    }
    }
    }

    8.12 The Three Standard Annotation #

    @Override - sign the override from superclass.
        //정상적인 사용
    @Override
    public int hashCode(){
    return toString().hashCode();
    }
    //스펠링이 틀려 compile error!!
    @Override
    public int hasCode(){ //misspelled => method does not override a method from its superclass error!!
    return toString().hashCode();
    }
    @Deprecated deprecated 주석과 동일하나 부모의 method가 deprecated되면 자식의 method를 사용해도 deprecated로 나온다.
    package com.jeid.tiger;
    public class AnnotationDeprecateTester {
    public static void main(String[] args){
    DeprecatedClass dep = new DeprecatedTester();
    dep.doSomething(10); //deprecated
    }
    }
    class DeprecatedClass {
    @Deprecated
    public void doSomething(int ii){ //deprecated
    System.out.println("This is DeprecatedClass's doSomething(int)");
    }
    public void doSomethingElse(int ii){
    System.out.println("This is DeprecatedClass's doSomethingElse(int)");
    }
    }
    class DeprecatedTester extends DeprecatedClass {
    @Override
    public void doSomething(int ii){
    System.out.println("This is DeprecatedTester's doSomething(int)");
    }
    }
    @SuppressWarnings SuppressWarnings에 인자는 String[] type으로 여러개를 배열형태로 쓸수 있다.
    package com.jeid.tiger;
    import java.util.ArrayList;
    import java.util.List;
    public class AnnotationSuppressWarningsTester {
    @SuppressWarnings({"unchecked", "fallthrough"} )
    private static void test1(){
    List list = new ArrayList();
    list.add("aaaaaa");
    }
    @SuppressWarnings("unchecked")
    private static void test2(){
    List list = new ArrayList();
    list.add("aaaaaa");
    }
    //warning이 없는 소스.
    private static void test3(){
    List<String> list = new ArrayList<String>();
    list.add("aaaaaa");
    }
    }

    8.13 Creating Custom Annotation Types #

    나만의 annotation을 정의할 수 있는데 키워드는 @interface이 각 method정의가 member라고 보면 된다. 간단한 예를 보면 다음과 같다.
    package com.jeid.tiger;
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    @Documented
    @Target( { ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation {
    String columnName();
    String methodName() default "";
    }
    //사용하는 쪽..
    public class AnnotationTester {
    @MyAnnotation(columnName = "test", methodName = "setTest")
    private String test;
    @MyAnnotation(columnName = "grpid")
    public String grpid;
    ....
    }
    //위의 test 멤버의 경우 다음과 같이 접근 가능하다.
    Field testField = cls.getDeclaredField("test");
    if (testField.isAnnotationPresent(MyAnnotation.class)) {
    Annotatioin anno = testField.getAnnotation(MyAnnotation.class);
    System.out.println(anno.columnName() + ", method = " + anno.methodName());
    }

    9 The for/in Statement #

    9.1 for/in 의 자주 사용되는 형태 #

    for/in은 무엇보다 다양한 유형의 예제를 보는것이 제일 빠를것이다. 형태별 사용 예제를 살펴보면 다음과 같다.
    //1. 가장 단순한 형태인 배열(array)
    String[] strs = { "aaa", "bbb", "ccc" };
    for (String str : strs) {
    System.out.println(str);
    }
    //2. List by using Iterator
    List<Number> lstNum = new LinkedList<Number>();
    lstNum.add(1);
    lstNum.add(1.2);
    for (Iterator<Number> iter = lstNum.iterator(); iter.hasNext();) {
    Number num = iter.next();
    System.out.println("num = " + num);
    }
    //3. List를 바로 사용
    List<String> lst = new LinkedList<String>();
    lst.add("aaaaa");
    lst.add("bbbbb");
    lst.add("ccccc");
    lst.add("ddddd");
    for (String str : lst) {
    System.out.println("str = " + str);
    }
    // 4. List of List
    List[] lists = { lst, lst };
    for (List<String> l : lists) {
    for (String str : l) {
    System.out.println("str = " + str);
    }
    }

    10 Static Import #

    10.1 static member/method import #

    Tiger에서는 다른 클래스의 member와 method를 import 할수 있다. 단, static 일 경우만 가능하다.
    //예를 들어 System.out.println() 이라는 것을 사용하기 위해서는 다음의 import 문이 필요하다.
    import java.lang.System; //물론 java.lang 이기에 import 문이 필요없지만 예를 들자면 그렇다는 것이다.&^^
    //허나, Tiger에서는 다음과 같이 사용할수 있다.
    import static java.lang.System.out;
    ...
    out.println(...);
    // method를 import 한다면..
    import static java.lang.System.out.println;
    ...
    println(...);

    11 References #

    posted by 좋은느낌/원철
    2008. 6. 24. 09:42 개발/Java

    이클립스 설치후 깔아야할 플러그인들 ..

    ( 현재 Eclipse 3.2.x 기준 )

    1. 기본적으로 WTP 플러그인을 설치한다.
        (Update 실행하면 됨 ㅋㅋ)

    2. AnyEdit 말이 필요 없다. 필수!
    - Ctrl + Alt + R 누르면 해당 링크로 바로 이동 ㅡ_ㅡ; 소스레벨의 F3키와는 다른 편리함 이밖에도 다른 기능들이 조낸 많음
    - 사이트 :  http://andrei.gmxhome.de/anyedit/index.html
    - 업데이트 : http://andrei.gmxhome.de/eclipse/

    3. properEdit
    - 각종 property 파일 수정할때 native2ascii 할 필요가 없게 해주는 유용함. ㅋ 일본어, 한글, utf-8 다 지원한다.

    4. Extended VS Presentation
    - 이클립스 스타일을 변경해줌과 동시에 인터페이스가 바뀐다 ㅡㅡ; 지금 랭킹 1위야 ㅡㅡ; 그밖에 여러가지
    - 사이트: http://andrei.gmxhome.de/skins/index.html
    - 업데이트 : http://andrei.gmxhome.de/eclipse/

    5. QuickREx - regular expressions
    - 웹개발을 하다보면 말이지 레귤러 익스프레션을 사용할 일이 생긴다고 ㅡㅡ; 요거 그거야 ㅋ
    - 사이트 : http://www.bastian-bergerhoff.com/eclipse/features/web/QuickREx/toc.html 
    - 업데이트 : http://www.bastian-bergerhoff.com/eclipse/features

    6. Log4E
    -  말안해도 알겠쥐?
    - 사이트 : http://log4e.jayefem.de
    - 업데이트 : http://log4e.jayefem.de/update

    7. Oxygen XML Editor and XSLT Editor/Debugger
    - XML 써바야지 ㅡㅡ;
    - 사이트 : http://www.oxygenxml.com
    - 업데이트 : http://www.oxygenxml.com/InstData/Eclipse

    8. JadClipse
    -  이건 역컴파일러라는거지 ㅎㅎ 넘 괜찮은넘 ㅡㅡ;
    - 사이트 : http://jadclipse.sourceforge.net/
    - 업데이트 :

    9. PMD For Eclipse
    -
    - 사이트 : http://pmd.sourceforge.net/
    - 업데이트 : http://pmd.sourceforge.net/eclipse/

    10. Code Analysis Plugin - CAP
    -  요건 페키지, 파일 들이 어떤 구조로 되어 있는지 한눈에 알 수 있게 해준다. 스크린샷 참고
    - 사이트 : http://cap.xore.de
    - 업데이트 : http://cap.xore.de/update/

    11. Checkstyle Plug-in
    - 알려진 소스에 대한 스타일 체크
    - 사이트 : http://eclipse-cs.sourceforge.net/
    - 업데이트 : http://eclipse-cs.sourceforge.net/update

    12. QuantumDB Eclipse Plugin
    - SQL
    - 사이트 : http://quantum.sourceforge.net/
    - 업데이트 :
    파일다운로드




    13. Maven Integration for Eclipse
    - 마빈 플러그인 이클립스에서 마빈을 사용하여 빌드를 할 수 있게 해준다 .. ㅋㅋ 필수조 ㅎㅎ
    - 사이트 : http://m2eclipse.codehaus.org/
    - 업데이트 : http://m2eclipse.codehaus.org/update/

    14. Lib Copy
    - 마빈 플러그인 이클립스에서 마빈을 사용하여 빌드를 할 경우 WTP와 통합이 되도록 해준다 ㅋㅋ 자세한 사항은 아래 사이트 참조 ( 이건 WTP를 사용 하지 않을꺼라면(대신 sysdo tomcat plugin 사용) 안해도 된다)
    - 사이트 : http://adam.kruszewski.name/projects/libcopy
    - 업데이트 : http://adam.kruszewski.name/eclipse

    15. Sysdeo Eclipse Tomcat Launcher plugin
    -  톰켓 플러그인
    - 사이트 : http://www.sysdeo.com/eclipse/tomcatplugin
    - 업데이트 :  톰켓 6.0 까지 지원 아직 배타이지만 정식 나오겠지 (압축풀어 설치)
    파일 다운 로드



    16. SubVersion 버전 관리 툴
    - 버전 관리 막강한 client 툴 이거 없으면 못해 CVS도 있지만 서브 버전의 막강한 기능을 구현
    - 사이트 : http://www.polarion.org/p_subversive_features.php
    - 업데이트 : http://www.polarion.org/download/p_subversive/update-site/



    ■ 이클립스 플러그인 관련 사이트

    http://www.eclipse-plugins.info/ 간단한 플러그인 정보와 인기도(?) 확인 가능
    http://www.sourceforge.net/ 각종 이클립스 플러그인 프로젝트들이 등록되어있음
    http://www.eclipseplugincentral.com/ 플러그인 쇼핑몰, 포럼


    ■ DB 플러그인

    1) Quantum DB (http://sourceforge.net/projects/quantum/)

    왼쪽 북마크에 접속하고자 하는 DB 추가하고 환경잡기(ID, 비번, 접속드라이버 등)
    원하는 북마크를 오른쪽버튼 클릭해서 DB에 connect한 후 오른쪽 쿼리 에디터에서 쿼리.

    [참고]
    - 오라클 JDBC드라이버 : C:oracleora81jdbclibclases12.zip 찾아서 추가 (oracle.jdbc.driver.OracleDriver)
    - connection URL : jdbc:oracle:thin:@000.00.00.000:1521:ORACLE8

    2) dbedit (http://sourceforge.net/projects/dbedit/)

    3) jfacedbc #상용# (http://sourceforge.net/projects/jfacedbc/)

    소스포지에 있는 버전은 2.X 버전이고 3.0부터는 상용으로 http://www.jfacedbc.com/ 에서 다운/구매 가능 (기능은 확실히 좋을 듯...)



    ■ XML 플러그인

    1) XMLBuddy http://www.xmlbuddy.com/
    XMLBuddy pro는 #상용#입니다.

    2) oxygen #상용#
    url update : http://www.oxygenxml.com/InstData/Eclipse/site.xml

    3) MyEclipse Enterprise Workbench #상용# (http://www.myeclipseide.com/)
    MyEclipse 설치하면 깔리는 XML 에디터.

    4) 그 외 JXMLEditor, MetaCoder , Sunbow , X-Men, XML Schema Quality Checker



    ■ J2EE 개발 플랫폼

    1) Lomboz (http://forge.objectweb.org/projects/lomboz)
    롬보즈를 쓰기 위해서는 EMF(http://www.eclipse.org/emf)도 깔려있어야 함

    2) MyEclipse Enterprise Workbench #상용# (http://www.myeclipseide.com/)



    ■ JSP 에디터 플러그인

    1) SolarEclipse (http://sourceforge.net/projects/solareclipse/)
    jsp 하이라이팅 기능만 있음

    2) Lomboz jsp editor (http://forge.objectweb.org/projects/lomboz)
    롬보즈 설치하면 깔리는 jsp 에디터. 코드 어시스턴스 기능 있음.

    3) MyEclipse Enterprise Workbench #상용# (http://www.myeclipseide.com/)
    MyEclipse 설치하면 깔리는 jsp 에디터. 롬보즈가 저장 시 에러 체크를 하는 반면, 실시간으로 에러 체크를 한다고 함.



    ■ 각종 플러그인

    1) Yoxos ( http://www.yoxos.com/ )

    유용한 플러그인들을 묶어 프로그램 인스톨하는 형식으로 배포.
    종류별로 잘 분류되어 있고 설치시 필요한 플러그인만 선택하여 설치 가능.

    2) subversion (svn) 플러그인
    url update : http://subclipse.tigris.org/update

    3) SWT/Swing 디자이너 #상용# http://www.swt-designer.com/




    ■ 플러그인 설치

    1) 설치유형 1 : 복사
    받은 플러그인 파일을 C:eclipseplugins 에 복사하고 재시작

    2) 설치유형 2 : url update
    Help > Software Updates > Find and Install 메뉴 선택
    "search for new features to install" 선택후 next 버튼
    new remote site 버튼을 클릭하여 플러그인명과 url update 주소를 입력하면 다운 받을 수 있다.

    3) 플러그인 설치 문제 해결

    복사해서 플러그인을 설치 할 때 가끔 반영이 안되는 문제가 있다.
    똑같이 설치를 해도 잘 되는 컴이 있는가 하면 그렇지 않은 것도 있으니... -_-a
    처음 실행 이전에 플러그인을 모두 복사해야 정상작동할 듯 싶다. 일단 실행 이후에 플러그인을 추가 설치하면 간혹 말썽이다.

    첫째, Help > Software Updates > Manage Configuration 에서 설치되지않은 것들이 있으면 enable 시켜준다.
    이렇게 해서 해결 된다면 제일 편하게 해결된 것.

    둘째, eclipse 폴더 아래 configuration 폴더를 지우고 재시작.

    셋째, 이래도 안 깔리면.... 이클립스를 아예 새로 풀고 플러그인들 먼저 다 복사해 둔 후 최초실행 시킨다.



    자료출처 : http://www.cyworld.com/kangs007
    posted by 좋은느낌/원철
    2008. 6. 17. 14:23 개발/Java
    출처 : http://www.ibm.com/developerworks/kr/forums/dw_thread.jsp?forum=26&thread=2517&cat=4

    commons-configuration 를 이용한 프로그램 설정 다루기
     

    대부분의 프로그램들에서 설정이라는 것이 필요하다.
    간단히 웹서버의 예를 들면...
    - 어떤 포트를 사용할 것인지
    - 홈 디렉토리 지정
    - DB 연동시 JDBC 드라이버 지정 및 URL 과 계정 정보
    이런 것들이 필요할텐데 간단히 프포퍼티 파일을 만들어서 JDK에서 기본으로 제공되는
    프포퍼티 클래스를 이용할 수도 있다. 그러나 JDK에서 기본으로 제공되는 클래스는
    기능이 단순하고 제한적이다. 예를 들어 스트링 타입으로만 처리되기 때문에 다른 타입의
    값을 원할때는 개발자가 모두 처리를 해주어야 한다. 또한 한글 처리도 매끄럽지 못하다.
    이런 이유들로 인해 간단한 설정 처리 프로그램을 만드는데에도 에러가 많아지고 그에 따는
    시간과 노력이 들어가게 된다. 그러나 걱정할 필요가 없다. commons-configuration 를
    이용하면 이런 대부분의 노력이 필요 없게 된다.
    애래에서처럼 프로퍼티 파일을 만들고 자바 프로그램을 실행시켜보면
    commons-configuration 의 일부 기능이지만 얼마나 좋은 것인지 알게 될 것이다.

    * commons-configuration 은 다른 라이브러리들에 의존성이 있다.
    commons-logging, commons-lang, commons-collections 라이브러리들도 포함시킨다.

    * test.prop 파일의 내용
    project.home = D:/dev/commons-configuration
    port = 8080
    debug = false
    temp.home = D:/새 폴더

    jdbc.driver = com.mysql.jdbc.Driver
    jdbc.driver = jdbc.odbc.JdbcOdbcDriver
    jdbc.driver = oracle.jdbc.driver.OracleDriver
    jdbc.driver = com.sybase.jdbc.SybDriver

    mysql.host = localhost
    mysql.db = test
    mysql.user =


    * 프로그램 소스
    import org.apache.commons.configuration.Configuration;
    import org.apache.commons.configuration.PropertiesConfiguration;

    public class PropertyTest {
    Configuration config;

    public void load() {
    try {
    // 프로퍼티 파일 로딩
    this.config = new PropertiesConfiguration("test.prop");
    }
    catch (org.apache.commons.configuration.ConfigurationException e) {
    System.err.println(e.getMessage());
    }
    }

    public void test() {
    try {
    String projectHome = config.getString("project.home");
    System.out.println("project.home = [" + projectHome + "]");

    // int primitive type, int 타입으로 즉시 사용 가능
    int port = config.getInt("port");
    System.out.println("port = [" + port + "]");

    // boolean primitive type, boolean 타입으로 즉시 사용 가능
    boolean debug = config.getBoolean("debug");
    System.out.println("debug = [" + debug + "]");

    // 한글도 이상 없다
    String tempHome = config.getString("temp.home");
    System.out.println("temp.home = [" + tempHome + "]");

    // String array type, 키와 값이 쌍으로 배열처럼 처리
    String[] jdbcDrivers = config.getStringArray("jdbc.driver");
    for (int i = 0; i < jdbcDrivers.length; i++) {
    System.out.println("[" + jdbcDrivers + "]");
    }

    // 값이 지정되어 있지 않는 경우, 예외를 발생하지 않는다
    String mysqlUser = config.getString("mysql.user");
    System.out.println("mysql.user = [" + mysqlUser + "]");

    // 키가 존재하지 않는 경우, 키가 존재하지 않는 경우에 값이 null
    String mysqlPassword = config.getString("mysql.password");
    System.out.println("mysql.password = [" + mysqlPassword + "]");

    // 키가 존재하지 않더라도 기본값을 지정되는 경우
    String defaultPassword = config.getString("mysql.password", "admin");
    System.out.println("mysql.password = [" + defaultPassword + "]");

    }
    catch (org.apache.commons.configuration.ConversionException e) {
    System.err.println(e.getMessage());
    }
    }

    public static void main(String[] args) {
    PropertyTest prop = new PropertyTest();
    prop.load();
    prop.test();
    }

    }

    * 실행 결과
    project.home = [D:/dev/commons-configuration]
    port = [8080]
    debug = [false]
    temp.home = [D:/새 폴더]
    [com.mysql.jdbc.Driver]
    [jdbc.odbc.JdbcOdbcDriver]
    [oracle.jdbc.driver.OracleDriver]
    [com.sybase.jdbc.SybDriver]
    mysql.user = []
    mysql.password = [null]
    mysql.password = [admin]

    posted by 좋은느낌/원철
    2008. 6. 17. 10:18 개발/Java
    [펌]log4j 설정법
    [출처]http://jami.tistory.com/entry/%ED%8E%8Clog4j-%EC%84%A4%EC%A0%95%EB%B2%95
    참고파일



    =============================================

    본문서는 자유롭게 배포/복사 할수 있지만

    이문서의 저자에 대한 언급을 삭제하시면 안됩니다

    저자 : GoodBug (unicorn@jakartaproject.com)

    최초 : http://www.jakartaproject.com 

    =============================================


    LOG4J

    I. 들어가면서.. 그리고 log4j


    log4j는 자바 어플리케이션에서 빠르고 효과적으로 로깅 할 수 있도록 도와주는 오픈 소스 프로젝트입니다.


    로깅(logging)은 코드의 가독성을 떨어뜨리는 단점이 있지만 애플리케이션에 문제가 있을 때 개발자가 자세한 상황을 파악할 수 있도록 해 주며 테스팅시 빠질 수 없는 요소입니다.


    아마도 여러분들은 여러 어플리케이션이 추가되면서 각 개발자들만의 독특한 로깅방식이 서로 썩이고 얽혀서 화면에 나타나는것을 많이 봤을겁니다 -_-;
    즉 로깅방법을 통일할 필요가 있는것이죠. 모든 개발자가 특정 포맷에 맞추어서 로깅 한다면 한결 로깅하기도 편하겠지요


    오픈 소스 프로젝트인 Log4j는 개발자들이 매우 손쉽고 다양한 형태로 로깅을 할 수 있도록 도와줍니다. 성능또한 우수해 더이상 System.out.println을 사용할 필요가 없습니다.



    II. 다운로드


    다운로드 http://logging.apache.org/log4j/docs/download.html

    매뉴얼 http://logging.apache.org/log4j/docs/documentation.html

    API spec http://logging.apache.org/log4j/docs/api/index.html



    III. LOG4J 구조


    일단 log4j를 잘 모르지만 그 구조만 살짝 살펴보고 넘어갑시다

    log4j는 크게 3가지 요소로 구성되며 그 구조는 다음과 같습니다

    ① Logger(Category) : 로깅 메세지를 Appender에 전달합니다.

    ② Appender : 전달된 로깅 메세지를 파일에다 기록할 것인지, 콘솔에 출력할 것인지

                       아니면 DB에 저장할 것인지 매개체 역활을 합니다.

    ③ Layout : Appender가 어디에 출력할 것인지 결정했다면 어떤 형식으로 출력할 것이지

                    출력 layout을 결졍합니다.

    쉽죠?



    IV. LOG4J 로깅 레벨


    log4j는 다양한 로깅레벨을 지원합니다.


    ① FATAL : 가장 크리티컬한 에러가 일어 났을 때 사용합니다.

    ② ERROR : 일반 에러가 일어 났을 때 사용합니다.

    ③ WARN : 에러는 아니지만 주의할 필요가 있을 때 사용합니다.

    ④ INFO : 일반 정보를 나타낼 때 사용합니다.

    ⑤ DEBUG : 일반 정보를 상세히 나타낼 때 사용합니다.


    만약 로깅 레벨을 WARN 으로 설정하였다면 그 이상 레벨만 로깅하게 됩니다.

    즉 WARN, ERROR, FATAL 의 로깅이 됩니다.



    V. 샘플코드 1


    jsp에서 사용하는 예제가 없어 만들어 봤습니다.


    test.jsp


    <%@ page contentType="text/html;charset=MS949"
     import="org.apache.log4j.Logger" %>

    <%!
     static Logger logger = Logger.getLogger("test.jsp");
    %>

    <%
    logger.fatal("fatal!!");

    logger.fatal("fatal2!!", new NullPointerException("널입니다요"));

    logger.error("error!", new NumberFormatException());

    logger.error("error!2");

    logger.warn("warn");

    logger.info("info");

    logger.debug("debug");
    %>


    결과 콘솔화면








    static Logger logger = Logger.getLogger("test.jsp");

    static 메소드 getLogger를 통해 logger 인스턴스를 가져옵니다.
    getLogger에는 파라미터로 스트링 혹은 클래스를 사용하는데 jsp에서는 클래스를 파라미터로 주기에는 좀 애매합니다. 그냥 스트링으로 주도록 하지요


    logger.fatal("fatal!!");
    logger.fatal("fatal2!!", new NullPointerException("널입니다요"));
      
    logger에 fatal 레벨의 메세지를 전달합니다. 다음 두가지 메소드를 지원하는군요

    fatal(Object message)

    fatal(Object message, Throwable t)

    각 레벨마다 위처럼 두가지 메소드를 지원합니다.


    지원 메쏘드
    logger.fatal(Object message) logger.fatal(Object message, Throwable t)
    logger.error(Object message) logger.error(Object message, Throwable t)
    logger.warn(Object message) logger.warn(Object message, Throwable t)
    logger.info(Object message) logger.info(Object message, Throwable t)
    logger.debug(Object message) logger.debug(Object message, Throwable t)


    VI. 샘플코드 2


    서블릿의 경우 다음과 같이 코딩하면 되겠군요

    TestServlet.java


    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class TestServlet extends HttpServlet {


        static Logger logger = Logger.getLogger(TestServlet.class);


        public void init(ServletConfig config) throws ServletException {
             super.init(config);
        }


        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

             try {
                  ...
       
                  logger.info("Hellow World~");

                  ...

              } catch (Exception e) {
                  logger.error("Error at TestServlet", e);
              }
         }
    }



    VII. LOG4J 설정


    log4j 설정은 프로그램 내에서 할 수 있지만 설정파일을 사용함으로서 좀더 유연하게 log4j환경을 만들 수 있습니다.


    프로그램에서 설정

    <%@ page contentType="text/html;charset=MS949"
     import="org.apache.log4j.*,java.io.* "
    %>

    <%!
     static Logger logger = Logger.getLogger("log4j.jsp");
    %>

    <%
    String layout = "%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n";
    String logfilename = "DailyLog.log";
    String datePattern = ".yyyy-MM-dd ";

    PatternLayout patternlayout = new PatternLayout(layout);
    DailyRollingFileAppender appender = new DailyRollingFileAppender(patternlayout, logfilename, datePattern);
    logger.addAppender(appender);
    logger.setLevel(Level.INFO);
    logger.fatal("fatal!!");
    %>


    property 파일에 설정
    log4j.properties를 만들어 /WEB-INF/classes 밑에 놓으세요



    log4j.rootLogger=INFO, stdout, rolling

    log4j.appender.stdout=org.apache.log4j.ConsoleAppender

    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

    log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n

    log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender

    log4j.appender.rolling.File=output.log

    log4j.appender.rolling.Append=true

    log4j.appender.rolling.MaxFileSize=500KB

    log4j.appender.rolling.DatePattern='.'yyyy-MM-dd

    log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

    log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n


    #최상위 카테고리에 INFO로 레벨 설정 및 appender로 stdout, rolling을 정의

    log4j.rootLogger=INFO, stdout, rolling

    #stdout 어펜더는 콘솔에 뿌리겠다는 정의

    log4j.appender.stdout=org.apache.log4j.ConsoleAppender

    #stdout 어펜더는 patternlayout을 사용하겠다는 정의

    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

    #페턴은 다음과 같이 포맷팅 하겠다는 것을 정의

    log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n


    #역시나 rolling 어펜더는 파일로 처리한다라고 정의

    log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender

    #로그 파일 이름은 output.log

    log4j.appender.rolling.File=output.log

    #true면 톰캣을 내렸다 올려도 파일이 리셋되지 않습니다.

    log4j.appender.rolling.Append=true

    #파일 최대 사이즈는 500KB로 설정

    log4j.appender.rolling.MaxFileSize=500KB

    #파일 포맷은 output.log.2005-03-10 으로 관리하겠다고 정의

    log4j.appender.rolling.DatePattern='.'yyyy-MM-dd

    #역시나 rolling 어펜더는 패턴 레이아웃을 사용하겠다고 정의

    log4j.appender.rolling.layout=org.apache.log4j.PatternLayout

    #rolling 어펜더는 패턴 레이아웃 포맷

    log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%t] %-17c{2} (%13F:%L) %3x - %m%n



    VIII. 설정 포맷


    로그파일명 포맷 (DatePattern)
    로그파일명 포맷입니다. 날짜, 시간 및 분단위로까지 로그 파일을 분리할 수 있습니다.

    형식 설명
    '.'yyyy-MM 매달 첫번째날에 로그파일을 변경합니다
    '.'yyyy-ww 매주의 시작시 로그파일을 변경합니다.
    '.'yyyy-MM-dd 매일 자정에 로그파일을 변경합니다.
    '.'yyyy-MM-dd-a 자정과 정오에 로그파일을 변경합니다.
    '.'yyyy-MM-dd-HH 매 시간의 시작마다 로그파일을 변경합니다.
    '.'yyyy-MM-dd-HH-mm 매분마다 로그파일을 변경합니다.



    PatternLayout 포맷
    로그자체를 어떤 포맷으로 남길지 결정합니다.
    layout에는 HTMLLayout, PatternLayout, SimpleLayout, XMLLayout등이 있으며 PatternLayout이 일반적으로 가장 많이 쓰입니다.


    형식 설명
    %p debug, info, warn, error, fatal 등의 priority 가 출력된다.
    %m 로그내용이 출력됩니다
    %d 로깅 이벤트가 발생한 시간을 기록합니다.
    포맷은 %d{HH:mm:ss, SSS}, %d{yyyy MMM dd HH:mm:ss, SSS}같은 형태로 사용하며 SimpleDateFormat에 따른 포맷팅을 하면 된다
    %t 로그이벤트가 발생된 쓰레드의 이름을 출력합니다.
    %% % 표시를 출력하기 위해 사용한다.
    %n 플랫폼 종속적인 개행문자가 출력된다. \r\n 또는 \n 일것이다.
    %c 카테고리를 표시합니다
    예) 카테고리가 a.b.c 처럼 되어있다면 %c{2}는 b.c가 출력됩니다.
    %C 클래스명을 포시합니다.
    예) 클래스구조가 org.apache.xyz.SomeClass 처럼 되어있다면 %C{2}는 xyz.SomeClass 가 출력됩니다
    %F 로깅이 발생한 프로그램 파일명을 나타냅니다.
    %l 로깅이 발생한 caller의 정보를 나타냅니다
    %L 로깅이 발생한 caller의 라인수를 나타냅니다
    %M 로깅이 발생한 method 이름을 나타냅니다.
    %r 어플리케이션 시작 이후 부터 로깅이 발생한 시점의 시간(milliseconds)
    %x 로깅이 발생한 thread와 관련된 NDC(nested diagnostic context)를 출력합니다.
    %X 로깅이 발생한 thread와 관련된 MDC(mapped diagnostic context)를 출력합니다.

    예시) (같은 색끼리 보시면 됩니다)

    위의 test.jsp를 다음 포맷으로 출력해본다면

    [%c] [%C] [%d] [%F] [%l] [%L] [%m] [%M] [%n] [%p] [%r] [%t] [%x] [%X]는 다음과 같다

    [test.jsp] [org.apache.jsp.test_jsp] [2005-03-10 12:37:23,561] [test_jsp.java] [org.apache.jsp.test_jsp._jspService(test_jsp.java:64)] [64] [fatal!!] [_jspService] [개행] [FATAL] [765567] [http-8080-Processor25] [] []

    posted by 좋은느낌/원철
    2008. 6. 17. 09:25 개발/Java

    [스크랩 원문] http://logging.apache.org/log4j/1.2/manual.html


    Short introduction to log4j: Ceki G?c? March 2002

    Copyright ?2000-2002 The Apache Software Foundation. All rights reserved. This software is published under the terms of the Apache Software License version 2.0, a copy of which has been included in the LICENSE file shipped with the log4j distribution. This document is based on the article "Log4j delivers control over logging" published in November 2000 edition of JavaWorld. However, the present article contains more detailed and up to date information. The present short manual also borrows some text from "The complete log4j manual" by the same author (yours truly).

    Abstract

    This document describes the log4j API, its unique features and design rationale. Log4j is an open source project based on the work of many authors. It allows the developer to control which log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files. Best of all, log4j has a gentle learning curve. Beware: judging from user feedback, it is also quite addictive.

    Introduction

    Almost every large application includes its own logging or tracing API. In conformance with this rule, the E.U. SEMPER project decided to write its own tracing API. This was in early 1996. After countless enhancements, several incarnations and much work that API has evolved to become log4j, a popular logging package for Java. The package is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative. The latest log4j version, including full-source code, class files and documentation can be found at http://logging.apache.org/log4j/. By the way, log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.

    Inserting log statements into code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is usually the case for multithreaded applications and distributed applications at large.

    Experience indicates that logging was an important component of the development cycle. It offeres several advantages. It provides precise context about a run of the application. Once inserted into the code, the generation of logging output requires no human intervention. Moreover, log output can be saved in persistent medium to be studied at a later time. In addition to its use in the development cycle, a sufficiently rich logging package can also be viewed as an auditing tool.

    As Brian W. Kernighan and Rob Pike put it in their truly excellent book "The Practice of Programming"

      As personal choice, we tend not to use debuggers beyond getting a
      stack trace or the value of a variable or two. One reason is that it
      is easy to get lost in details of complicated data structures and
      control flow; we find stepping through a program less productive
      than thinking harder and adding output statements and self-checking
      code at critical places. Clicking over statements takes longer than
      scanning the output of judiciously-placed displays. It takes less
      time to decide where to put print statements than to single-step to
      the critical section of code, even assuming we know where that
      is. More important, debugging statements stay with the program;
      debugging sessions are transient.
    

    Logging does have its drawbacks. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast and extensible. Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use.

    Loggers, Appenders and Layouts

    Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

    Logger hierarchy

    The first and foremost advantage of any logging API over plain System.out.println resides in its ability to disable certain log statements while allowing others to print unhindered. This capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria. This observation had previously led us to choose category as the central concept of the package. However, since log4j version 1.2, Logger class has replaced the Category class. For those familiar with earlier versions of log4j, the Logger class can be considered as a mere alias to the Category class.

    Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule:

    Named Hierarchy
    A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger.

    For example, the logger named "com.foo" is a parent of the logger named "com.foo.Bar". Similarly, "java" is a parent of "java.util" and an ancestor of "java.util.Vector". This naming scheme should be familiar to most developers.

    The root logger resides at the top of the logger hierarchy. It is exceptional in two ways:

    1. it always exists,
    2. it cannot be retrieved by name.
    Invoking the class static Logger.getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class are listed below.

      package org.apache.log4j;
    
      public class Logger {
    
        // Creation & retrieval methods:
        public static Logger getRootLogger();
        public static Logger getLogger(String name);
    
        // printing methods:
        public void trace(Object message);
        public void debug(Object message);
        public void info(Object message);
        public void warn(Object message);
        public void error(Object message);
        public void fatal(Object message);
    
        // generic printing method:
        public void log(Level l, Object message);
    }
    

    Loggers may be assigned levels. The set of possible levels, that is:



    TRACE,

    DEBUG,

    INFO,

    WARN,

    ERROR and

    FATAL



    are defined in the org.apache.log4j.Level class. Although we do not encourage you to do so, you may define your own levels by sub-classing the Level class. A perhaps better approach will be explained later on.

    If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level. More formally:

    Level Inheritance

    The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.

    To ensure that all loggers can eventually inherit a level, the root logger always has an assigned level.

    Below are four tables with various assigned level values and the resulting inherited levels according to the above rule.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X none Proot
    X.Y none Proot
    X.Y.Z none Proot
    Example 1

    In example 1 above, only the root logger is assigned a level. This level value, Proot, is inherited by the other loggers X, X.Y and X.Y.Z.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X Px Px
    X.Y Pxy Pxy
    X.Y.Z Pxyz Pxyz
    Example 2

    In example 2, all loggers have an assigned level value. There is no need for level inheritence.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X Px Px
    X.Y none Px
    X.Y.Z Pxyz Pxyz
    Example 3

    In example 3, the loggers root, X and X.Y.Z are assigned the levels Proot, Px and Pxyz respectively. The logger X.Y inherits its level value from its parent X.

    Logger

    name
    Assigned

    level
    Inherited

    level
    root Proot Proot
    X Px Px
    X.Y none Px
    X.Y.Z none Px
    Example 4

    In example 4, the loggers root and X and are assigned the levels Proot and Px respectively. The loggers X.Y and X.Y.Z inherits their level value from their nearest parent X having an assigned level..

    Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.

    By definition, the printing method determines the level of a logging request. For example, if c is a logger instance, then the statement c.info("..") is a logging request of level INFO.

    A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. This rule is summarized below.

    Basic Selection Rule

    A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.

    This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

    Here is an example of this rule.

       // get a logger instance named "com.foo"
       Logger  logger = Logger.getLogger("com.foo");
    
       // Now set its level. Normally you do not need to set the
       // level of a logger programmatically. This is usually done
       // in configuration files.
       logger.setLevel(Level.INFO);
    
       Logger barlogger = Logger.getLogger("com.foo.Bar");
    
       // This request is enabled, because WARN >= INFO.
       logger.warn("Low fuel level.");
    
       // This request is disabled, because DEBUG < INFO.
       logger.debug("Starting search for nearest gas station.");
    
       // The logger instance barlogger, named "com.foo.Bar",
       // will inherit its level from the logger named
       // "com.foo" Thus, the following request is enabled
       // because INFO >= INFO.
       barlogger.info("Located nearest gas station.");
    
       // This request is disabled, because DEBUG < INFO.
       barlogger.debug("Exiting gas station search");
    

    Calling the getLogger method with the same name will always return a reference to the exact same logger object.

    For example, in

       Logger x = Logger.getLogger("wombat");
       Logger y = Logger.getLogger("wombat");
    x and y refer to exactly the same logger object.

    Thus, it is possible to configure a logger and then to retrieve the same instance somewhere else in the code without passing around references. In fundamental contradiction to biological parenthood, where parents always preceed their children, log4j loggers can be created and configured in any order. In particular, a "parent" logger will find and link to its descendants even if it is instantiated after them.

    Configuration of the log4j environment is typically done at application initialization. The preferred way is by reading a configuration file. This approach will be discussed shortly.

    Log4j makes it easy to name loggers by software component. This can be accomplished by statically instantiating a logger in each class, with the logger name equal to the fully qualified name of the class. This is a useful and straightforward method of defining loggers. As the log output bears the name of the generating logger, this naming strategy makes it easy to identify the origin of a log message. However, this is only one possible, albeit common, strategy for naming loggers. Log4j does not restrict the possible set of loggers. The developer is free to name the loggers as desired.

    Nevertheless, naming loggers after the class where they are located seems to be the best strategy known so far.

    Appenders and Layouts

    The ability to selectively enable or disable logging requests based on their logger is only part of the picture. Log4j allows logging requests to print to multiple destinations. In log4j speak, an output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. It is also possible to log asynchronously.

    More than one appender can be attached to a logger.

    The addAppender method adds an appender to a given logger. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy. In other words, appenders are inherited additively from the logger hierarchy. For example, if a console appender is added to the root logger, then all enabled logging requests will at least print on the console. If in addition a file appender is added to a logger, say C, then enabled logging requests for C and C's children will print on a file and on the console. It is possible to override this default behavior so that appender accumulation is no longer additive by setting the additivity flag to false.

    The rules governing appender additivity are summarized below.

    Appender Additivity

    The output of a log statement of logger C will go to all the appenders in C and its ancestors. This is the meaning of the term "appender additivity".

    However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and it's ancestors upto and including P but not the appenders in any of the ancestors of P.

    Loggers have their additivity flag set to true by default.

    The table below shows an example:

    Logger

    Name
    Added

    Appenders
    Additivity

    Flag
    Output Targets Comment
    root A1 not applicable A1 The root logger is anonymous but can be accessed with the Logger.getRootLogger() method. There is no default appender attached to root.
    x A-x1, A-x2 true A1, A-x1, A-x2 Appenders of "x" and root.
    x.y none true A1, A-x1, A-x2 Appenders of "x" and root.
    x.y.z A-xyz1 true A1, A-x1, A-x2, A-xyz1 Appenders in "x.y.z", "x" and root.
    security A-sec false A-sec No appender accumulation since the additivity flag is set to false.
    security.access none true A-sec Only appenders of "security" because the additivity flag in "security" is set to false.

    More often than not, users wish to customize not only the output destination but also the output format. This is accomplished by associating a layout with an appender. The layout is responsible for formatting the logging request according to the user's wishes, whereas an appender takes care of sending the formatted output to its destination.

    The PatternLayout, part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.

    For example, the PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output something akin to:

    176 [main] INFO  org.foo.Bar - Located nearest gas station.
    

    The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.

    Just as importantly, log4j will render the content of the log message according to user specified criteria. For example, if you frequently need to log Oranges, an object type used in your current project, then you can register an OrangeRenderer that will be invoked whenever an orange needs to be logged.

    Object rendering follows the class hierarchy. For example, assuming oranges are fruits, if you register an FruitRenderer, all fruits including oranges will be rendered by the FruitRenderer, unless of course you registered an orange specific OrangeRenderer.

    Object renderers have to implement the ObjectRenderer interface.

    Configuration

    Inserting log requests into the application code requires a fair amount of planning and effort. Observation shows that approximately 4 percent of code is dedicated to logging. Consequently, even moderately sized applications will have thousands of logging statements embedded within their code. Given their number, it becomes imperative to manage these log statements without the need to modify them manually.

    The log4j environment is fully configurable programmatically. However, it is far more flexible to configure log4j using configuration files. Currently, configuration files can be written in XML or in Java properties (key=value) format.

    Let us give a taste of how this is done with the help of an imaginary application MyApp that uses log4j.

     import com.foo.Bar;
    
     // Import log4j classes.
     import org.apache.log4j.Logger;
     import org.apache.log4j.BasicConfigurator;
    
     public class MyApp {
    
       // Define a static logger variable so that it references the
       // Logger instance named "MyApp".
       static Logger logger = Logger.getLogger(MyApp.class);
    
       public static void main(String[] args) {
    
         // Set up a simple configuration that logs on the console.
         BasicConfigurator.configure();
    
         logger.info("Entering application.");
         Bar bar = new Bar();
         bar.doIt();
         logger.info("Exiting application.");
       }
     }
    

    MyApp begins by importing log4j related classes. It then defines a static logger variable with the name MyApp which happens to be the fully qualified name of the class.

    MyApp uses the Bar class defined in the package com.foo.

     package com.foo;
     import org.apache.log4j.Logger;
    
     public class Bar {
       static Logger logger = Logger.getLogger(Bar.class);
    
       public void doIt() {
         logger.debug("Did it again!");
       }
     }
    

    The invocation of the BasicConfigurator.configure method creates a rather simple log4j setup. This method is hardwired to add to the root logger a ConsoleAppender. The output will be formatted using a PatternLayout set to the pattern "%-4r [%t] %-5p %c %x - %m%n".

    Note that by default, the root logger is assigned to Level.DEBUG.

    The output of MyApp is:

    0    [main] INFO  MyApp  - Entering application.
    36   [main] DEBUG com.foo.Bar  - Did it again!
    51   [main] INFO  MyApp  - Exiting application.
    

    The figure below depicts the object diagram of MyApp after just having called the BasicConfigurator.configure method.

    As a side note, let me mention that in log4j child loggers link only to their existing ancestors. In particular, the logger named com.foo.Bar is linked directly to the root logger, thereby circumventing the unused com or com.foo loggers. This significantly increases performance and reduces log4j's memory footprint.

    The MyApp class configures log4j by invoking BasicConfigurator.configure method. Other classes only need to import the org.apache.log4j.Logger class, retrieve the loggers they wish to use, and log away.

    The previous example always outputs the same log information. Fortunately, it is easy to modify MyApp so that the log output can be controlled at run-time. Here is a slightly modified version.

     import com.foo.Bar;
    
     import org.apache.log4j.Logger;
     import org.apache.log4j.PropertyConfigurator;
    
     public class MyApp {
    
       static Logger logger = Logger.getLogger(MyApp.class.getName());
    
       public static void main(String[] args) {
    
    
         // BasicConfigurator replaced with PropertyConfigurator.
         PropertyConfigurator.configure(args[0]);
    
         logger.info("Entering application.");
         Bar bar = new Bar();
         bar.doIt();
         logger.info("Exiting application.");
       }
     }
    

    This version of MyApp instructs PropertyConfigurator to parse a configuration file and set up logging accordingly.

    Here is a sample configuration file that results in exactly same output as the previous BasicConfigurator based example.

    # Set root logger level to DEBUG and its only appender to A1.
    log4j.rootLogger=DEBUG, A1
    
    # A1 is set to be a ConsoleAppender.
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    
    # A1 uses PatternLayout.
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
    

    Suppose we are no longer interested in seeing the output of any component belonging to the com.foo package. The following configuration file shows one possible way of achieving this.

    log4j.rootLogger=DEBUG, A1
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    
    # Print the date in ISO 8601 format
    log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
    
    # Print only messages of level WARN or above in the package com.foo.
    log4j.logger.com.foo=WARN
    

    The output of MyApp configured with this file is shown below.

    2000-09-07 14:07:41,508 [main] INFO  MyApp - Entering application.
    2000-09-07 14:07:41,529 [main] INFO  MyApp - Exiting application.
    

    As the logger com.foo.Bar does not have an assigned level, it inherits its level from com.foo, which was set to WARN in the configuration file. The log statement from the Bar.doIt method has the level DEBUG, lower than the logger level WARN. Consequently, doIt() method's log request is suppressed.

    Here is another configuration file that uses multiple appenders.

    log4j.rootLogger=debug, stdout, R
    
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    
    # Pattern to output the caller's file name and line number.
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
    
    log4j.appender.R=org.apache.log4j.RollingFileAppender
    log4j.appender.R.File=example.log
    
    log4j.appender.R.MaxFileSize=100KB
    # Keep one backup file
    log4j.appender.R.MaxBackupIndex=1
    
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
    

    Calling the enhanced MyApp with the this configuration file will output the following on the console.

     INFO [main] (MyApp2.java:12) - Entering application.
    DEBUG [main] (Bar.java:8) - Doing it again!
     INFO [main] (MyApp2.java:15) - Exiting application.
    

    In addition, as the root logger has been allocated a second appender, output will also be directed to the example.log file. This file will be rolled over when it reaches 100KB. When roll-over occurs, the old version of example.log is automatically moved to example.log.1.

    Note that to obtain these different logging behaviors we did not need to recompile code. We could just as easily have logged to a UNIX Syslog daemon, redirected all com.foo output to an NT Event logger, or forwarded logging events to a remote log4j server, which would log according to local server policy, for example by forwarding the log event to a second log4j server.

    Default Initialization Procedure

    The log4j library does not make any assumptions about its environment. In particular, there are no default log4j appenders. Under certain well-defined circumstances however, the static inializer of the Logger class will attempt to automatically configure log4j. The Java language guarantees that the static initializer of a class is called once and only once during the loading of a class into memory. It is important to remember that different classloaders may load distinct copies of the same class. These copies of the same class are considered as totally unrelated by the JVM.

    The default initialization is very useful in environments where the exact entry point to the application depends on the runtime environment. For example, the same application can be used as a stand-alone application, as an applet, or as a servlet under the control of a web-server.

    The exact default initialization algorithm is defined as follows:

    1. Setting the log4j.defaultInitOverride system property to any other value then "false" will cause log4j to skip the default initialization procedure (this procedure).
    2. Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value "log4j.properties".
    3. Attempt to convert the resource variable to a URL.
    4. If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the classpath by calling org.apache.log4j.helpers.Loader.getResource(resource, Logger.class) which returns a URL. Note that the string "log4j.properties" constitutes a malformed URL. See Loader.getResource(java.lang.String) for the list of searched locations.
    5. If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL. The PropertyConfigurator will be used to parse the URL to configure log4j unless the URL ends with the ".xml" extension, in which case the DOMConfigurator will be used. You can optionaly specify a custom configurator. The value of the log4j.configuratorClass system property is taken as the fully qualified class name of your custom configurator. The custom configurator you specify must implement the Configurator interface.

    Example Configurations

    Default Initialization under Tomcat

    The default log4j initialization is particularly useful in web-server environments. Under Tomcat 3.x and 4.x, you should place the log4j.properties under the WEB-INF/classes directory of your web-applications. Log4j will find the properties file and initialize itself. This is easy to do and it works. You can also choose to set the system property log4j.configuration before starting Tomcat. For Tomcat 3.x The TOMCAT_OPTS environment variable is used to set command line options. For Tomcat 4.0, set the CATALINA_OPTS environment variable instead of TOMCAT_OPTS. Example 1

    The Unix shell command

       export TOMCAT_OPTS="-Dlog4j.configuration=foobar.txt"
    
    tells log4j to use the file foobar.txt as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. The file will be read using the PropertyConfigurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

    Example 2

    The Unix shell command

       export TOMCAT_OPTS="-Dlog4j.debug -Dlog4j.configuration=foobar.xml"
    
    tells log4j to output log4j-internal debugging information and to use the file foobar.xml as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. Since the file ends with a .xml extension, it will read using the DOMConfigurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

    Example 3

    The Windows shell command

       set TOMCAT_OPTS=-Dlog4j.configuration=foobar.lcf -Dlog4j.configuratorClass=com.foo.BarConfigurator
    
    tells log4j to use the file foobar.lcf as the default configuration file. This file should be place under the WEB-INF/classes directory of your web-application. Due to the definition of the log4j.configuratorClass system property, the file will be read using the com.foo.BarConfigurator custom configurator. Each web-application will use a different default configuration file because each file is relative to a web-application.

    Example 4

    The Windows shell command

       set TOMCAT_OPTS=-Dlog4j.configuration=file:/c:/foobar.lcf
    tells log4j to use the file c:\foobar.lcf as the default configuration file. The configuration file is fully specified by the URL file:/c:/foobar.lcf. Thus, the same configuration file will be used for all web-applications.

    Different web-applications will load the log4j classes through their respective classloaderss. Thus, each image of the log4j environment will act independetly and without any mutual synchronization. For example, FileAppenders defined exactly the same way in multiple web-application configurations will all attempt to write the same file. The results are likely to be less than satisfactory. You must make sure that log4j configurations of different web-applications do not use the same underlying system resource.

    Initialization servlet

    It is also possible to use a special servlet for log4j initialization. Here is an example,

    package com.foo;
    
    import org.apache.log4j.PropertyConfigurator;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.PrintWriter;
    import java.io.IOException;
    
    public class Log4jInit extends HttpServlet {
    
      public
      void init() {
        String prefix =  getServletContext().getRealPath("/");
        String file = getInitParameter("log4j-init-file");
        // if the log4j-init-file is not set, then no point in trying
        if(file != null) {
          PropertyConfigurator.configure(prefix+file);
        }
      }
    
      public
      void doGet(HttpServletRequest req, HttpServletResponse res) {
      }
    }
    

    Define the following servlet in the web.xml file for your web-application.

      <servlet>
        <servlet-name>log4j-init</servlet-name>
        <servlet-class>com.foo.Log4jInit</servlet-class>
    
        <init-param>
          <param-name>log4j-init-file</param-name>
          <param-value>WEB-INF/classes/log4j.lcf</param-value>
        </init-param>
    
        <load-on-startup>1</load-on-startup>
      </servlet>
    

    Writing an initialization servlet is the most flexible way for initializing log4j. There are no constraints on the code you can place in the init() method of the servlet.

    Nested Diagnostic Contexts

    Most real-world systems have to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. Logging is especially well suited to trace and debug complex distributed applications. A common approach to differentiate the logging output of one client from another is to instantiate a new separate logger for each client. This promotes the proliferation of loggers and increases the management overhead of logging.

    A lighter technique is to uniquely stamp each log request initiated from the same client interaction. Neil Harrison described this method in the book "Patterns for Logging Diagnostic Messages," in Pattern Languages of Program Design 3, edited by R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley, 1997).

    To uniquely stamp each request, the user pushes contextual information into the NDC, the abbreviation of Nested Diagnostic Context. The NDC class is shown below.

      public class NDC {
        // Used when printing the diagnostic
        public static String get();
    
        // Remove the top of the context from the NDC.
        public static String pop();
    
        // Add diagnostic context for the current thread.
        public static void push(String message);
    
        // Remove the diagnostic context for this thread.
        public static void remove();
      }
    

    The NDC is managed per thread as a stack of contextual information. Note that all methods of the org.apache.log4j.NDC class are static. Assuming that NDC printing is turned on, every time a log request is made, the appropriate log4j component will include the entire NDC stack for the current thread in the log output. This is done without the intervention of the user, who is responsible only for placing the correct information in the NDC by using the push and pop methods at a few well-defined points in the code. In contrast, the per-client logger approach commands extensive changes in the code.

    To illustrate this point, let us take the example of a servlet delivering content to numerous clients. The servlet can build the NDC at the very beginning of the request before executing other code. The contextual information can be the client's host name and other information inherent to the request, typically information contained in cookies. Hence, even if the servlet is serving multiple clients simultaneously, the logs initiated by the same code, i.e. belonging to the same logger, can still be distinguished because each client request will have a different NDC stack. Contrast this with the complexity of passing a freshly instantiated logger to all code exercised during the client's request.

    Nevertheless, some sophisticated applications, such as virtual hosting web servers, must log differently depending on the virtual host context and also depending on the software component issuing the request. Recent log4j releases support multiple hierarchy trees. This enhancement allows each virtual host to possess its own copy of the logger hierarchy.

    Performance

    One of the often-cited arguments against logging is its computational cost. This is a legitimate concern as even moderately sized applications can generate thousands of log requests. Much effort was spent measuring and tweaking logging performance. Log4j claims to be fast and flexible: speed first, flexibility second.

    The user should be aware of the following performance issues.

    1. Logging performance when logging is turned off.

      When logging is turned off entirely or just for a set of levels, the cost of a log request consists of a method invocation plus an integer comparison. On a 233 MHz Pentium II machine this cost is typically in the 5 to 50 nanosecond range.

      However, The method invocation involves the "hidden" cost of parameter construction.

      For example, for some logger cat, writing,

           logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
          
      incurs the cost of constructing the message parameter, i.e. converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. This cost of parameter construction can be quite high and it depends on the size of the parameters involved.

      To avoid the parameter construction cost write:

            if(logger.isDebugEnabled() {
              logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
            }
         

      This will not incur the cost of parameter construction if debugging is disabled. On the other hand, if the logger is debug-enabled, it will incur twice the cost of evaluating whether the logger is enabled or not: once in debugEnabled and once in debug. This is an insignificant overhead because evaluating a logger takes about 1% of the time it takes to actually log.

      In log4j, logging requests are made to instances of the Logger class. Logger is a class and not an interface. This measurably reduces the cost of method invocation at the cost of some flexibility.

      Certain users resort to preprocessing or compile-time techniques to compile out all log statements. This leads to perfect performance efficiency with respect to logging. However, since the resulting application binary does not contain any log statements, logging cannot be turned on for that binary. In my opinion this is a disproportionate price to pay in exchange for a small performance gain.

    2. The performance of deciding whether to log or not to log when logging is turned on.

      This is essentially the performance of walking the logger hierarchy. When logging is turned on, log4j still needs to compare the level of the log request with the level of the request logger. However, loggers may not have an assigned level; they can inherit them from the logger hierarchy. Thus, before inheriting a level, the logger may need to search its ancestors.

      There has been a serious effort to make this hierarchy walk to be as fast as possible. For example, child loggers link only to their existing ancestors. In the BasicConfigurator example shown earlier, the logger named com.foo.Bar is linked directly to the root logger, thereby circumventing the nonexistent com or com.foo loggers. This significantly improves the speed of the walk, especially in "sparse" hierarchies.

      The typical cost of walking the hierarchy is typically 3 times slower than when logging is turned off entirely.

    3. Actually outputting log messages

      This is the cost of formatting the log output and sending it to its target destination. Here again, a serious effort was made to make layouts (formatters) perform as quickly as possible. The same is true for appenders. The typical cost of actually logging is about 100 to 300 microseconds. See org.apache.log4.performance.Logging for actual figures.

    Although log4j has many features, its first design goal was speed. Some log4j components have been rewritten many times to improve performance. Nevertheless, contributors frequently come up with new optimizations. You should be pleased to know that when configured with the SimpleLayout performance tests have shown log4j to log as quickly as System.out.println.

    Conclusions

    Log4j is a popular logging package written in Java. One of its distinctive features is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrary granularity. This helps reduce the volume of logged output and minimize the cost of logging.

    One of the advantages of the log4j API is its manageability. Once the log statements have been inserted into the code, they can be controlled with configuration files. They can be selectively enabled or disabled, and sent to different and multiple output targets in user-chosen formats. The log4j package is designed so that log statements can remain in shipped code without incurring a heavy performance cost.

    Acknowledgments

    Many thanks to N. Asokan for reviewing the article. He is also one of the originators of the logger concept. I am indebted to Nelson Minar for encouraging me to write this article. He has also made many useful suggestions and corrections to this article. Log4j is the result of a collective effort. My special thanks go to all the authors who have contributed to the project. Without exception, the best features in the package have all originated in the user community.
    posted by 좋은느낌/원철
    2008. 6. 17. 09:20 개발/Java

    Ant

    스크랩 원본 : http://www.javastudy.co.kr/docs/lec_oop/ant/ant1.htm

    ANT (상): Ant 무엇에 쓰는 물건인고?

    저자: 김영익

    자바 빌드 도구인 Ant와 이를 이용한 실전예제를 다루는 기사이다. Ant는 실제로 어떤 프로그램을 개발하느냐에 상관없이 사용되는 빌드 도구로 얼마나 개발을 편리하게 해주느냐가 관건이지 프로그램이나 프로젝트와는 특별한 관계가 없다. 본 기사는 모든 자바 개발자를 대상으로하여 작성되었다. 초급자에게는 앞으로 진행할 프고젝트나 프로그램을 편하게 개발할 수 있게 해주며, 중급 이상자에게는 더욱 더 게을러질 수 있는(?) 기회를 제공해 줄 것이다.

    1. Ant 개요

    다음은 Ant를 소개하는 자카르타 사이트의 원문 중에서 처음 부분이다.
    Apache Ant is a Java based build tool. In theory it is kind of like make without make's wrinkles. Why another build tool when there is already make, gnumake, nmake, jam, and others? Because all of those tools have limitations that Ant's original author couldn't live with when developing software across multiple platforms. . . . 이후 생략(http://jakarta.apache.org/ant/index.html 참고).
    Ant가 탄생하게 된 배경을 원문과 필자의 경험으로 간추려 보면 다음과 같다.
    C나 C++를 사용하는 개발자들은 대부분 make나 nmake 또는 기타 다른 빌드 도구를 사용해왔다. 그렇다면 자바 개발자들은 어떤 빌드 도구를 사용할 것인가? 물론 make를 사용할 수 있다. 실제로 필자도 본인과 절친한 개발자가 만든 make 파일을 사용한 적이 있었다. 하지만 근본적으로 자바 언어를 위한 것이 아니기 때문에 불편하고 심지어는 필요한 기능이 없을 수도 있다. 하지만 이제는 걱정할 필요가 없다. 우리에겐 Ant가 있기 때문이다. Ant는 make를 비롯한 기존의 빌드 도구를 사용하면서 겪게 되는 많은 어려움을 줄여주면서 더 많은 기능을 제공한다. 물론 처음 배우는 개발자들에겐 약간의 시간을 투자해야 하는 부담이 가겠지만 일단 배우고 나면 그 효과는 투자한 시간에 비해 몇 배 이상이 될 것이다.
    Ant와 같은 빌드 도구를 사용하지 않을 경우 도스 창에서 클래스 패스에 클래스를 추가하거나 소스 파일 컴파일, jar 파일로 묶는 작업, 묶은 jar 파일을 특정 디렉토리로 이동시키고 수정된 내용을 javadoc으로 문서화 시키는 등의 작업은 소스가 수정될 때마다 한 단계씩 도스 창에서 모두 입력해야 한다. 하지만 Ant를 사용하면 마치 배치(bat) 파일을 실행한 것처럼 이와 같은 일련의 작업들을 Ant를 이용하여 단 한번에 수행할 수 있다. 정말 편리하지 않겠는가?

    Ant의 주요 기능을 알기 쉽게 몇 가지만 나열해 보면 아래와 같다.
    • 자바 소스 파일 컴파일(너무 당연하다)
    • jar, war, ear, zip 파일의 생성
    • javadoc을 실행하여 도움말 생성
    • 파일이나 폴더의 이동 및 복사, 삭제
    • 각각의 작업에 대한 의존성 설정
    • 유닉스에서처럼 파일이나 폴더에 퍼미션 설정
    • 파일의 변경 날짜를 설정하는 touch 기능
    • 외부 프로그램의 실행
    이외에도 너무 많아서 나열할 수 가 없을 정도로 많은 기능들이 있다. 하지만 뭐니 뭐니 해도 가장 유용한 기능은 빌드할 때마다 수많은 키보드를 두드려야 하는 단순 노동을 하지 않아도 된다는 것이고 플랫폼에 무관한 XML을 이용한다는 것이다. XML을 사용하는 것이 무슨 장점이 될 수 있냐고 하실 분들도 있을지 모르겠다. 하지만 예전에 make 파일을 사용하면서 특정 부분에서 항상 앞에 탭(tab)키를 입력해야만 하는 것을 몰라서 개발자들이 고생하는 것을 본 적이 있다. Ant의 등장은 이와 같은 모호함을 없애자는 것이다. 또한 XML은 이미 IT 업계의 상당 부분에서 표준으로 자리를 잡아 가고 있는 현실이다. 냉혹한 현실에 뒤쳐지는 개발자는 살아 남을 수 없다.

    2. 어디에서 Ant를 구할 수 있나?

    Ant는 Jakarta 사이트에 가면 다운 받을 수 있다. 어서 가서 받아 두자.
    http://jakarta.apache.org/builds/ant/release/v1.4.1/bin/

    이 글을 쓰는 시점에서는 버전 1.4.1이 가장 최신의 버전이지만 Ant도 버전에 따라 API의 변화가 있다. 버전이 다르면 빌드할 때 'deprecated …'와 같은 메시지가 뜨거나 에러가 발생할 수 있으므로 가능한 한 같은 버전을 다운 받아서 사용하길 권장하는 바이다.

    3. Ant 설치

    설치에는 그다지 복잡한 사항이 없다. 일단 사이트에서 다운로드 받은 압축 파일(jakarta-ant-1.4.1-bin.zip)을 적당한 위치에 풀어놓기만 하면 된다. 그리고 몇 가지 환경 설정을 추가로 해줄 필요가 있다.

    설치한 폴더가 c:\dev\tools\jakarta-ant-1.4.1 일 경우 [그림 1]처럼 디렉토리와 파일들이 생성된다.

    /bin : Ant 실행을 위한 배치 파일이 있다(유닉스나 리눅스의 경우 셸 파일 사용)
    /lib : jar 파일들
    /docs : 매뉴얼과 API 문서가 있다.


    [그림 1] 설치 후 디렉토리 및 파일

    윈도우 환경에서는 환경 설정을 다음과 같이 해주면 된다.
    set ANT_HOME=c:\dev\tools\jakarta-ant-1.4.1
    set JAVA_HOME=c:\jdk1.3.1
    set PATH=%PATH%;%ANT_HOME%\bin
    
    유닉스나 기타 다른 운영체제에서의 설정은 Ant 매뉴얼(http://jakarta.apache.org/ant/manual/install.html)을 참고하기 바란다.

    4. Hello Ant !

    이제 설치가 끝났으니 실전 예제로 들어가 보도록 하자. 개발자들에게는 이미 익숙한 Hello 예제부터 시작할 것이다.

    4.1 준비하기

    먼저 적절한 폴더 설정과 소스 파일이 당연히 필요하다. 그림과 같이 c:\\ant_test 폴더를 만들고 하위 폴더로 classes, doc, jar, src 폴더를 생성한다. 그리고 src 폴더 밑에는 HelloAnt.java 파일을 하나 생성한다.


    [그림 2] HelloAnt.java 파일을 만든다

    HelloAnt.java의 내용은 어떤 것이라도 상관 없으니 여러분께서 알아서 하시길...

    4.2 Build.xml

    Ant를 실행하면 초기값으로 현재 폴더에 있는 build.xml 파일을 찾아서 빌드하게 된다. 여기에서는 build.xml 파일의 위치를 "C:\ant_test" 밑에 두었다.


    [그림 3] build.xml 생성

    이제부터는 build.xml 파일을 살펴볼 것이다. 혹시 XML에 익숙치 않다고 하더라도 겁먹지 말고 차근차근 살펴보도록 하자. 만약 아래의 XML 파일을 사용할 때는 반드시 주석문을 제거하고 사용해야 한다. 그렇지 않으면 Ant를 실행할 때 에러가 발생한다.
    <?xml version="1.0"?>
    
    <!--
    name : 프로젝트 이름
    default : 초기치로 설정되는 작업, 아무 것도 지정하지 않고 실행하면 이 작업을 수행
    basedir : 프로젝트에 대한 기준 폴더를 지정
    property : 프로젝트에서 사용할 각 폴더들의 위치를 지정
    ${basedir} : 이미 앞에서 설정된 값을 읽어온다
    -->
    
    <project name="HelloAnt" default="javadoc" basedir="." >
    <property name="src.dir" value="${basedir}/src" />
    <property name="classes.dir" value="${basedir}/classes" />
    <property name="jar.dir" value="${basedir}/jar" />
    <property name="javadoc.dir" value="${basedir}/doc" />
    
    
    <!--
    target : 각각의 타겟을 지정, 타겟이란 프로젝트를 이루는 하나 하나의 작업 단위
    srcdir : 컴파일 하기 위한 자바 소스 파일의 위치를 지정
    destdir : 어느 폴더에 클래스 파일들을 위치 시킬지 지정
    -->
    
    <target name="compile" >
    <javac srcdir="${src.dir}" destdir="${classes.dir}" />
    </target>
    
    <!--
    jar : 파일을 만든다
    depends : compile 정상적으로 수행되어야만 진행
    jarfile : jar 파일의 위치와 파일 이름 지정
    basedir : jar로 묶을 클래스 파일의 위치
    includes : 모든 폴더에서 클래스 파일들만 포함
    -->
    
    <target name="jar" depends="compile">
    <jar jarfile="${jar.dir}/hello.jar"
    basedir="${classes.dir}"
    includes="**/*.class"
    />
    </target>
    
    <!--
    javadoc을 실행
    depends : compile과 jar 수행이 정상적으로 끝나야만 실행
    sourcepath : 소스 폴더 지정
    sourcefiles : 소스 파일 지정
    windowtitle : 제목 지정
    destdir : 파일 생성후 저장할 폴더 지정
    -->
    
    <target name="javadoc" depends="compile, jar" >
    <javadoc
    sourcepath="${src.dir}"
    sourcefiles="${src.dir}/HelloAnt.java"
    windowtitle="HelloAnt API"
    destdir="${javadoc.dir}"
    />
    </target>
    
    <!--
    소스 코드를 제외한 모든 작업 파일들과 폴더를 삭제한다
    -->
    
    <target name="clean" >
    <delete dir="${classes.dir}/classes/*"/>
    <delete dir="${jar.dir}/jar/*"/>
    <delete dir="${javadoc.dir}/doc/*"/>
    </target>
    
    </project>
    
    이런 파일을 한번만 만들어 두면 다른 프로젝트를 할 때도 조금씩 수정해서 계속 써먹을 수 있다. 재사용(reuse)이란 그래서 좋은 것이다.

    4.3 Ant 실행

    그럼 어떻게 실행하면 될까? 먼저 실행할 때 필요한 옵션으로는 어떤 것들이 있는지 알아보자. 도스 창 프롬프트에서 'ant ?help' 라고 입력한다
    C:\ant_test>ant -help
    ant [options] [target [target2 [target3] ...]]
    Options :
      -help                   도움말을 보여준다.
      -projecthelp            프로젝트에 필요한 도움을 보여준다
      -version                현재 ant 버전을 보여준다
      -quiet                  build하는 과정을 디스플레이 하지 않는다.
      -verbose                verbose모드를 실시한다.
      -debug                  debugging 정보를 보여준다.
      -emacs                  로깅 정보를 만들어낸다
      -logfile file           주어진 파일로 로그를 출력한다.
      -logger classname       클래스를 이용하여 로깅을 수행한다.
      -listener classname     리스너클래스를 추가한다.
      -buildfile file         대상 build파일을 정의한다.
      -D<property>=<value>    build설정에 필요한 프로퍼티를 사용한다.
      -find file              루트로부터 buildfile을 찾아서 실행한다.
    
    앞에서 만든 빌드 파일을 실행한 결과는 다음과 같다. 실행은 build.xml 파일이 있는 폴더에서 도스 창을 열고 'ant'라고만 입력하면 된다.
    C:\ant_test>ant
    Buildfile: build.xml
    
    compile:
    
    jar:
    
    javadoc:
      [javadoc] Generating Javadoc
      [javadoc] Javadoc execution
      [javadoc] Loading source file C:\ant_test\src\HelloAnt.java...
      [javadoc] Constructing Javadoc information...
      [javadoc] Building tree for all the packages and classes...
      [javadoc] Building index for all the packages and classes...
      [javadoc] Building index for all classes...
    
    BUILD SUCCESSFUL
    
    Total time: 3 seconds
    C:\ant_test>
    
    폴더를 살펴보면 각 폴더에 클래스 파일들, jar 파일, HTML 문서가 생성된 것을 확인할 수 있다. 만일 Ant를 실행할 때 에러가 발생했다면 왜 에러가 발생하는 것인가? 앞에서 필자는 주석문을 제거하고 사용하기를 권고했다. 주석문을 제거하지 않고 사용할 경우 다음과 같은 에러 메시지를 출력하면서 Ant는 실패 결과를 알려준다.
    C:\ant_test>ant
    Buildfile: build.xml
    
    BUILD FAILED
    
    C:\ant_test\build.xml:1: Character conversion error: "Malformed UTF-8 char -- is
     an XML encoding declaration missing?" (line number may be too low).
    
    Total time: 0 seconds
    C:\ant_test>
    
    위와 같이 에러가 발생했을 경우 메시지를 보면서 하나씩 해결해 나가도록 하자. 그리고 그 해결은 여러분 스스로 해보길 바란다.

    다음 기사에서는 Ant 실전 예제를 비록하여 Jbuilder에서 AntRunner 사용하기에 대해 살펴볼 것이다.
    posted by 좋은느낌/원철
    prev 1 2 next