Created
September 10, 2016 10:29
-
-
Save MaksimDmitriev/f76c4fe374d6332d574e2b4fe8a26a25 to your computer and use it in GitHub Desktop.
PublicInstance Singleton in Java. Why is it not a lazy initialization?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mian; | |
import sample.PublicInstance; | |
public class Main { | |
public static void main(String[] args) { | |
System.out.println(PublicInstance.STRING); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PublicInstance() from 1 | |
Lorem |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// when STRING is final | |
Lorem | |
See? The PublicInstance() constructor wasn't called. | |
final matters :) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample; | |
public class PublicInstance { | |
public static String STRING = "Lorem"; | |
public static final PublicInstance INSTANCE = new PublicInstance(); | |
private PublicInstance() { | |
System.out.println("PublicInstance() from " + Thread.currentThread().getId()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm.. But with public static String STRING = new String("Lorem"); PublicInstance() will be called.