美文网首页
用枚举强化singleton属性

用枚举强化singleton属性

作者: SetsunaHao | 来源:发表于2018-09-04 10:16 被阅读0次
    使用枚举实现单例的好处
    • 代码简洁易于阅读
    • 能有效防止序列化或者反射攻击

    1.创建一个连接池类(例如数据库连接池),这种功能的类,我们一般都希望它是一个单例的类

    public class ConnectionPool {
        public void getConnection(){
            System.out.println(this.hashCode() + ": get a connection");
        }
    }
    

    2.新建一个枚举类,用来管理连接池类

    public enum  PoolManager {
        INSTANCE;
        private ConnectionPool connectionPool = new ConnectionPool();
        public ConnectionPool getConnectionPool(){
            return this.connectionPool;
        }
    }
    

    3.测试单线程

    public class App {
        public static void main(String[] args) {
            PoolManager.INSTANCE.getConnectionPool().getConnection();
            PoolManager.INSTANCE.getConnectionPool().getConnection();
            PoolManager.INSTANCE.getConnectionPool().getConnection();
    
            new ConnectionPool().getConnection();
            new ConnectionPool().getConnection();
            new ConnectionPool().getConnection();
        }
    }
    
    result : 
        2061475679: get a connection
        2061475679: get a connection
        2061475679: get a connection
        
        140435067: get a connection
        1450495309: get a connection
        1670782018: get a connection
    
    • PoolManager管理的ConnectionPool的hashcode是一致的
    • new 出来的ConnectionPool hashcode不一致,并不是同一个对象

    4.测试多线程环境

      public static void main(String[] args) {
           for (int i = 0; i < 10000; i++){
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                       PoolManager.INSTANCE.getConnectionPool().getConnection();
                   }
               }).start();
           }
        }
        
    resut :
        1184554318: get a connection
        1184554318: get a connection
        1184554318: get a connection
        1184554318: get a connection
        1184554318: get a connection
        ....
        ....
    
    • 多线程环境下ConnectionPool hashcode也是一致的

    相关文章

      网友评论

          本文标题:用枚举强化singleton属性

          本文链接:https://www.haomeiwen.com/subject/coziwftx.html