高频面试题-单例模式

package com.iamitman.first;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.*;

/**
 * 饿汉式:不论是否被使用,加载该类时都会被初始化
 */
public class B_Singleton {

    public static final B_Singleton INSTANCE = new B_Singleton();

    private B_Singleton() {

    }
}

/**
 * 枚举单例(与饿汉式一样)
 */
enum EnumSingleton {
    INSTANCE
}

/**
 * 静态代码块(饿汉式)
 * 与第一种不同之处是如果想在创建时先从外部初始化一些数据,比如从配置文件获取数据,这种方式可以实现。
 */
class StaticSingleton {
    public static final StaticSingleton INSTANCE;
    private String info;

    static {
        try {
            Properties properties = new Properties();
            properties.load(StaticSingleton.class.getClassLoader().getResourceAsStream(""));
            INSTANCE = new StaticSingleton(properties.getProperty(""));
        } catch (IOException e) {
            throw new RuntimeException();
        }

    }

    private StaticSingleton(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

/**
 * 懒汉式
 * 线程不安全,需要加锁
 */
class LazySingleton {

    private static LazySingleton instance;

    private LazySingleton() {

    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new LazySingleton();
        }
        return instance;
    }

    /**
     * 线程安全
     *
     * @return
     */
    public static LazySingleton getInstanceSafe() {
        synchronized (LazySingleton.class) {
            if (instance == null) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instance = new LazySingleton();
            }
        }
        return instance;
    }

    /**
     * 线程安全 + 性能好(已经初始化的情况下不再等待锁)
     *
     * @return
     */
    public static LazySingleton getInstanceSafeAndFast() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        Callable<LazySingleton> callable = new Callable<LazySingleton>() {

            public LazySingleton call() throws Exception {
                return LazySingleton.getInstance();
            }
        };

        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<LazySingleton> future1 = service.submit(callable);
        Future<LazySingleton> future2 = service.submit(callable);

        LazySingleton lazySingleton1 = null;
        try {
            lazySingleton1 = future1.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        LazySingleton lazySingleton2 = null;
        try {
            lazySingleton2 = future2.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println(lazySingleton1 == lazySingleton2);

        service.shutdown();
    }
}

/**
 * 懒汉式 线程安全的(静态内部类)
 * 只有在加载内部类的时候才会初始化实例
 */
class InnerSingleton {
    private InnerSingleton() {

    }

    private static class Inner {
        private static final InnerSingleton INSTANCE = new InnerSingleton();
    }

    public static InnerSingleton getInstance() {
        return Inner.INSTANCE;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值