隨筆-57  評(píng)論-202  文章-17  trackbacks-0
                使用Jakarta Commons Pool可以根據(jù)需要快速的實(shí)現(xiàn)自己的對(duì)象池,只需要實(shí)現(xiàn)PoolableObjectFactory或者KeyedPoolableObjectFactory接口。KeyedPoolableObjectFactory和PoolableObjectFactory的不同之處在于KeyedPoolableObjectFactory的每個(gè)方法都比PoolableObjectFactory多了一個(gè)Object key的參數(shù),使用這個(gè)參數(shù)可以使得對(duì)象池中的每個(gè)對(duì)象都有所不同。
                PoolableObjectFactory定義了五個(gè)方法(摘至Jakarta Commons Pool API文檔):
          1. makeObject is called whenever a new instance is needed.
          2. activateObject is invoked on every instance before it is returned from the pool.
          3. passivateObject is invoked on every instance when it is returned to the pool.
          4. destroyObject is invoked on every instance when it is being "dropped" from the pool (whether due to the response from validateObject, or for reasons specific to the pool implementation.)
          5. validateObject is invoked in an implementation-specific fashion to determine if an instance is still valid to be returned by the pool. It will only be invoked on an "activated" instance. 


                下面是我的一個(gè)SocketChannel對(duì)象池的實(shí)現(xiàn),實(shí)現(xiàn)了KeyedPoolableObjectFactory接口。

          package sample.pool;

          import java.net.SocketAddress;
          import java.nio.channels.SocketChannel;

          import org.apache.commons.pool.KeyedPoolableObjectFactory;

          /**
           * <p>Title: </p>
           *
           * <p>Description: </p>
           *
           * <p>Copyright: Copyright (c) 2005</p>
           *
           * <p>Company: </p>
           *
           * @author George Hill
           * @version 1.0
           
          */


          public class SocketPoolableObjectFactory implements KeyedPoolableObjectFactory {

              
          /**
               * 創(chuàng)建新的對(duì)象
               * @param key Object 創(chuàng)建對(duì)象需要用到的參數(shù)
               * @return Object SocketChannel實(shí)例
               * @throws Exception
               
          */

              
          public Object makeObject(Object key) throws Exception {
              SocketAddress address 
          = (SocketAddress) key;

              
          // 創(chuàng)建SocketChannel
              SocketChannel channel = SocketChannel.open(address);

              
          return channel;
            }


            
          /**
             * 銷毀對(duì)象
             * @param key Object 創(chuàng)建對(duì)象時(shí)的參數(shù)
             * @param obj Object 需要銷毀的對(duì)象
             * @throws Exception
             
          */

            
          public void destroyObject(Object key, Object obj) throws Exception {
              SocketChannel channel 
          = (SocketChannel) obj;

              
          if (channel != null)
                channel.close();
              channel 
          = null;
            }


            
          /**
             * 檢驗(yàn)對(duì)象是否有效
             * @param key Object 創(chuàng)建對(duì)象時(shí)的參數(shù)
             * @param obj Object 需要進(jìn)行檢驗(yàn)的對(duì)象
             * @return boolean 有效返回true,無(wú)效返回false
             
          */

            
          public boolean validateObject(Object key, Object obj) {
              SocketChannel channel 
          = (SocketChannel) obj;

              
          if (channel != null && channel.isOpen() && channel.isConnected())
                
          return true;

              
          return false;
            }


            
          /**
             * 將對(duì)象激活,這里不需要做任何工作
             * @param key Object
             * @param obj Object
             * @throws Exception
             
          */

            
          public void activateObject(Object key, Object obj) throws Exception {
            }


            
          /**
             * 將對(duì)象掛起,這里不需要做任何工作
             * @param key Object
             * @param obj Object
             * @throws Exception
             
          */

            
          public void passivateObject(Object key, Object obj) throws Exception {
            }


          }

                我的測(cè)試程序:

          package sample.pool;

          import java.io.IOException;
          import java.net.
          *;
          import java.nio.ByteBuffer;
          import java.nio.channels.
          *;
          import java.util.
          *;

          import org.apache.commons.pool.
          *;
          import org.apache.commons.pool.impl.
          *;

          /**
           * <p>Title: 測(cè)試的線程類</p>
           *
           * <p>Description: </p>
           *
           * <p>Copyright: Copyright (c) 2005</p>
           *
           * <p>Company: </p>
           *
           * @author George Hill
           * @version 1.0
           
          */


          public class TestThread implements Runnable {

            
          // 線程名稱
            private String name;

            
          // 對(duì)象池
            private KeyedObjectPool pool;

            
          // 連接的網(wǎng)絡(luò)地址
            private InetSocketAddress address;

            
          public TestThread(String name, KeyedObjectPool pool,
                              InetSocketAddress address) 
          {
              
          this.name = name;
              
          this.pool = pool;
              
          this.address = address;
            }


            
          public void run() {
              System.
          out.println(name + ": Client Start");
              SocketChannel channel 
          = null;

              
          try {
                channel 
          = (SocketChannel) pool.borrowObject(address);
              }

              
          catch (Exception ex) {
                ex.printStackTrace();
              }


              
          // 從對(duì)象池中借出對(duì)象成功
              if (channel != null{
                System.
          out.println(name + ": Borrow Channel successfully!");

                
          try {
                  channel.configureBlocking(
          false);

                  
          // 創(chuàng)建Selector
                  Selector selector = Selector.open();
                  
          // 向Selector注冊(cè)我們需要的READ事件
                  SelectionKey skey = channel.register(selector, SelectionKey.OP_READ);

                  boolean stop 
          = false;
                  
          int n = 0;
                  
          int read = 0;
                  ByteBuffer buffer 
          = ByteBuffer.allocate(1024);

                  System.
          out.println("Client Start");

                  
          // 輪詢
                  while (!stop) {
                    
          // 獲取Selector返回的時(shí)間值
                    n = selector.select();

                    
          // 當(dāng)傳回的值大于0事,讀事件發(fā)生了
                    if (n > 0{
                      Set 
          set = selector.selectedKeys();
                      Iterator it 
          = set.iterator();

                      
          while (it.hasNext()) {
                        skey 
          = (SelectionKey) it.next();
                        it.remove();

                        
          if (skey.isReadable()) {
                          SocketChannel sc 
          = (SocketChannel) skey.channel();

                          
          while ( (read = sc.read(buffer)) != -1{
                            
          if (read == 0{
                              
          break;
                            }


                            buffer.flip();
                            
          byte[] array = new byte[read];
                            buffer.
          get(array);
                            String s 
          = new String(array);
                            System.
          out.print(s);
                            buffer.clear();

                            
          if (s.indexOf("new"!= -1{
                              stop 
          = true;
                              System.
          out.println();
                            }

                          }

                        }

                      }

                    }

                  }

                }

                
          catch (IOException ioe) {
                  ioe.printStackTrace();
                }


                
          try {
                  pool.returnObject(address, channel);
                }

                
          catch (Exception ex) {
                  ex.printStackTrace();
                }

              }


              System.
          out.println(name + ": Client Stop");
            }


            
          /**
             * 測(cè)試方法
             * @param args String[] 控制臺(tái)參數(shù)
             * @throws Exception
             
          */

            
          public static void main(String[] args) throws Exception {
              SocketPoolableObjectFactory factory 
          = new SocketPoolableObjectFactory();
              StackKeyedObjectPoolFactory poolFactory 
          = new StackKeyedObjectPoolFactory(factory);
              KeyedObjectPool pool 
          = poolFactory.createPool();

              
          // 創(chuàng)建連接清華BBS的線程
              Thread t1 = new Thread(new TestThread("清華", pool, new InetSocketAddress("bbs.tsinghua.edu.cn"23)));
              t1.start();
              
          // 創(chuàng)建連接華南理工BBS的線程
              Thread t2 = new Thread(new TestThread("華南理工", pool, new InetSocketAddress("bbs.gznet.edu.cn"23)));
              t2.start();
            }


          }



                參考資料:
                1. Jakarta Commons Pool網(wǎng)站:http://jakarta.apache.org/commons/pool/
                2. IBM開(kāi)發(fā)者的一篇很好的文章《使用Jakarta Commons Pool處理對(duì)象池化》
          posted on 2005-05-20 14:08 小米 閱讀(4095) 評(píng)論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 西峡县| 平凉市| SHOW| 辽中县| 永嘉县| 渑池县| 资源县| 千阳县| 离岛区| 九龙县| 武冈市| 涟水县| 淮南市| 曲周县| 天镇县| 炉霍县| 虎林市| 县级市| 拜泉县| 兴文县| 稷山县| 长沙县| 元阳县| 乌审旗| 合肥市| 贺州市| 湾仔区| 淳安县| 浦城县| 巫溪县| 金川县| 贡嘎县| 镇远县| 萨迦县| 桑植县| 新建县| 凉城县| 凤庆县| 武义县| 通河县| 昭通市|