Let's say I created an object, like this
Object obj = new Object();
Now I want to get how long has the object existed, like
System.out.println("Creating object");
Object obj = new Object();
//Print 0
System.out.println("The object has existed for (ms): " + getTime(obj));
Thread.sleep(1000);
//Print 1000
System.out.println("The object has existed for (ms): " + getTime(obj));
How can I do so? Any help is appreciated.
Try this code. finalize() method run in destroy time of object.if the the object goes to garbage collector that finalize method run. in my code System.gc() use for call garbase collector. This code is very long. its only for understanding purpose. You can customize this code.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Thamira
*/
public class Demostra {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("Creating object :" + sdf.format(cal.getTime()));
Object obj = new Object() {
@Override
protected void finalize() throws Throwable {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("The object has removed for : " + sdf.format(cal.getTime()));
super.finalize(); //To change body of generated methods, choose Tools | Templates.
}
};
cal = Calendar.getInstance();
sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("The object has existed for : " + sdf.format(cal.getTime()));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Demostra.class.getName()).log(Level.SEVERE, null, ex);
}
cal = Calendar.getInstance();
sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("The object has existed for : " + sdf.format(cal.getTime()));
obj = null;
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Demostra.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With