public class ChildUnsafe1 {
public static ChildUnsafe1 childUnsafe1;
int age;
ChildUnsafe1(int age){
childUnsafe1 = this;
this.age = age;
}
}
public class ChildUnsafe2 {
public static ChildUnsafe2 childUnsafe2;
int age;
ChildUnsafe2(int age){
this.age = age;
childUnsafe2 = this;
}
}
public class Childsafe2 {
public volatile static Childsafe2 childUnsafe2;
int age;
Childsafe2(int age){
this.age = age;
childUnsafe2 = this;
}
}
public class ChildUnsafe3 extends Childsafe2{
private Object obj;
ChildUnsafe3(int age){
super(10);
obj= new Object();
}
public void doSomething(){
System.out.println(obj.toString());
}
}
public final class ChildFactory {
private static int age;
static {
Thread ageInitializerThread = new Thread(()->{
System.out.println("in thread running");
age=10;
});
ageInitializerThread.start();
try {
ageInitializerThread.join();
} catch (InterruptedException ie) {
throw new AssertionError(ie);
}
}
public static int getAge() {
if (age == 0) {
throw new IllegalStateException("Error initializing age");
}
return age;
}
public static void main(String[] args) {
int age = getAge();
}
}
public final class ChildFactory2 {
private static int age;
static {
System.out.println("in thread running");
age=10;
}
public static int getAge() {
if (age == 0) {
throw new IllegalStateException("Error initializing age");
}
return age;
}
public static void main(String[] args) {
int age = getAge();
}
}
public final class ChildFactory3 {
private static final ThreadLocal<Integer> ageHolder = ThreadLocal.withInitial(() -> 10);
public static int getAge() {
int localAge = ageHolder.get();
if (localAge == 0) {
throw new IllegalStateException("Error initializing age");
}
return localAge;
}
public static void main(String[] args) {
int age = getAge();
}
}