tbwshc

          java 單例加鎖方法的討論

          java 單例加鎖方法:

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

          使得實(shí)例化時(shí),只在第一次加鎖,這樣效率會(huì)有提高。

           

          Java代碼 復(fù)制代碼 收藏代碼
          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.     }  

           

          初始實(shí)例化 單例c3p0對(duì)象的方法,常用的是

           

          Java代碼 復(fù)制代碼 收藏代碼
          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.      * 從數(shù)據(jù)庫(kù)連接池取連接  
          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.         // 當(dāng)連接池中的連接耗盡的時(shí)候c3p0一次同時(shí)獲取的連接數(shù)。Default: 3 acquireIncrement   
          26.         cpds.setAcquireIncrement(Integer.valueOf(p   
          27.                 .getProperty("acquireincrement")));   
          28.         // 定義在從數(shù)據(jù)庫(kù)獲取新連接失敗后重復(fù)嘗試的次數(shù)。Default: 30 acquireRetryAttempts   
          29.         cpds.setAcquireRetryAttempts(Integer.valueOf(p   
          30.                 .getProperty("acquireretryattempts")));   
          31.         // 兩次連接中間隔時(shí)間,單位毫秒。Default: 1000 acquireRetryDelay   
          32.         cpds.setAcquireRetryDelay(Integer.valueOf(p   
          33.                 .getProperty("acquireretrydelay")));   
          34.         // 自動(dòng)提交事務(wù);連接關(guān)閉時(shí)默認(rèn)將所有未提交的操作回滾。Default: false autoCommitOnClose   
          35.         cpds.setAutoCommitOnClose(Boolean.valueOf(p   
          36.                 .getProperty("autocommitonclose")));   
          37.         // 當(dāng)連接池用完時(shí)客戶端調(diào)用getConnection()后等待獲取新連接的時(shí)間,超時(shí)后將拋出SQLException,   
          38.         // 如設(shè)為0則無(wú)限期等待.單位毫秒,默認(rèn)為0   
          39.         cpds.setCheckoutTimeout(Integer.valueOf(p   
          40.                 .getProperty("checkouttimeout")));   
          41.         // 每多少秒檢查所有連接池中的空閑連接。默認(rèn)為0表示不檢查。Default: 0 idleConnectionTestPeriod   
          42.         cpds.setIdleConnectionTestPeriod(Integer.valueOf(p   
          43.                 .getProperty("idleconnectiontestperiod")));   
          44.         // 最大空閑時(shí)間,25000秒內(nèi)未使用則連接被丟棄。若為0則永不丟棄。Default: 0 maxIdleTime   
          45.         cpds.setMaxIdleTime(Integer.valueOf(p.getProperty("maxidletime")));   
          46.         // 初始化時(shí)獲取三個(gè)連接,取值應(yīng)在minPoolSize與maxPoolSize之間。Default: 3 initialPoolSize   
          47.         cpds.setInitialPoolSize(Integer.valueOf(p   
          48.                 .getProperty("initialpoolsize")));   
          49.         // 連接池中保留的最小連接數(shù)。   
          50.         cpds.setMinPoolSize(Integer.valueOf(p.getProperty("minpoolsize")));   
          51.         // 連接池中保留的最大連接數(shù)。Default: 15 maxPoolSize   
          52.         cpds.setMaxPoolSize(Integer.valueOf(p.getProperty("maxpoolsize")));   
          53.         // JDBC的標(biāo)準(zhǔn)參數(shù),用以控制數(shù)據(jù)源內(nèi)加載的PreparedStatement數(shù)據(jù).但由于預(yù)緩存的Statement屬于單個(gè)Connection而不是整個(gè)連接池.所以   
          54.         // 設(shè)置這個(gè)參數(shù)需要考濾到多方面的因素,如果maxStatements與maxStatementsPerConnection均為0,則緩存被關(guān)閉.默認(rèn)為0;   
          55.         cpds.setMaxStatements(Integer.valueOf(p.getProperty("maxstatements")));   
          56.         // 連接池內(nèi)單個(gè)連接所擁有的最大緩存被關(guān)閉.默認(rèn)為0;   
          57.         cpds.setMaxStatementsPerConnection(Integer.valueOf(p   
          58.                 .getProperty("maxstatementsperconnection")));   
          59.         // C3P0是異步操作的,緩慢的JDBC操作通過(guò)幫助進(jìn)程完成.擴(kuò)展這些操作可以有效的提升性能,通過(guò)多數(shù)程實(shí)現(xiàn)多個(gè)操作同時(shí)被執(zhí)行.默為為3   
          60.         cpds.setNumHelperThreads(Integer.valueOf(p   
          61.                 .getProperty("numhelperthreads")));   
          62.         // 用戶修改系統(tǒng)配置參數(shù)執(zhí)行前最多等待的秒數(shù).默認(rèn)為300;   
          63.         cpds.setPropertyCycle(Integer.valueOf(p.getProperty("propertycycle")));   
          64.         // 如果設(shè)為true那么在取得連接的同時(shí)將校驗(yàn)連接的有效性。Default: false testConnectionOnCheckin   
          65.         cpds.setTestConnectionOnCheckin(Boolean.valueOf(p   
          66.                 .getProperty("testconnectiononcheckin")));   
          67.         // 因性能消耗大請(qǐng)只在需要的時(shí)候使用它。   
          68.         // 如果設(shè)為true那么在每個(gè)connection提交的時(shí)候都將校驗(yàn)其有效性。   
          69.         // 建議使用idleConnectionTestPeriod或automaticTestTable等方法來(lái)提升連接測(cè)試的性能。Default:   
          70.         // false testConnectionOnCheckout   
          71.         cpds.setTestConnectionOnCheckout(Boolean.valueOf(p   
          72.                 .getProperty("testconnectionOncheckout")));   
          73.         // 獲取連接失敗將會(huì)引起所有等待連接池來(lái)獲取連接的線程拋出異常。   
          74.         // 但是數(shù)據(jù)源仍有效保留,并在下次調(diào)用getConnection()的時(shí)候繼續(xù)嘗試獲取連接。   
          75.         // 如果設(shè)為true,那么在嘗試獲取連接失敗后該數(shù)據(jù)源將申明已斷開(kāi)并永久關(guān)閉。Default: false   
          76.         // breakAfterAcquireFailure   
          77.         cpds.setBreakAfterAcquireFailure(Boolean.valueOf(p   
          78.                 .getProperty("breakafteracquirefailure")));   
          79.   
          80.     }   
          81.   
          82.     /**  
          83.      * 獲得ConnectionManager單例對(duì)象  
          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.     }  

           

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

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


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 沽源县| 颍上县| 紫云| 大名县| 揭东县| 台州市| 同仁县| 竹溪县| 南木林县| 嵊州市| 韶关市| 隆德县| 石家庄市| 克东县| 朝阳区| 呼和浩特市| 察哈| 临沧市| 景洪市| 阳江市| 嘉禾县| 内乡县| 会理县| 利津县| 津南区| 临桂县| 抚顺市| 佛坪县| 丰城市| 韩城市| 蚌埠市| 长顺县| 额尔古纳市| 辽宁省| 横山县| 乌兰浩特市| 满洲里市| 黔西| 开化县| 呼伦贝尔市| 内乡县|