tbwshc

          java 單例加鎖方法的討論

          java 單例加鎖方法:

          ScheduleEngine是個單例類,在獲得實例的方法getinstance中,兩次判斷其是否為空,有利于多線程的并發操作。

          使得實例化時,只在第一次加鎖,這樣效率會有提高。

           

          Java代碼 復制代碼 收藏代碼
          1. class ScheduleEngine{   
          2.        
          3.         private static Lock instanceLock=new ReentrantLock();   
          4.            
          5.         private ScheduleEngine() {   
          6.             setproperties;   
          7.         }   
          8.            
          9.         public static ScheduleEngine getInstance(int temphandlerType) {   
          10.             if(null==engine) {   
          11.                 instanceLock.lock();   
          12.                 try  
          13.                 {   
          14.                 if(null==engine)   
          15.                 {   
          16.                 handlerType=temphandlerType;   
          17.                 engine=new ScheduleEngine(temphandlerType);   
          18.                 }   
          19.            
          20.                 }   
          21.                 finally  
          22.                 {   
          23.                 instanceLock.unlock();   
          24.                 }   
          25.             }   
          26.             return engine;   
          27.             }    
          28.     }  

           

          初始實例化 單例c3p0對象的方法,常用的是

           

          Java代碼 復制代碼 收藏代碼
          1. public final class ConnectionManager {   
          2.   
          3.     private static ConnectionManager instance;   
          4.     private static ComboPooledDataSource cpds;   
          5.   
          6.     private static String c3p0Properties;   
          7.   
          8.     /**  
          9.      * 從數據庫連接池取連接  
          10.      * @throws Exception  
          11.      */  
          12.     private ConnectionManager() throws Exception {   
          13.         Properties p = new Properties();   
          14.         c3p0Properties = System.getProperty("user.dir") +   
          15.                 "/mom_project_config/database.properties";   
          16. //      p.load(this.getClass().getClassLoader().getResourceAsStream(c3p0Properties));   
          17.         p.load(new BufferedInputStream(new FileInputStream(c3p0Properties)));   
          18. //      String url = p.getProperty("url") + p.getProperty("database");   
          19.         String url = p.getProperty("url") + p.getProperty("database")+"?useUnicode=true&characterEncoding=UTF-8";   
          20.         cpds = new ComboPooledDataSource();   
          21.         cpds.setDriverClass(p.getProperty("driverclass"));   
          22.         cpds.setJdbcUrl(url);   
          23.         cpds.setUser(p.getProperty("user"));   
          24.         cpds.setPassword(p.getProperty("password"));   
          25.         // 當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 acquireIncrement   
          26.         cpds.setAcquireIncrement(Integer.valueOf(p   
          27.                 .getProperty("acquireincrement")));   
          28.         // 定義在從數據庫獲取新連接失敗后重復嘗試的次數。Default: 30 acquireRetryAttempts   
          29.         cpds.setAcquireRetryAttempts(Integer.valueOf(p   
          30.                 .getProperty("acquireretryattempts")));   
          31.         // 兩次連接中間隔時間,單位毫秒。Default: 1000 acquireRetryDelay   
          32.         cpds.setAcquireRetryDelay(Integer.valueOf(p   
          33.                 .getProperty("acquireretrydelay")));   
          34.         // 自動提交事務;連接關閉時默認將所有未提交的操作回滾。Default: false autoCommitOnClose   
          35.         cpds.setAutoCommitOnClose(Boolean.valueOf(p   
          36.                 .getProperty("autocommitonclose")));   
          37.         // 當連接池用完時客戶端調用getConnection()后等待獲取新連接的時間,超時后將拋出SQLException,   
          38.         // 如設為0則無限期等待.單位毫秒,默認為0   
          39.         cpds.setCheckoutTimeout(Integer.valueOf(p   
          40.                 .getProperty("checkouttimeout")));   
          41.         // 每多少秒檢查所有連接池中的空閑連接。默認為0表示不檢查。Default: 0 idleConnectionTestPeriod   
          42.         cpds.setIdleConnectionTestPeriod(Integer.valueOf(p   
          43.                 .getProperty("idleconnectiontestperiod")));   
          44.         // 最大空閑時間,25000秒內未使用則連接被丟棄。若為0則永不丟棄。Default: 0 maxIdleTime   
          45.         cpds.setMaxIdleTime(Integer.valueOf(p.getProperty("maxidletime")));   
          46.         // 初始化時獲取三個連接,取值應在minPoolSize與maxPoolSize之間。Default: 3 initialPoolSize   
          47.         cpds.setInitialPoolSize(Integer.valueOf(p   
          48.                 .getProperty("initialpoolsize")));   
          49.         // 連接池中保留的最小連接數。   
          50.         cpds.setMinPoolSize(Integer.valueOf(p.getProperty("minpoolsize")));   
          51.         // 連接池中保留的最大連接數。Default: 15 maxPoolSize   
          52.         cpds.setMaxPoolSize(Integer.valueOf(p.getProperty("maxpoolsize")));   
          53.         // JDBC的標準參數,用以控制數據源內加載的PreparedStatement數據.但由于預緩存的Statement屬于單個Connection而不是整個連接池.所以   
          54.         // 設置這個參數需要考濾到多方面的因素,如果maxStatements與maxStatementsPerConnection均為0,則緩存被關閉.默認為0;   
          55.         cpds.setMaxStatements(Integer.valueOf(p.getProperty("maxstatements")));   
          56.         // 連接池內單個連接所擁有的最大緩存被關閉.默認為0;   
          57.         cpds.setMaxStatementsPerConnection(Integer.valueOf(p   
          58.                 .getProperty("maxstatementsperconnection")));   
          59.         // C3P0是異步操作的,緩慢的JDBC操作通過幫助進程完成.擴展這些操作可以有效的提升性能,通過多數程實現多個操作同時被執行.默為為3   
          60.         cpds.setNumHelperThreads(Integer.valueOf(p   
          61.                 .getProperty("numhelperthreads")));   
          62.         // 用戶修改系統配置參數執行前最多等待的秒數.默認為300;   
          63.         cpds.setPropertyCycle(Integer.valueOf(p.getProperty("propertycycle")));   
          64.         // 如果設為true那么在取得連接的同時將校驗連接的有效性。Default: false testConnectionOnCheckin   
          65.         cpds.setTestConnectionOnCheckin(Boolean.valueOf(p   
          66.                 .getProperty("testconnectiononcheckin")));   
          67.         // 因性能消耗大請只在需要的時候使用它。   
          68.         // 如果設為true那么在每個connection提交的時候都將校驗其有效性。   
          69.         // 建議使用idleConnectionTestPeriod或automaticTestTable等方法來提升連接測試的性能。Default:   
          70.         // false testConnectionOnCheckout   
          71.         cpds.setTestConnectionOnCheckout(Boolean.valueOf(p   
          72.                 .getProperty("testconnectionOncheckout")));   
          73.         // 獲取連接失敗將會引起所有等待連接池來獲取連接的線程拋出異常。   
          74.         // 但是數據源仍有效保留,并在下次調用getConnection()的時候繼續嘗試獲取連接。   
          75.         // 如果設為true,那么在嘗試獲取連接失敗后該數據源將申明已斷開并永久關閉。Default: false   
          76.         // breakAfterAcquireFailure   
          77.         cpds.setBreakAfterAcquireFailure(Boolean.valueOf(p   
          78.                 .getProperty("breakafteracquirefailure")));   
          79.   
          80.     }   
          81.   
          82.     /**  
          83.      * 獲得ConnectionManager單例對象  
          84.      * @return  
          85.      */  
          86.     public synchronized static ConnectionManager getInstance() {   
          87.         if (instance == null) {   
          88.             try {   
          89.                 instance = new ConnectionManager();   
          90.             } catch (Exception e) {   
          91.                 e.printStackTrace();   
          92.             }   
          93.         }   
          94.         return instance;   
          95.     }   
          96.   
          97.     /**  
          98.      * 獲得連接  
          99.      * @return  
          100.      */  
          101.     public Connection getContection() {   
          102.         try {   
          103.             return cpds.getConnection();   
          104.         } catch (SQLException e) {   
          105.             e.printStackTrace();   
          106.         }   
          107.         return null;   
          108.     }  

           

          在初始化獲得單例的方法上面加鎖,不利于并發操作的執行,用第一段代碼兩次判斷是否為空的方式,可以減少代碼執行中鎖的引用。 不足之處煩請朋友們指正。。

          posted on 2012-08-03 17:28 chen11-1 閱讀(2340) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 长泰县| 皋兰县| 施甸县| 太仓市| 沙河市| 新巴尔虎左旗| 德庆县| 松原市| 昆山市| 海南省| 河东区| 平陆县| 霍州市| 武川县| 马鞍山市| 奉化市| 卫辉市| 丹东市| 杨浦区| 安国市| 两当县| 万安县| 襄樊市| 辉南县| 福海县| 治县。| 库伦旗| 武宣县| 东海县| 邻水| 香河县| 富民县| 专栏| 额济纳旗| 临泽县| 丹凤县| 辉南县| 永清县| 章丘市| 连城县| 凌海市|