2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Java creationism of instance/object

Sometimes we used to get requirement like how many object we have created which are alive. And typically do by adding a private static variable which can be access by a public method. Now lets see the fun:

public class Create {
    private static long numberOf = 0;
    
    public Create() {
        numberOf++;
    }
    
    public static long getNumberOf() {
        return numberOf;
    }
}

public class Creator {
    public static void main(String... args) {
        for(int i=0; i < 100; i++)
            Create create = new Create();
        System.out.println(Create.getNumberOf());
    }
}

Now after seeing the code we might think like will get the result as 100. Where actual fact is the program will not compile. You will get Exception like :
"not a statement".

A local variable declaration looks like a statement but its not, it"s a local variable declaration statement. The syntax of the language dose not allow a local variable declaration statement as the statement repeated by for, while, or a do loop. A local variable declaration can appear only as a statement directly within a block.

for(int i=0; i < 100; i++) { // BLOCK START ...
    Create create = new Create(); // LIKE HERE ...
} // BLOCK END ...

else we can write as below:

for(int i=0; i < 100; i++) { // BLOCK START ...
    new Create(); // LIKE HERE ...
} // BLOCK END ...
        
Now if we talk about the thread safe, the way we did all code is not at all thread safe. Now to make it thread save we can follow below methods:

public class Create {
    private static long numberOf = 0;
    
    public Create() {
        synchronized (Create.class){
            numberOf++;
        }
    }
    
    public static synchronized long getNumberOf() {
        return numberOf;
    }
}

or else we can use below way :

public class Create {
    private static AtomicLong numberOf = new AtomicLong();
    
    public Create() {
        numberOf.increamentAndGet();
    }
    
    public static long getNumberOf() {
        return numberOf.get();
    }
}