餓漢
public class Hungry{
private Hungry(){}
private static final Hungry hungry = new Hungry();
public static Hungry getInstance(){
return hungry;
}
}
缺點:占用空間,被呼叫之前都仍占用記憶體
懶漢
public class Lazy {
private Lazy(){
//呼叫下執行緒名,看哪幾個執行緒獲得了物件
System.out.println(Thread.currentThread().getName());
};
private static Lazy lazy = null;
public static Lazy getInstance(){
if(lazy==null){
lazy = new Lazy();
}
return lazy;
}
//用十條多執行緒測驗下
public static void main(String[] args) {
for(int i = 0;i<10;i++){
new Thread(()->{
Lazy.getInstance();
}).start();
}
}
}
結果顯示在多執行緒情況下不安全
雙重驗證懶漢式—DCL
public class Lazy {
private Lazy(){
System.out.println(Thread.currentThread().getName());
};
//添加volatile關鍵字阻止指令重排
private volatile static Lazy lazy = null;
public static Lazy getInstance() {
if (lazy == null) {
synchronized (Lazy.class) {
if (lazy == null) {
lazy = new Lazy();
}
}
}
return lazy;
}
public static void main(String[] args) {
for(int i = 0;i<10;i++){
new Thread(()->{
Lazy.getInstance();
//執行順序:
//1分配記憶體空間
//2初始化物件
//3將物件指向記憶體空間
//因為此操作不是原子性操作,可能發生指令重排,造成空指標例外
}).start();
}
}
}
//但仍可通過反射機制破解,可以升級為多重驗證,如下
public class Lazy {
private static boolean one = false;//加強一下,三重驗證
private Lazy() {
//此處也可以加個鎖
if(!one){
one=true;
}else {
//拋個例外終止反射
throw new RuntimeException("再搞破壞把你抓起來!");
}
}
private volatile static Lazy lazy = null;
public static Lazy getInstance() {
if (lazy == null) {
synchronized (Lazy.class) {
if (lazy == null) {
lazy = new Lazy();
}
}
}
return lazy;
}
public static void main(String[] args) throws Exception {
Constructor<Lazy> declaredConstructor = Lazy.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
//通過反射創建物件
Lazy lazy1 = declaredConstructor.newInstance();
Lazy lazy2 = declaredConstructor.newInstance();
//輸出兩個物件的hashcode--不一致,說明單例被破壞
System.out.println(lazy1.hashCode());
System.out.println(lazy2.hashCode());
//多重驗證后會報例外--再搞破壞把你抓起來!
}
}
靜態內部類單例
靜態內部類只有類中屬性被呼叫時才開始加載,可以節省資源
public class InnerSingle{
private InnerSingle(){}
private static class Inner{
private static final InnerSingle innerSingle = new InnerSingle();
}
public static InnerSingle getInstance(){
return Inner.innerSingle;
}
}
靜態內部類單例執行緒安全,并且是懶加載,但仍可被反射破解,那我們進反射原始碼看看情況
public T newInstance(Object ... initargs)
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, null, modifiers);
}
}
if ((clazz.getModifiers() & Modifier.ENUM) != 0)
//不可通過反射創建列舉類
throw new IllegalArgumentException("Cannot reflectively create enum objects");
ConstructorAccessor ca = constructorAccessor; // read volatile
if (ca == null) {
ca = acquireConstructorAccessor();
}
@SuppressWarnings("unchecked")
T inst = (T) ca.newInstance(initargs);
return inst;
}
根據反射原始碼得知,列舉類不可被破壞
列舉單例
public enum EnumSingleton {
INSTANCE;
public void method() {
System.out.println("這是一個列舉方法");
}
}
//呼叫方式
public class Main {
public static void main(String[] args) {
EnumSingleton.INSTANCE.method();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/141996.html
標籤:其他
上一篇:Hutool的發送郵件,簡單明了
