java - Is instantiating non final static variables Thread-Safe? -
is 2 class same?
public class singletone { // yes bug if change class way // private static singletone instance = new singletone(); // , empty constructor? private static singletone instance; private singletone() { instance = new singletone(); } public static singletone getinstance(){ return instance; } }
and
public class singletone { private final static singletone instance = new singletone(); private singletone() { } public static singletone getinstance(){ return instance; } }
is there thread-safety issue in none final variable instantiated constructor?
question 2:
what differences between
private final static singletone instance = new singletone(); private singletone() { }
and this:
private final static singletone instance; private singletone() { instance = new singletone(); }
queston 1
your first example doesnt work.
as if make call singletone.getinstance()
before object of type has been created return null
second example works fine
question 2
same situation, youre instatiating static field in constructor. doesnt make sense cant guarantee constructor has been called before accessing static field.
you can instead:
private final static singletone instance; static { instance = new singletone(); }
this instantiate static field when class first loaded.
answering comment.
if this:
private static final singletone instance = new singletone();
that thread safe if first thread hasnt finished initializing class , thread tries access other thread block.
see question more info: thread safety of static blocks in java
Comments
Post a Comment