以下属于单例模式的优点的是_三、单例模式详解
4.單例模式詳解
4.1.課程目標(biāo)
1、掌握單例模式的應(yīng)用場(chǎng)景。
2、掌握IDEA環(huán)境下的多線程調(diào)試方式。
3、掌握保證線程安全的單例模式策略。
4、掌握反射暴力攻擊單例解決方案及原理分析。
5、序列化破壞單例的原理及解決方案。
6、掌握常見的單例模式寫法。
4.2.內(nèi)容定位
1、聽說(shuō)過(guò)單例模式,但不知道如何應(yīng)用的人群。
2、單例模式是非常經(jīng)典的高頻面試題,希望通過(guò)面試單例彰顯技術(shù)深度,順利拿到Offer的人群。
4.3.單例模式的應(yīng)用場(chǎng)景
單例模式(SingletonPattern)是指確保一個(gè)類在任何情況下都絕對(duì)只有一個(gè)實(shí)例,并提供一個(gè)全局訪問(wèn)點(diǎn)。單例模式是創(chuàng)建型模式。單例模式在現(xiàn)實(shí)生活中應(yīng)用也非常廣泛,例如,公司CEO、部門經(jīng) 理 等 。 J2EE 標(biāo) 準(zhǔn) 中 的 ServletContext 、 ServletContextConfig 等 、 Spring 框 架 應(yīng) 用 中 的 ApplicationContext、數(shù)據(jù)庫(kù)的連接池BDPool等也都是單例形式。
4.4.餓漢式單例模式
方法1.靜態(tài)方法獲得私有成員對(duì)象
?/**? * 優(yōu)點(diǎn):執(zhí)行效率高,性能高,沒(méi)有任何的鎖? * 缺點(diǎn):某些情況下,可能會(huì)造成內(nèi)存浪費(fèi)? */?public class HungrySingleton {? ? ?//先靜態(tài)、后動(dòng)態(tài) ? ? ?//先屬性、后方法 ? ? ?//先上后下? ? ?private static final HungrySingleton hungrySingleton = new HungrySingleton();??? ? ?private HungrySingleton(){}??? ? ?public static HungrySingleton getInstance(){? ? ? ? ?return ?hungrySingleton;? ? }?}方法2.利用靜態(tài)代碼塊與類同時(shí)加載的特性生成單例對(duì)象
?//餓漢式靜態(tài)塊單例模式?public class HungryStaticSingleton {? ? ?//先靜態(tài)后動(dòng)態(tài)? ? ?//先上,后下? ? ?//先屬性后方法? ? ?private static final HungryStaticSingleton hungrySingleton;??? ? ?//裝個(gè)B? ? ?static {? ? ? ? ?hungrySingleton = new HungryStaticSingleton();? ? }??? ? ?private HungryStaticSingleton(){}??? ? ?public static HungryStaticSingleton getInstance(){? ? ? ? ?return ?hungrySingleton;? ? }?}類結(jié)構(gòu)圖
優(yōu)缺點(diǎn)
優(yōu)點(diǎn):沒(méi)有加任何鎖、執(zhí)行效率比較高,用戶體驗(yàn)比懶漢式單例模式更好。
缺點(diǎn):類加載的時(shí)候就初始化,不管用與不用都占著空間,浪費(fèi)了內(nèi)存,有可能“占著茅坑不拉屎”。
源碼
Spring中IoC容器ApplicationContext本身就是典型的餓漢式單例模式
4.5.懶漢式單例模式
特點(diǎn)
懶漢式單例模式的特點(diǎn)是:被外部類調(diào)用的時(shí)候內(nèi)部類才會(huì)加載。
方法1.加大鎖
?/**? * 優(yōu)點(diǎn):節(jié)省了內(nèi)存,線程安全? * 缺點(diǎn):性能低? */?//懶漢式單例模式在外部需要使用的時(shí)候才進(jìn)行實(shí)例化?public class LazySimpleSingletion {? ? ?private static LazySimpleSingletion instance;? ? ?//靜態(tài)塊,公共內(nèi)存區(qū)域 ? ? ?private LazySimpleSingletion(){}??? ? ?public synchronized static LazySimpleSingletion getInstance(){? ? ? ? ?if(instance == null){? ? ? ? ? ? ?instance = new LazySimpleSingletion();? ? ? ? }? ? ? ? ?return instance;? ? }?}???public class ExectorThread implements Runnable {? ? ?public void run() {? ? ? ? ?LazySimpleSingletion instance = LazySimpleSingletion.getInstance();? ? ? ? ?System.out.println(Thread.currentThread().getName() + ":" + instance);? ? }?}???public class LazySimpleSingletonTest {? ? ?public static void main(String[] args) {? ? ? ? ?Thread t1 = new Thread(new ExectorThread());? ? ? ? ?Thread t2 = new Thread(new ExectorThread());? ? ? ? ?t1.start();? ? ? ? ?t2.start();? ? ? ? ?System.out.println("End");? ? }?}給getInstance()加上synchronized關(guān)鍵字,使這個(gè)方法變成線程同步方法:
當(dāng)執(zhí)行其中一個(gè)線程并調(diào)用getInstance()方法時(shí),另一個(gè)線程在調(diào)用getInstance() 方法,線程的狀態(tài)由 RUNNING 變成了 MONITOR,出現(xiàn)阻塞。直到第一個(gè)線程執(zhí)行完,第二個(gè)線程 才恢復(fù)到RUNNING狀態(tài)繼續(xù)調(diào)用getInstance()方法
線程切換調(diào)試
上圖完美地展現(xiàn)了 synchronized 監(jiān)視鎖的運(yùn)行狀態(tài),線程安全的問(wèn)題解決了。但是,用 synchronized加鎖時(shí),在線程數(shù)量比較多的情況下,如果CPU分配壓力上升,則會(huì)導(dǎo)致大批線程阻塞, 從而導(dǎo)致程序性能大幅下降。那么,有沒(méi)有一種更好的方式,既能兼顧線程安全又能提升程序性能呢? 答案是肯定的。我們來(lái)看雙重檢查鎖的單例模式:
方法2.雙重檢查鎖
?/**? * 優(yōu)點(diǎn):性能高了,線程安全了? * 缺點(diǎn):可讀性難度加大,不夠優(yōu)雅? */?public class LazyDoubleCheckSingleton {? ? ?// volatile解決指令重排序? ? ?private volatile static LazyDoubleCheckSingleton instance;??? ? ?private LazyDoubleCheckSingleton() {? ? }??? ? ?public static LazyDoubleCheckSingleton getInstance() {? ? ? ? ?//檢查是否要阻塞,第一個(gè)instance == null是為了創(chuàng)建后不再走synchronized代碼,提高效率。可以理解是個(gè)開關(guān)。創(chuàng)建后這個(gè)開關(guān)就關(guān)上,后面的代碼就不用執(zhí)行了。? ? ? ? ?if (instance == null) {? ? ? ? ? ? ?synchronized (LazyDoubleCheckSingleton.class) {? ? ? ? ? ? ? ? ?//檢查是否要重新創(chuàng)建實(shí)例? ? ? ? ? ? ? ? ?if (instance == null) {? ? ? ? ? ? ? ? ? ? ?instance = new LazyDoubleCheckSingleton();? ? ? ? ? ? ? ? ? ? ?//指令重排序的問(wèn)題? ? ? ? ? ? ? ? ? ? ?//1.分配內(nèi)存給這個(gè)對(duì)象 ? ? ? ? ? ? ? ? ? ? ?//2.初始化對(duì)象? ? ? ? ? ? ? ? ? ? ?//3.設(shè)置 lazy 指向剛分配的內(nèi)存地址? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? }? ? ? ? ?return instance;? ? }?}???public class ExectorThread implements Runnable {? ? ?public void run() {? ? ? ? ?LazyDoubleCheckSingleton instance = LazyDoubleCheckSingleton.getInstance();? ? ? ? ?System.out.println(Thread.currentThread().getName() + ":" + instance);? ? }?}???public class LazySimpleSingletonTest {? ? ?public static void main(String[] args) {? ? ? ? ?Thread t1 = new Thread(new ExectorThread());? ? ? ? ?Thread t2 = new Thread(new ExectorThread());? ? ? ? ?t1.start();? ? ? ? ?t2.start();? ? ? ? ?System.out.println("End");? ? }?}當(dāng)?shù)谝粋€(gè)線程調(diào)用 getInstance()方法時(shí),第二個(gè)線程也可以調(diào)用。當(dāng)?shù)谝粋€(gè)線程執(zhí)行到 synchronized時(shí)會(huì)上鎖,第二個(gè)線程就會(huì)變成 MONITOR狀態(tài),出現(xiàn)阻塞。此時(shí),阻塞并不是基于整 個(gè)LazySimpleSingleton類的阻塞,而是在getInstance()方法內(nèi)部的阻塞,只要邏輯不太復(fù)雜,對(duì)于 調(diào)用者而言感知不到。
但是,用到 synchronized 關(guān)鍵字總歸要上鎖,對(duì)程序性能還是存在一定影響的。難道就真的沒(méi)有更好的方案嗎?當(dāng)然有。我們可以從類初始化的角度來(lái)考慮,看下面的代碼,采用靜態(tài)內(nèi)部類的方式:
方法3.靜態(tài)內(nèi)部類
?/*? ?ClassPath : LazyStaticInnerClassSingleton.class? ? ? ? ? ? ? ?LazyStaticInnerClassSingleton$LazyHolder.class? ? 優(yōu)點(diǎn):寫法優(yōu)雅,利用了Java本身語(yǔ)法特點(diǎn),性能高,避免了內(nèi)存浪費(fèi),不能被反射破壞? ? 缺點(diǎn):不優(yōu)雅? */?//這種形式兼顧餓漢式單例模式的內(nèi)存浪費(fèi)問(wèn)題和 synchronized 的性能問(wèn)題 ?//完美地屏蔽了這兩個(gè)缺點(diǎn)?//自認(rèn)為史上最牛的單例模式的實(shí)現(xiàn)方式 ?public class LazyStaticInnerClassSingleton {??? ? ?//使用 LazyInnerClassGeneral 的時(shí)候,默認(rèn)會(huì)先初始化內(nèi)部類 ? ? ?//如果沒(méi)使用,則內(nèi)部類是不加載的? ? ?private LazyStaticInnerClassSingleton(){? ? ? ? ?// if(LazyHolder.INSTANCE != null){? ? ? ? ?// ? ? throw new RuntimeException("不允許非法創(chuàng)建多個(gè)實(shí)例");? ? ? ? ?// }? ? }??? ? ?//每一個(gè)關(guān)鍵字都不是多余的,static 是為了使單例的空間共享,保證這個(gè)方法不會(huì)被重寫、重載 ? ? ?private static LazyStaticInnerClassSingleton getInstance(){? ? ? ? ?//在返回結(jié)果以前,一定會(huì)先加載內(nèi)部類 ? ? ? ? ?return LazyHolder.INSTANCE;? ? }??? ? ?//默認(rèn)不加載 ? ? ?private static class LazyHolder{? ? ? ? ?private static final LazyStaticInnerClassSingleton INSTANCE = new LazyStaticInnerClassSingleton();? ? }?}這種方式兼顧了餓漢式單例模式的內(nèi)存浪費(fèi)問(wèn)題和 synchronized 的性能問(wèn)題。內(nèi)部類一定是要在方法調(diào)用之前初始化,巧妙地避免了線程安全問(wèn)題。由于這種方式比較簡(jiǎn)單,我們就不帶大家一步一步 調(diào)試了。
內(nèi)部類語(yǔ)法特性 : 內(nèi)部類用時(shí)才加載
4.6.反射破壞單例
?public class ReflectTest {??? ? ?public static void main(String[] args) {? ? ? ? ?try {? ? ? ? ? ? ?//在很無(wú)聊的情況下,進(jìn)行破壞 ? ? ? ? ? ? ?Class> clazz = LazyStaticInnerClassSingleton.class;? ? ? ? ? ? ?//通過(guò)反射獲取私有的構(gòu)造方法? ? ? ? ? ? ?Constructor c = clazz.getDeclaredConstructor(null);? ? ? ? ? ? ?//強(qiáng)制訪問(wèn) ? ? ? ? ? ? ?c.setAccessible(true);? ? ? ? ? ? ?//暴力初始化? ? ? ? ? ? ?Object instance1 = c.newInstance();? ? ? ? ? ? ?//調(diào)用了兩次構(gòu)造方法,相當(dāng)于“new”了兩次,犯了原則性錯(cuò)誤 ? ? ? ? ? ? ?Object instance2 = c.newInstance();? ? ? ? ? ? ?System.out.println(instance1);? ? ? ? ? ? ?System.out.println(instance2);? ? ? ? ? ? ?System.out.println(instance1 == instance2);? // Enum? ? ? ? }catch (Exception e){? ? ? ? ? ? ?e.printStackTrace();? ? ? ? }? ? }?}???com.gupaoedu.vip.pattern.singleton.lazy.LazyStaticInnerClassSingleton@64cee07?com.gupaoedu.vip.pattern.singleton.lazy.LazyStaticInnerClassSingleton@1761e840?false大家有沒(méi)有發(fā)現(xiàn),上面介紹的單例模式的構(gòu)造方法除了加上 private 關(guān)鍵字,沒(méi)有做任何處理。如 果我們使用反射來(lái)調(diào)用其構(gòu)造方法,再調(diào)用 getInstance()方法,應(yīng)該有兩個(gè)不同的實(shí)例。現(xiàn)在來(lái)看一 段測(cè)試代碼,以LazyInnerClassSingleton為例:
顯然,創(chuàng)建了兩個(gè)不同的實(shí)例。現(xiàn)在,我們?cè)谄錁?gòu)造方法中做一些限制,一旦出現(xiàn)多次重復(fù)創(chuàng)建, 則直接拋出異常。所以需要在私有構(gòu)造方法添加異常:
? ? ?private LazyStaticInnerClassSingleton(){? ? ? ? ?if(LazyHolder.INSTANCE != null){? ? ? ? ? ? ?throw new RuntimeException("不允許非法創(chuàng)建多個(gè)實(shí)例");? ? ? ? }? ? }4.7.序列化破壞單例(擴(kuò)展知識(shí))
一個(gè)單例對(duì)象創(chuàng)建好后,有時(shí)候需要將對(duì)象序列化然后寫入磁盤,下次使用時(shí)再?gòu)拇疟P中讀取對(duì)象 并進(jìn)行反序列化,將其轉(zhuǎn)化為內(nèi)存對(duì)象。反序列化后的對(duì)象會(huì)重新分配內(nèi)存,即重新創(chuàng)建。如果序列化 的目標(biāo)對(duì)象為單例對(duì)象,就違背了單例模式的初衷,相當(dāng)于破壞了單例,來(lái)看一段代碼:
?//反序列化導(dǎo)致破壞單例模式 ?public class SeriableSingleton implements Serializable {? ? ?//序列化? ? ?//把內(nèi)存中對(duì)象的狀態(tài)轉(zhuǎn)換為字節(jié)碼的形式? ? ?//把字節(jié)碼通過(guò)IO輸出流,寫到磁盤上? ? ?//永久保存下來(lái),持久化? ? ?? ? ?//反序列化? ? ?//將持久化的字節(jié)碼內(nèi)容,通過(guò)IO輸入流讀到內(nèi)存中來(lái)? ? ?//轉(zhuǎn)化成一個(gè)Java對(duì)象? ? ?? ? ?// 餓漢式? ? ?public ?final static SeriableSingleton INSTANCE = new SeriableSingleton();? ? ?private SeriableSingleton(){}? ? ?public static SeriableSingleton getInstance(){? ? ? ? ?return INSTANCE;? ? }? ? ?// private Object readResolve(){ return INSTANCE;}?}???public class SeriableSingletonTest {? ? ?public static void main(String[] args) {? ? ? ? ?SeriableSingleton s1 = null;? ? ? ? ?SeriableSingleton s2 = SeriableSingleton.getInstance();? ? ? ? ?FileOutputStream fos = null;? ? ? ? ?try {? ? ? ? ? ? ?fos = new FileOutputStream("SeriableSingleton.obj");? ? ? ? ? ? ?ObjectOutputStream oos = new ObjectOutputStream(fos);? ? ? ? ? ? ?oos.writeObject(s2);? ? ? ? ? ? ?oos.flush();? ? ? ? ? ? ?oos.close();? ? ? ? ? ? ?FileInputStream fis = new FileInputStream("SeriableSingleton.obj");? ? ? ? ? ? ?ObjectInputStream ois = new ObjectInputStream(fis);? ? ? ? ? ? ?s1 = (SeriableSingleton)ois.readObject();? ? ? ? ? ? ?ois.close();? ? ? ? ? ? ?System.out.println(s1);? ? ? ? ? ? ?System.out.println(s2);? ? ? ? ? ? ?System.out.println(s1 == s2);? ? ? ? } catch (Exception e) {? ? ? ? ? ? ?e.printStackTrace();? ? ? ? }? ? }?}???打印結(jié)果:?com.gupaoedu.vip.pattern.singleton.seriable.SeriableSingleton@68837a77?com.gupaoedu.vip.pattern.singleton.seriable.SeriableSingleton@4b6995df?false從運(yùn)行結(jié)果可以看出,反序列化后的對(duì)象和手動(dòng)創(chuàng)建的對(duì)象是不一致的,實(shí)例化了兩次,違背了單 例模式的設(shè)計(jì)初衷。那么,我們?nèi)绾伪WC在序列化的情況下也能夠?qū)崿F(xiàn)單例模式呢?其實(shí)很簡(jiǎn)單,只需 要增加readResolve()方法即可。
再看運(yùn)行結(jié)果,如下圖所示。
?com.gupaoedu.vip.pattern.singleton.seriable.SeriableSingleton@4b6995df?com.gupaoedu.vip.pattern.singleton.seriable.SeriableSingleton@4b6995df?true大家一定會(huì)想:這是什么原因呢?為什么要這樣寫?看上去很神奇的樣子,也讓人有些費(fèi)解。不如 我們一起來(lái)看看JDK的源碼實(shí)現(xiàn)以了解清楚。我們進(jìn)入ObjectInputStream類的readObject()方法, 代碼如下:
?public final Object readObject()? ? ? ? ?throws IOException, ClassNotFoundException? ? {? ? ? ? ?if (enableOverride) {? ? ? ? ? ? ?return readObjectOverride();? ? ? ? }??? ? ? ? ?// if nested read, passHandle contains handle of enclosing object? ? ? ? ?int outerHandle = passHandle;? ? ? ? ?try {? ? ? ? ? ? ?Object obj = readObject0(false);? ? ? ? ? ? ?handles.markDependency(outerHandle, passHandle);? ? ? ? ? ? ?ClassNotFoundException ex = handles.lookupException(passHandle);? ? ? ? ? ? ?if (ex != null) {? ? ? ? ? ? ? ? ?throw ex;? ? ? ? ? ? }? ? ? ? ? ? ?if (depth == 0) {? ? ? ? ? ? ? ? ?vlist.doCallbacks();? ? ? ? ? ? }? ? ? ? ? ? ?return obj;? ? ? ? } finally {? ? ? ? ? ? ?passHandle = outerHandle;? ? ? ? ? ? ?if (closed && depth == 0) {? ? ? ? ? ? ? ? ?clear();? ? ? ? ? ? }? ? ? ? }? ? }我們發(fā)現(xiàn),在readObject()方法中又調(diào)用了重寫的readObject0()方法。進(jìn)入readObject0()方法, 代碼如下:
?private Object readObject0(boolean unshared) throws IOException {? ...? ? ?case TC_OBJECT:? ? return checkResolve(readOrdinaryObject(unshared));? ? ...?}我們看到TC_OBJECT中調(diào)用了ObjectInputStream的readOrdinaryObject()方法,看源碼:
? ? ?private Object readOrdinaryObject(boolean unshared)? ? ? ? ?throws IOException? ? {? ? ? ? ?if (bin.readByte() != TC_OBJECT) {? ? ? ? ? ? ?throw new InternalError();? ? ? ? }??? ? ? ? ?ObjectStreamClass desc = readClassDesc(false);? ? ? ? ?desc.checkDeserialize();??? ? ? ? ?Class> cl = desc.forClass();? ? ? ? ?if (cl == String.class || cl == Class.class? ? ? ? ? ? ? ? ?|| cl == ObjectStreamClass.class) {? ? ? ? ? ? ?throw new InvalidClassException("invalid class descriptor");? ? ? ? }??? ? ? ? ?Object obj;? ? ? ? ?try {? ? ? ? ? ? ?obj = desc.isInstantiable() ? desc.newInstance() : null;? ? ? ? } catch (Exception ex) {? ? ? ? ? ? ?throw (IOException) new InvalidClassException(? ? ? ? ? ? ? ? ?desc.forClass().getName(),? ? ? ? ? ? ? ? ?"unable to create instance").initCause(ex);? ? ? ? }? ...??? ? ? ? ?return obj;? ? }我們發(fā)現(xiàn)調(diào)用了ObjectStreamClass的isInstantiable()方法,而isInstantiable()方法的代碼如下:
? ? ?boolean isInstantiable() {? ? ? ? ?requireInitialized();? ? ? ? ?return (cons != null);? ? }上述代碼非常簡(jiǎn)單,就是判斷一下構(gòu)造方法是否為空,構(gòu)造方法不為空就返回true。這意味著只要 有無(wú)參構(gòu)造方法就會(huì)實(shí)例化。
這時(shí)候其實(shí)還沒(méi)有找到加上 readResolve()方法就避免了單例模式被破壞的真正原因。再回到 ObjectInputStream的readOrdinaryObject()方法,繼續(xù)往下看:
? ? ?private Object readOrdinaryObject(boolean unshared)? ? ? ? ?throws IOException? ? {? ? ? ? ?if (bin.readByte() != TC_OBJECT) {? ? ? ? ? ? ?throw new InternalError();? ? ? ? }??? ? ? ? ?ObjectStreamClass desc = readClassDesc(false);? ? ? ? ?desc.checkDeserialize();??? ? ? ? ?Class> cl = desc.forClass();? ? ? ? ?if (cl == String.class || cl == Class.class? ? ? ? ? ? ? ? ?|| cl == ObjectStreamClass.class) {? ? ? ? ? ? ?throw new InvalidClassException("invalid class descriptor");? ? ? ? }??? ? ? ? ?Object obj;? ? ? ? ?try {? ? ? ? ? ? ?obj = desc.isInstantiable() ? desc.newInstance() : null;? ? ? ? } catch (Exception ex) {? ? ? ? ? ? ?throw (IOException) new InvalidClassException(? ? ? ? ? ? ? ? ?desc.forClass().getName(),? ? ? ? ? ? ? ? ?"unable to create instance").initCause(ex);? ? ? ? }??? ? ? ? ...? ? ? ? ?if (obj != null &&? ? ? ? ? ? ?handles.lookupException(passHandle) == null &&? ? ? ? ? ? ?desc.hasReadResolveMethod())? ? ? ? {? ? ? ? ? ? ?Object rep = desc.invokeReadResolve(obj);? ? ? ? ? ? ?if (unshared && rep.getClass().isArray()) {? ? ? ? ? ? ? ? ?rep = cloneArray(rep);? ? ? ? ? ? }? ? ? ? ? ? ?if (rep != obj) {? ? ? ? ? ? ? ? ?// Filter the replacement object? ? ? ? ? ? ? ? ?if (rep != null) {? ? ? ? ? ? ? ? ? ? ?if (rep.getClass().isArray()) {? ? ? ? ? ? ? ? ? ? ? ? ?filterCheck(rep.getClass(), Array.getLength(rep));? ? ? ? ? ? ? ? ? ? } else {? ? ? ? ? ? ? ? ? ? ? ? ?filterCheck(rep.getClass(), -1);? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ?handles.setObject(passHandle, obj = rep);? ? ? ? ? ? }? ? ? ? }??? ? ? ? ?return obj;? ? }判斷無(wú)參構(gòu)造方法是否存在之后,又調(diào)用了hasReadResolveMethod()方法,來(lái)看代碼:
? ? ?boolean hasReadResolveMethod() {? ? ? ? ?requireInitialized();? ? ? ? ?return (readResolveMethod != null);? ? }上述代碼邏輯非常簡(jiǎn)單,就是判斷 readResolveMethod 是否為空,不為空就返回 true。那么 readResolveMethod是在哪里賦值的呢?通過(guò)全局查找知道,在私有方法 ObjectStreamClass()中給 readResolveMethod進(jìn)行了賦值,來(lái)看代碼:
? ? ?private final void requireInitialized() {? ? ? ? ?if (!initialized)? ? ? ? ? ? ?throw new InternalError("Unexpected call when not initialized");? ? }上面的邏輯其實(shí)就是通過(guò)反射找到一個(gè)無(wú)參的 readResolve()方法,并且保存下來(lái)。現(xiàn)在回到 ObjectInputStream 的 readOrdinaryObject()方法繼續(xù)往下看,如果 readResolve()方法存在則調(diào)用 invokeReadResolve()方法,來(lái)看代碼:
? ? ?Object invokeReadResolve(Object obj)? ? ? ? ?throws IOException, UnsupportedOperationException? ? {? ? ? ? ?requireInitialized();? ? ? ? ?if (readResolveMethod != null) {? ? ? ? ? ? ?try {? ? ? ? ? ? ? ? ?return readResolveMethod.invoke(obj, (Object[]) null);? ? ? ? ? ? } catch (InvocationTargetException ex) {? ? ? ? ? ? ? ? ?Throwable th = ex.getTargetException();? ? ? ? ? ? ? ? ?if (th instanceof ObjectStreamException) {? ? ? ? ? ? ? ? ? ? ?throw (ObjectStreamException) th;? ? ? ? ? ? ? ? } else {? ? ? ? ? ? ? ? ? ? ?throwMiscException(th);? ? ? ? ? ? ? ? ? ? ?throw new InternalError(th); ?// never reached? ? ? ? ? ? ? ? }? ? ? ? ? ? } catch (IllegalAccessException ex) {? ? ? ? ? ? ? ? ?// should not occur, as access checks have been suppressed? ? ? ? ? ? ? ? ?throw new InternalError(ex);? ? ? ? ? ? }? ? ? ? } else {? ? ? ? ? ? ?throw new UnsupportedOperationException();? ? ? ? }? ? }我們可以看到,在invokeReadResolve()方法中用反射調(diào)用了readResolveMethod方法。
通過(guò)JDK源碼分析我們可以看出,雖然增加 readResolve()方法返回實(shí)例解決了單例模式被破壞的 問(wèn)題,但是實(shí)際上實(shí)例化了兩次,只不過(guò)新創(chuàng)建的對(duì)象沒(méi)有被返回而已。如果創(chuàng)建對(duì)象的動(dòng)作發(fā)生頻率加快,就意味著內(nèi)存分配開銷也會(huì)隨之增大,難道真的就沒(méi)辦法從根本上解決問(wèn)題嗎?下面講的注冊(cè)式單例也許能幫助到你。
為什么添加了readResolve()方法就可以了?
ObjectInputStream源碼中,讀取文件時(shí)寫死判斷是否有readResolve()方法,有調(diào)用這個(gè)方法,沒(méi)有則重新創(chuàng)建對(duì)象。
4.8.注冊(cè)式單例模式
將每一個(gè)實(shí)例都緩存到統(tǒng)一的容器中,使用唯一表示獲取實(shí)例。
注冊(cè)式單例模式又稱為登記式單例模式,就是將每一個(gè)實(shí)例都登記到某一個(gè)地方,使用唯一的標(biāo)識(shí)獲取實(shí)例。注冊(cè)式單例模式有兩種:一種為枚舉式單例模式,另一種為容器式單例模式。
方法1. 枚舉式單例模式
先來(lái)看枚舉式單例模式的寫法,來(lái)看代碼,創(chuàng)建EnumSingleton類:
?public enum EnumSingleton {? ? ?INSTANCE;??? ? ?private Object data;??? ? ?public Object getData() {? ? ? ? ?return data;? ? }??? ? ?public void setData(Object data) {? ? ? ? ?this.data = data;? ? }??? ? ?public static EnumSingleton getInstance(){return INSTANCE;}?}來(lái)看測(cè)試代碼:
?public class EnumSingletonTest {? ? ?public static void main(String[] args) {? ? ? ? EnumSingleton instance = EnumSingleton.getInstance();? ? ? ? instance.setData(new Object());? ? ? ? ?try {? ? ? ? ? ? ?Class clazz = EnumSingleton.class;? ? ? ? ? ? ?Constructor c = clazz.getDeclaredConstructor(String.class, int.class);? ? ? ? ? ? ?c.setAccessible(true);? ? ? ? ? ? ?System.out.println(c);? ? ? ? ? ? ?Object o = c.newInstance();? ? ? ? ? ? ?System.out.println(o);? ? ? ? } catch (Exception e) {? ? ? ? ? ? ?e.printStackTrace();? ? ? ? }? ? }?}?java.lang.Object@2acf57e3?java.lang.Object@2acf57e3?true沒(méi)有做任何處理,我們發(fā)現(xiàn)運(yùn)行結(jié)果和預(yù)期的一樣。那么枚舉式單例模式如此神奇,它的神秘之處 在哪里體現(xiàn)呢?下面通過(guò)分析源碼來(lái)揭開它的神秘面紗。
下載一個(gè)非常好用的 Java反編譯工具 Jad(下載地址:https://varaneckas.com/jad/),解壓后 配置好環(huán)境變量(這里不做詳細(xì)介紹),就可以使用命令行調(diào)用了。找到工程所在的Class目錄,復(fù)制 EnumSingleton.class 所在的路徑,如下圖所示。
然后切換到命令行,切換到工程所在的Class目錄,輸入命令 jad 并在后面輸入復(fù)制好的路徑,在 Class 目錄下會(huì)多出一個(gè) EnumSingleton.jad 文件。打開 EnumSingleton.jad 文件我們驚奇地發(fā)現(xiàn)有 如下代碼:
?static { ? ? ?INSTANCE = new EnumSingleton("INSTANCE", 0); ? ? ?$VALUES = (new EnumSingleton[] { ? ? ? ? ?INSTANCE ? ? }); ?}原來(lái),枚舉式單例模式在靜態(tài)代碼塊中就給INSTANCE進(jìn)行了賦值,是餓漢式單例模式的實(shí)現(xiàn)。至 此,我們還可以試想,序列化能否破壞枚舉式單例模式呢?不妨再來(lái)看一下 JDK 源碼,還是回到 ObjectInputStream的readObject0()方法:
? ? ?private Object readObject0(boolean unshared) throws IOException {? ? ? ? ...? ? ? ? ?case TC_ENUM:? ? ? ? return checkResolve(readEnum(unshared));? ? ? ? ...? ? }我們看到,在readObject0()中調(diào)用了readEnum()方法,來(lái)看readEnum()方法的代碼實(shí)現(xiàn):
? ? ?private Enum> readEnum(boolean unshared) throws IOException {? ? ? ? ?if (bin.readByte() != TC_ENUM) {? ? ? ? ? ? ?throw new InternalError();? ? ? ? }??? ? ? ? ?ObjectStreamClass desc = readClassDesc(false);? ? ? ? ?if (!desc.isEnum()) {? ? ? ? ? ? ?throw new InvalidClassException("non-enum class: " + desc);? ? ? ? }??? ? ? ? ?int enumHandle = handles.assign(unshared ? unsharedMarker : null);? ? ? ? ?ClassNotFoundException resolveEx = desc.getResolveException();? ? ? ? ?if (resolveEx != null) {? ? ? ? ? ? ?handles.markException(enumHandle, resolveEx);? ? ? ? }??? ? ? ? ?String name = readString(false);? ? ? ? ?Enum> result = null;? ? ? ? ?Class> cl = desc.forClass();? ? ? ? ?if (cl != null) {? ? ? ? ? ? ?try {? ? ? ? ? ? ? ? ?@SuppressWarnings("unchecked")? ? ? ? ? ? ? ? ?Enum> en = Enum.valueOf((Class)cl, name);? ? ? ? ? ? ? ? ?result = en;? ? ? ? ? ? } catch (IllegalArgumentException ex) {? ? ? ? ? ? ? ? ?throw (IOException) new InvalidObjectException(? ? ? ? ? ? ? ? ? ? ?"enum constant " + name + " does not exist in " +? ? ? ? ? ? ? ? ? ? ?cl).initCause(ex);? ? ? ? ? ? }? ? ? ? ? ? ?if (!unshared) {? ? ? ? ? ? ? ? ?handles.setObject(enumHandle, result);? ? ? ? ? ? }? ? ? ? }??? ? ? ? ?handles.finish(enumHandle);? ? ? ? ?passHandle = enumHandle;? ? ? ? ?return result;? ? }我們發(fā)現(xiàn),枚舉類型其實(shí)通過(guò)類名和類對(duì)象類找到一個(gè)唯一的枚舉對(duì)象。因此,枚舉對(duì)象不可能被 類加載器加載多次。那么反射是否能破壞枚舉式單例模式呢?來(lái)看一段測(cè)試代碼:
? ? ?public static void main(String[] args) {? ? ? ? ?try {? ? ? ? ? ? ?Class clazz = EnumSingleton.class;? ? ? ? ? ? ?Constructor c = clazz.getDeclaredConstructor();? ? ? ? ? ? ?c.newInstance();? ? ? ? } catch (Exception e) {? ? ? ? ? ? ?e.printStackTrace();? ? ? ? }? ? }運(yùn)行結(jié)果如下圖所示。
結(jié)果中報(bào)的是 java.lang.NoSuchMethodException異常,意思是沒(méi)找到無(wú)參的構(gòu)造方法。這時(shí)候, 我們打開 java.lang.Enum的源碼,查看它的構(gòu)造方法,只有一個(gè)protected類型的構(gòu)造方法,代碼如 下:
? ? ?protected Enum(String name, int ordinal) {? ? ? ? ?this.name = name;? ? ? ? ?this.ordinal = ordinal;? ? }我們?cè)賮?lái)做一個(gè)下面這樣的測(cè)試:
? ? ?public static void main(String[] args) {? ? ? ? ?try {? ? ? ? ? ? ?Class clazz = EnumSingleton.class;? ? ? ? ? ? ?Constructor c = clazz.getDeclaredConstructor(String.class, int.class);? ? ? ? ? ? ?c.setAccessible(true);? ? ? ? ? ? ?EnumSingleton enumSingleton = (EnumSingleton) c.newInstance("Tom", 666);? ? ? ? } catch (Exception e) {? ? ? ? ? ? ?e.printStackTrace();? ? ? ? }? ? }運(yùn)行結(jié)果如下圖所示
這時(shí)錯(cuò)誤已經(jīng)非常明顯了,“Cannot reflectively create enum objects”,即不能用反射來(lái)創(chuàng)建 枚舉類型。還是習(xí)慣性地想來(lái)看看JDK源碼,進(jìn)入Constructor的newInstance()方法:
? ? ?@CallerSensitive? ? ?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;? ? }從上述代碼可以看到,在 newInstance()方法中做了強(qiáng)制性的判斷,如果修飾符是Modifier.ENUM 枚舉類型,則直接拋出異常。
到此為止,我們是不是已經(jīng)非常清晰明了呢?枚舉式單例模式也是《EffectiveJava》書中推薦的一種單例模式實(shí)現(xiàn)寫法。JDK枚舉的語(yǔ)法特殊性及反射也為枚舉保駕護(hù)航,讓枚舉式單例模式成為一種比 較優(yōu)雅的實(shí)現(xiàn)。
枚舉源碼
java.lang.Enum通過(guò)valueOf獲得值
? ? ?public static > T valueOf(Class enumType,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?String name) {? ? ? ? ?T result = enumType.enumConstantDirectory().get(name);? ? ? ? ?if (result != null)? ? ? ? ? ? ?return result;? ? ? ? ?if (name == null)? ? ? ? ? ? ?throw new NullPointerException("Name is null");? ? ? ? ?throw new IllegalArgumentException(? ? ? ? ? ? ?"No enum constant " + enumType.getCanonicalName() + "." + name);? ? }??? ? ?Map enumConstantDirectory() {? ? ? ? ?if (enumConstantDirectory == null) {? ? ? ? ? ? ?T[] universe = getEnumConstantsShared();? ? ? ? ? ? ?if (universe == null)? ? ? ? ? ? ? ? ?throw new IllegalArgumentException(? ? ? ? ? ? ? ? ? ? ?getName() + " is not an enum type");? ? ? ? ? ? ?Map m = new HashMap<>(2 * universe.length);? ? ? ? ? ? ?for (T constant : universe)? ? ? ? ? ? ? ? ?m.put(((Enum>)constant).name(), constant);? ? ? ? ? ? ?enumConstantDirectory = m;? ? ? ? }? ? ? ? ?return enumConstantDirectory;? ? }? ? ?private volatile transient Map enumConstantDirectory = null;枚舉模式的實(shí)例天然具有線程安全性,防止序列化與反射的特性。
有點(diǎn)像餓漢式單例。創(chuàng)建時(shí)就將常量存放在map容器中。
優(yōu)點(diǎn):寫法優(yōu)雅。加載時(shí)就創(chuàng)建對(duì)象。線程安全。
缺點(diǎn):不能大批量創(chuàng)建對(duì)象,否則會(huì)造成浪費(fèi)。spring中不能使用它。
結(jié)論:如果不是特別重的對(duì)象,建議使用枚舉單例模式,它是JVM天然的單例。
方法2. 容器式單例
Spring改良枚舉寫出的改良方法:IOC容器
接下來(lái)看注冊(cè)式單例模式的另一種寫法,即容器式單例模式,創(chuàng)建ContainerSingleton類:
?public class ContainerSingleton {??? ? ?private ContainerSingleton(){}??? ? ?private static Map ioc = new ConcurrentHashMap();??? ? ?public static Object getInstance(String className){? ? ? ? ?Object instance = null;? ? ? ? ?if(!ioc.containsKey(className)){? ? ? ? ? ? ?try {? ? ? ? ? ? ? ? ?instance = Class.forName(className).newInstance();? ? ? ? ? ? ? ? ?ioc.put(className, instance);? ? ? ? ? ? }catch (Exception e){? ? ? ? ? ? ? ? ?e.printStackTrace();? ? ? ? ? ? }? ? ? ? ? ? ?return instance;? ? ? ? }else{? ? ? ? ? ? ?return ioc.get(className);? ? ? ? }? ? }?}測(cè)試
?public class ContainerSingletonTest {? ? ?public static void main(String[] args) {? ? ? ? ?Object instance1 = ContainerSingleton.getInstance("com.gupaoedu.vip.pattern.singleton.test.Pojo");? ? ? ? ?Object instance2 = ContainerSingleton.getInstance("com.gupaoedu.vip.pattern.singleton.test.Pojo");? ? ? ? ?System.out.println(instance1 == instance2);? ? }?}結(jié)果
?true容器式單例模式適用于實(shí)例非常多的情況,便于管理。但它是非線程安全的。到此,注冊(cè)式單例模式介紹完畢。我們?cè)賮?lái)看看Spring中的容器式單例模式的實(shí)現(xiàn)代碼:
?public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory? implements AutowireCapableBeanFactory {? ? ?? /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */? private final Map factoryBeanInstanceCache =? new ConcurrentHashMap(16);?}容器為啥不能被反射破壞?秩序的維護(hù)者,創(chuàng)造了一個(gè)生態(tài)
4.9.線程單例實(shí)現(xiàn)ThreadLocal
最后贈(zèng)送給大家一個(gè)彩蛋,講講線程單例實(shí)現(xiàn) ThreadLocal。ThreadLocal 不能保證其創(chuàng)建的對(duì)象 是全局唯一的,但是能保證在單個(gè)線程中是唯一的,天生是線程安全的。下面來(lái)看代碼:
?public class ThreadLocalSingleton {? ? ?private static final ThreadLocal threadLocaLInstance =? ? ? ? ? ? ?new ThreadLocal(){? ? ? ? ? ? ? ? ?@Override? ? ? ? ? ? ? ? ?protected ThreadLocalSingleton initialValue() {? ? ? ? ? ? ? ? ? ? ?return new ThreadLocalSingleton();? ? ? ? ? ? ? ? }? ? ? ? ? ? };??? ? ?private ThreadLocalSingleton(){}??? ? ?public static ThreadLocalSingleton getInstance(){? ? ? ? ?return threadLocaLInstance.get();? ? }?}寫一下測(cè)試代碼:
?public class ThreadLocalSingletonTest {??? ? ?public static void main(String[] args) {? ? ? ? ?System.out.println(ThreadLocalSingleton.getInstance());? ? ? ? ?System.out.println(ThreadLocalSingleton.getInstance());? ? ? ? ?System.out.println(ThreadLocalSingleton.getInstance());? ? ? ? ?System.out.println(ThreadLocalSingleton.getInstance());? ? ? ? ?System.out.println(ThreadLocalSingleton.getInstance());? ? ? ? ?Thread t1 = new Thread(new ExectorThread());? ? ? ? ?Thread t2 = new Thread(new ExectorThread());? ? ? ? ?t1.start();? ? ? ? ?t2.start();? ? ? ? ?System.out.println("End");? ? }?}運(yùn)行結(jié)果如下圖所示。
?com.gupaoedu.vip.pattern.singleton.threadlocal.ThreadLocalSingleton@1761e840?com.gupaoedu.vip.pattern.singleton.threadlocal.ThreadLocalSingleton@1761e840?com.gupaoedu.vip.pattern.singleton.threadlocal.ThreadLocalSingleton@1761e840?com.gupaoedu.vip.pattern.singleton.threadlocal.ThreadLocalSingleton@1761e840?com.gupaoedu.vip.pattern.singleton.threadlocal.ThreadLocalSingleton@1761e840?End?Thread-0:com.gupaoedu.vip.pattern.singleton.lazy.LazyDoubleCheckSingleton@551f86f1?Thread-1:com.gupaoedu.vip.pattern.singleton.lazy.LazyDoubleCheckSingleton@551f86f1我們發(fā)現(xiàn),在主線程中無(wú)論調(diào)用多少次,獲取到的實(shí)例都是同一個(gè),都在兩個(gè)子線程中分別獲取到 了不同的實(shí)例。那么 ThreadLocal是如何實(shí)現(xiàn)這樣的效果的呢?我們知道,單例模式為了達(dá)到線程安全 的目的,會(huì)給方法上鎖,以時(shí)間換空間。ThreadLocal 將所有的對(duì)象全部放在 ThreadLocalMap 中,為每個(gè)線程都提供一個(gè)對(duì)象,實(shí)際上是以空間換時(shí)間來(lái)實(shí)現(xiàn)線程隔離的。
不是線程作為key,而是threadlocal本身。
ThreadLocal源碼
?public T get() {? ? ?Thread t = Thread.currentThread();? ? ?ThreadLocalMap map = getMap(t);? ? ?if (map != null) {? ? ? ? ?ThreadLocalMap.Entry e = map.getEntry(this);? ? ? ? ?if (e != null) {? ? ? ? ? ? ?@SuppressWarnings("unchecked")? ? ? ? ? ? ?T result = (T)e.value;? ? ? ? ? ? ?return result;? ? ? ? }? ? }? ? ?return setInitialValue();?}5.0.源碼
AbstractFactoryBean
? public final T getObject() throws Exception {? if (isSingleton()) {? return (this.initialized ? this.singletonInstance : getEarlySingletonInstance());? }? else {? return createInstance();? }? }??? private T getEarlySingletonInstance() throws Exception {? Class[] ifcs = getEarlySingletonInterfaces();? if (ifcs == null) {? throw new FactoryBeanNotInitializedException(? getClass().getName() + " does not support circular references");? }? if (this.earlySingletonInstance == null) {? this.earlySingletonInstance = (T) Proxy.newProxyInstance(? this.beanClassLoader, ifcs, new EarlySingletonInvocationHandler());? }? return this.earlySingletonInstance;? }MyBatis的ErrorContext使用了ThreadLocal
?public class ErrorContext {??? ?private static final ThreadLocal LOCAL = new ThreadLocal<>();??? ?private ErrorContext() {? }??? ?public static ErrorContext instance() {? ? ?ErrorContext context = LOCAL.get();? ? ?if (context == null) {? ? ? ?context = new ErrorContext();? ? ? ?LOCAL.set(context);? ? }? ? ?return context;? }?}5.0.單例模式小結(jié)
單例模式優(yōu)點(diǎn):
單例模式的缺點(diǎn):
學(xué)習(xí)單例模式的知識(shí)重點(diǎn)總結(jié)
單例模式可以保證內(nèi)存里只有一個(gè)實(shí)例,減少了內(nèi)存的開銷,還可以避免對(duì)資源的多重占用。單例模式看起來(lái)非常簡(jiǎn)單,實(shí)現(xiàn)起來(lái)其實(shí)也非常簡(jiǎn)單,但是在面試中卻是一個(gè)高頻面試點(diǎn)。希望“小伙伴們” 通過(guò)本章的學(xué)習(xí),對(duì)單例模式有了非常深刻的認(rèn)識(shí),在面試中彰顯技術(shù)深度,提升核心競(jìng)爭(zhēng)力,給面試 加分,順利拿到錄取通知(Offer)。
5.1.作業(yè)
1、解決容器式單例的線程安全問(wèn)題。
兩種方法:雙重檢查鎖,利用ConcurrentHashMap#putIfAbsent()方法的原子性。
?public class ContainerSingleton {??? ? ?private static Map ioc = new ConcurrentHashMap();??? ? ?private ContainerSingleton() {? ? ? ? ?throw new RuntimeException("不可被實(shí)例化!");? ? }??? ? ?// 方法一:雙重檢查鎖? ? ?public static Object getInstance(String className) {? ? ? ? ?Object instance = null;? ? ? ? ?if (!ioc.containsKey(className)) {? ? ? ? ? ? ?synchronized (ContainerSingleton.class) {? ? ? ? ? ? ? ? ?if (!ioc.containsKey(className)) {? ? ? ? ? ? ? ? ? ? ?try {? ? ? ? ? ? ? ? ? ? ? ? ?instance = Class.forName(className).newInstance();? ? ? ? ? ? ? ? ? ? ? ? ?ioc.put(className, instance);? ? ? ? ? ? ? ? ? ? } catch (Exception e) {? ? ? ? ? ? ? ? ? ? ? ? ?e.printStackTrace();? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ? ? ?return instance;? ? ? ? ? ? ? ? } else {? ? ? ? ? ? ? ? ? ? ?return ioc.get(className);? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? }? ? ? ? ?return ioc.get(className);? ? }??? ? ?// 方法二:利用ConcurrentHashMap#putIfAbsent()方法的原子性? ? ?public static Object getInstance1(String className){? ? ? ? ?Object instance = null;? ? ? ? ?try {? ? ? ? ? ? ?ioc.putIfAbsent(className, Class.forName(className).newInstance());? ? ? ? }catch (Exception e){? ? ? ? ? ? ?e.printStackTrace();? ? ? ? }? ? ? ? ?return ioc.get(className);? ? }?} 《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的以下属于单例模式的优点的是_三、单例模式详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 10kv开关柜价格_什么是10KV开闭所
- 下一篇: lopa分析_【风险分析方法】HAZOP