ãã«ãã¹ã¬ããã«ã¤ãã¦ããããèãã¦ãæ©ä¼ãå¤ãã£ãã®ã§ã¡ãã£ã¨ã¾ã¨ãã¦ã¿ãã
Singletonã®double-checked lockingã¯ã¢ã³ããã¿ã¼ã³ã ã¨ãã話
double-checked lockingとSingletonパターン
ãããã§ãåæã«æ¸ããã¦ããããã©ãã¡ã¸ã£ã¼ãªæ¸ãæ¹ãªã®ã§ã¿ããªãã¤ã®éã«ã使ã£ã¦ãã¾ã£ã¦ãããã¨ãå¤ãã*1被害ã«ä¼ãå¯è½æ§ãé常ã«ä½ãã®ã§å¯¾çã¯ã»ã¼å¿
è¦ãªããã©ç¥ã£ã¦ããã¦æã¯ãªãã
double-checked lockingã¨ã¯ã©ããªã½ã¼ã¹ãã¨ããã¨
public static Singleton getInstance(){ if (instance == null){ synchronized(Singleton.class) { //1 if (instance == null) //2 instance = new Singleton(); //3 } } return instance; }
è³æ¥µä¸è¬çã«è¦ãããå¤å´ã§1åNULLãã§ãã¯ããã¦ã·ã³ã¯ãå
é¨ã§ãã1åNULLãã§ãã¯ãã¦ã¤ã³ã¹ã¿ã³ã¹ãè¿å´ããã¨ãã£ãå®è£
ã§ãã
ä¸è¦ã¾ã£ããåé¡ãªãã®ã§ãããå¹é£ã®ã¿ã¤ãã³ã°ã§ããgetInstanceãä¸æ£ãªå¤ãè¿å´ããå¯è½æ§ãããã¾ãã
詳ããã¯ここãåç
§ã§ãããã¡ã¢ãªã確ä¿ãããç¬éã¨ãã³ã³ã¹ãã©ã¯ã¿ãçµäºããã¿ã¤ãã³ã°ãç°ãªãããããã®éã«ã¹ã¬ãããåãæ¿ããå¯è½æ§ãããã¾ãããã®å ´åå¾ããæ¥ãã¹ã¬ããï¼ã¹ã¬ãã2ï¼ã¯åæåãå®äºãã¦ããªãã¤ã³ã¹ã¿ã³ã¹ãåç
§ãã¦ãã¾ãã¾ãã
1. ã¹ã¬ãã1ãgetInstance() ã¡ã½ããã«å ¥ãã¾ãã
double-checked lockingとSingletonパターン
2. instance ãnull ã§ãããããã¹ã¬ãã1㯠//1ã§synchronized ãããã¯ã«å ¥ãã¾ãã
3. ã¹ã¬ãã1㯠//3ã«é²ãã§ã¤ã³ã¹ã¿ã³ã¹ãénull ã«ãã¾ããããã®ã¨ãã«ã¯ã¾ã ã³ã³ã¹ãã©ã¯ã¿ã¼ãå®è¡ããã¦ãã¾ããã
4. ã¹ã¬ãã1ãã¹ã¬ãã2ã«åã£ã¦ä»£ãããã¾ãã
5. ã¹ã¬ãã2ã¯ãã¤ã³ã¹ã¿ã³ã¹ãnull ã«ãªã£ã¦ãããã©ããã調ã¹ã¾ããã¤ã³ã¹ã¿ã³ã¹ãnull ã«ãªã£ã¦ããªããããã¹ã¬ãã2ã¯ãå®å ¨ã«æ§æããããããé¨åçã«ããåæåããã¦ããªãSingleton ãªãã¸ã§ã¯ãããinstance åç §ã«å¯¾ãã¦æ»ãã¾ãã
6. ã¹ã¬ãã2ãã¹ã¬ãã1ã«åã£ã¦ä»£ãããã¾ãã
7. ã¹ã¬ãã1ã¯ãã³ã³ã¹ãã©ã¯ã¿ã¼ãå®è¡ãã¦ããã«å¯¾ããåç §ãæ»ããã¨ã«ãããSingleton ãªãã¸ã§ã¯ãã®åæåãå®äºãã¾ãã
ããã¯Javaã®ã¡ã¢ãªã¢ãã«ã®åé¡ã§å®éã«ãããçºçãããã¯VMãJITã³ã³ãã¤ã©ãªã©ã¨ãé¢ä¿ãã¾ãï¼ã§ãJITãããé ã«ã¯Singletonãªãã¸ã§ã¯ãã®çæã¯çµãã£ã¦ãã®ã§åé¡ãªãï¼
C++ã§Mutexã§æä»ããã«volatileã ãã§æä»ããã°ããã³ã³ãã¤ã©ã«ããæé©åã¯é²ãã¦ããã¼ãã¦ã¨ã¢ã«ããæé©åï¼å½ä»¤ã®reorderï¼ã¯é²ããªãã£ã¦ããã®ã¨åããããªã¬ãã«ã®è©±ã§ããã
java.text.SimpleDateFormat ã¯ã¹ã¬ããã»ã¼ãã§ã¯ãªãã¨ãã話ã
ãããæåã§ãããAPIããã¥ã¡ã³ãã«ãããã¦ããã¾ã
Oracle Technology Network for Java Developers | Oracle Technology Network | Oracle
ã¤ãã§ã«ãjava.text.Formatãããjava.text.MessageFormatãããjava.text.NumberFormatãã®ãã©ã¼ãããç³»ã¯ã©ã¹ã¯ã¹ã¬ããã»ã¼ãã§ã¯ããã¾ããã
JavanoCoreAPIã§ãã¹ã¬ããã»ã¼ããããªããã®ã¯ããã®ã§æ°ãã¤ããªãã¦ã¯ãªãã¾ããããã³ãã®APIããªã¼ãã³ã½ã¼ã¹ã®å ´åã¯ç¹ã«æ°ãã¤ãã¾ãããã
ã¤ã³ã¯ãªã¡ã³ããã¹ã¬ããã»ã¼ãã§ã¯ãªãã¨ãã話ã
ã¤ã³ã¯ãªã¡ã³ãã¯å®éã«ã¯èªã¿åãã¨è¿½å ã¨ä¿åã®3ã¤ã®æ¼ç®ãªã®ã§ãã®éã«ã¹ã¬ãããåãæ¿ããå¯è½æ§ãããã¾ãã
連載.NETマルチスレッド・プログラミング入門:第3回 マルチスレッドでデータの不整合を防ぐための排他制御 ― マルチスレッド・プログラミングにおける排他制御と同期制御(前編) ― (3/3) - @IT
è¤æ°ã®ã¹ã¬ãããã1ã¤ã®Intãªããã¤ã³ã¯ãªã¡ã³ããã¾ããã½ã¼ã¹ãæ¸ãã¨åç¾ã§ããããããï¼æã¯åç¾ã§ããã®ã§ããä»ãã£ã¦ã¿ããåç¾ããªããªã£ã¦ã¾ãããVMãã¼ã¸ã§ã³ã¢ãããã¦ããã£ãããï¼ï¼
StringBufferã¯ã¹ã¬ããã»ã¼ãã§ã¨StringBuilderã¯ã¹ã¬ããã¢ã³ã»ã¼ãã¨ãã話ã
ã¾ãããã¯ãã¨ãã¨ãã¹ã¬ããã»ã¼ãã ã£ããã®ã¯ã¹ã¬ããã»ã¼ããããªããã®ãåºæ¥ãã®ã§ã¿ããªç¥ã£ã¦ãã§ãããã
ç¡é§ã«ã¹ã¬ããã»ã¼ãã«ããã¨éããªãã®ã§å¿
è¦ãªã¨ããæå¤ã¯æä»ããªãããã«ãã¾ãããã¨ãã話ã
*1:ç§ã3å¹´ãããåã«æãã¦ãããã¾ã§ã¾ã£ããããããã£ãã