I came across opinions that some classes ("heavy class") should not be repeatedly created and disposed of as it takes too of JVM's overhead/time/resources. While it is possible to imagine what is a heavy-class - I have never came across any definition of it.
Background:
- repeatedly creating and disposing of SimpleDateFormat for converison of date was seen as a bad practice. SimpleDateFormat is not thread safe and I would not be in favour of synchronization of it in the web environment.
So:
- is there a proper definition of "heavy class" ?
UPDATE
I do not think of any definition of a "heavy class". If you can come up with any definition - I am happy to upvote...
Meanwhile I created a test to find out how long it takes for a JVM to create and dispose of SimpleDateFormat objects. On my i7 box I got 390-400 thousands of objects created and disposed of (run with heap memory limit 64Mb, -Xms32m -Xmx64m):
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;
public class SdfTest {
static AtomicLong created = new AtomicLong(0L);
static AtomicLong disposed = new AtomicLong(0L);
public static class SimpleDateFormat2 extends SimpleDateFormat {
private static final long serialVersionUID = 1L;
public SimpleDateFormat2() {
created.incrementAndGet();
}
@Override
protected void finalize() throws Throwable {
disposed.incrementAndGet();
super.finalize();
}
}
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.format("Start: total mem: %d, freeMemory: %d, maxMemory: %d%n",
rt.totalMemory(), rt.freeMemory(), rt.maxMemory());
LocalDateTime start = LocalDateTime.now();
for (int i = 0; i < 10_000_000; i++) {
new SimpleDateFormat2();
}
System.gc();
LocalDateTime stop = LocalDateTime.now();
Long durationMs = Duration.between(start, stop).toMillis();
System.out.println("Duration: " + durationMs + " miliseconds");
System.out.println("Created " + created + " and disposed of: " + disposed + " objects.");
System.out.println("Average time of creating + disposing time: " + 1000 *
( (double) disposed.get() / durationMs) + " objects per second." );
}
}
Scored:
Start: total mem: 32505856, freeMemory: 31597048, maxMemory: 59768832
Duration: 25568 miliseconds Created 10000000 and disposed of: 10000000 objects
Average time of creating + disposing time: 391113.8923654568 objects per second.