測試高並發環境下五種單例模式的執行效率


一、高並發環境下五種單例模式的調用效率測試示例

 

package edu.aeon.test;
import java.util.concurrent.CountDownLatch;

import edu.aeon.model.singleton.HungrySingleton;
import edu.aeon.model.singleton.LazySingleton;
import edu.aeon.model.singleton.LazySingleton1;
import edu.aeon.model.singleton.SingletonDCL;
import edu.aeon.model.singleton.SingletonEnum;

/**
 * 測試多線程環境下五種創建單例模式的調用效率
 * 
 * @author aeon
 *
 */
public class Test {

    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();
        int threadNum = 100;
        final CountDownLatch countDownLatch = new CountDownLatch(threadNum);

        for (int i = 0; i < threadNum; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    for (int i = 0; i < 1000000; i++) {
                        /*//1.測試餓漢式
                        HungrySingleton hungrySingleton = HungrySingleton.getSinletonInstance();
                        //2.測試懶漢式
                        LazySingleton lazySingleton = LazySingleton.getLazySingletonInstance();
                        //3.測試雙重檢測鎖
                        SingletonDCL singletonDCL = SingletonDCL.getInstance();
                        //4.測試靜態內部類
                        LazySingleton1 lazySingleton1 = LazySingleton1.getLazySingletonInstance();
                        //5.測試枚舉
                        SingletonEnum singletonEnum = SingletonEnum.singletonEnumInstance;*/
                    }
                    countDownLatch.countDown();
                }
            }).start();
        }

        countDownLatch.await(); // main線程阻塞,直到計數器變為0,才會繼續往下執行!

        long end = System.currentTimeMillis();
        System.out.println("總耗時:" + (end - start));
    }
}

二、測試結果

單例模式 調用時間(毫秒)
餓漢式 15
懶漢式 897
雙重檢查鎖 16
靜態內部類 15
枚舉式 14

三、高並發情況下單例模式的選用標准
  3.1如果要產生的單例對象占用資源比較少,不需要延時加載,則:枚舉式好於餓漢式。
  3.2如果要產生的單例對象占用資源比較大,需要延時加載,則:靜態內部類好於懶漢式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM