• Source
    1. import java.util.*;
    2. import java.lang.*;
    3. import java.io.*;
    4.  
    5. class Ideone {
    6.  
    7. public static void main (String[] args) throws java.lang.Exception {
    8.  
    9. long st, en;
    10. st = System.nanoTime();
    11. for(int i = 1; i < 100000; i++){
    12. Singleton s=Singleton.getInstance();
    13. }
    14. en = System.nanoTime();
    15. System.out.println("One:" + (en - st)/1000000.d + " msc");
    16. //------
    17.  
    18. st = System.nanoTime();
    19. for(int i = 1; i < 100000; i++){
    20. Singleton2 s=Singleton2.getInstance();
    21. }
    22. en = System.nanoTime();
    23. System.out.println("Two:" + (en - st)/1000000.d + " msc");
    24. //------
    25.  
    26. SingletonBulder sb=new SingletonBulder();
    27. Singleton s0=sb.getInstance();
    28.  
    29. st = System.nanoTime();
    30. for(int i = 1; i < 100000; i++){
    31. Singleton s=sb.getInstance();
    32. }
    33. en = System.nanoTime();
    34. System.out.println("SB:" + (en - st)/1000000.d + " msc");
    35. }
    36. }
    37.  
    38. class Singleton {
    39. private static volatile Singleton instance;
    40.  
    41. public static Singleton getInstance() {
    42. if (instance == null) {
    43. synchronized (Singleton.class) {
    44. if (instance == null) {
    45. instance = new Singleton();
    46. }
    47. }
    48. }
    49. return instance;
    50. }
    51. }
    52.  
    53. class Singleton2 {
    54. private static volatile Singleton2 instance2;
    55.  
    56. private static Singleton2 getInstance2() {
    57. if (instance2 == null) {
    58. synchronized(Singleton2.class) {
    59. if (instance2 == null) {
    60. instance2 = new Singleton2();
    61. }
    62. }
    63. }
    64. return instance2;
    65. }
    66.  
    67. private static Singleton2 instance;
    68.  
    69. public static Singleton2 getInstance() {
    70. if (instance == null) {
    71. instance = getInstance2();
    72. }
    73. return instance;
    74. }
    75. }
    76.  
    77. class SingletonBulder {
    78. private static Singleton instance;
    79. private static SingletonBulder.SB sb;
    80. public SingletonBulder(){
    81. sb=new SB();
    82. }
    83. public Singleton getInstance() {
    84. return sb.getInstance();
    85. }
    86. private class SB{
    87. public Singleton getInstance() {
    88. instance=Singleton.getInstance();
    89. sb=new SB(){
    90. public Singleton getInstance(){
    91. return instance;
    92. }
    93. };
    94. return instance;
    95. }
    96. }
    97. }