单例模式


最简单的单例

package org.me.javaapp.singleton;
import org.me.javaapp.util.DateUtil;
public class Singleton {
    private Singleton() {
        try {
            System.out.println("Singleton is 初始化开始>>>"+DateUtil.getNowTimeString());
            Thread.sleep(1000 * 2);
        } catch (Exception ex) {
            System.out.println("Error" + ex.toString());
        }
        System.out.println("Singleton is 初始化完成>>>"+DateUtil.getNowTimeString());
    }
    private static Singleton instance = new Singleton();
    public static Singleton getInstance() {
        return instance;
    }
    public static void createString() {
        System.out.println("createString in Singleton 无延迟加载");
    }
}


加入延迟加载机制,但是性能不好

package org.me.javaapp.singleton;
import org.me.javaapp.util.DateUtil;

public class LazySingleton {
    private LazySingleton() {
        try {
            System.out.println("Singleton is 初始化开始>>>"+DateUtil.getNowTimeString());
            Thread.sleep(1000 * 2);
        } catch (Exception ex) {
            System.out.println("Error" + ex.toString());
        }
        System.out.println("Singleton is 初始化完成>>>"+DateUtil.getNowTimeString());
    }
    private static LazySingleton instance = null;
    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

内部类实现

package org.me.javaapp.singleton;
import org.me.javaapp.util.DateUtil;
public class StaticSingleton {
    private StaticSingleton() {
        try {
            System.out.println("Singleton is 初始化开始>>>"+DateUtil.getNowTimeString());
            Thread.sleep(1000 * 2);
        } catch (Exception ex) {
            System.out.println("Error" + ex.toString());
        }
        System.out.println("Singleton is 初始化完成>>>"+DateUtil.getNowTimeString());
    }
    private static class SingletonHolder {
        private static StaticSingleton instance = new StaticSingleton();
    }
    public static StaticSingleton getInstance() {
        return SingletonHolder.instance;
    }
    public static void createString() {
        System.out.println("createString in StaticSingleton内部类实现延迟加载");
    }
}


测试用例

package org.me.test;
import org.me.javaapp.singleton.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import junit.framework.Assert;
import org.junit.Test;

public class TestSingleton {

    //@Test
    public void test() {
        Singleton s = Singleton.getInstance();
        Singleton s1 = null;
        Class singletonClass = Singleton.class;
        Constructor cons;
        try {
            cons = singletonClass.getDeclaredConstructor(null);
            cons.setAccessible(true);
            s1 = (Singleton) cons.newInstance(null);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        Assert.assertNotSame(s, s1);
    }

    public static class AccessSingletonThread extends Thread {

        long begintime;

        public AccessSingletonThread(long begintime) {
            this.begintime = begintime;
        }

        @Override
        public void run() {
            System.out.println("try to get instance");
            for (int i = 0; i < 100000; i++) //Singleton.getInstance();
            {
                LazySingleton.getInstance();
            }
            System.out.println("spend:" + (System.currentTimeMillis() - begintime));
        }
    }

    //@Test
    public void testPerformance() throws InterruptedException {
        ExecutorService exe = Executors.newFixedThreadPool(5);
        long begintime = System.currentTimeMillis();
        exe.submit(new AccessSingletonThread(begintime));
        exe.submit(new AccessSingletonThread(begintime));
        exe.submit(new AccessSingletonThread(begintime));
        exe.submit(new AccessSingletonThread(begintime));
        exe.submit(new AccessSingletonThread(begintime));

        Thread.sleep(10000);
    }
    
    @Test
    public void testSingleton() {
        Singleton.createString();
        Singleton.getInstance();
        Singleton.createString();
        System.out.println("------------------------------------------------------------------------");
        StaticSingleton.createString();
        StaticSingleton.getInstance();
        StaticSingleton.createString();
    }
}

输出:

单例模式_第1张图片


参考:《Java程序性能优化——让你的Java程序更快、更稳定》

你可能感兴趣的:(单例模式)