Interesting little java demo

I wrote the class below to ensure that a class reference is preserved when you add it to a collection (I had forgotten and had a quick panic moment) but I found something interesting, the time nature of java is really inaccurate. I printed out the time in millis, slept for 100, then time in millis again. You would expect the second number to be first + 100, right? It’s actually +95 of my machine. Ugly.

import java.util.ArrayList;
import java.util.List;

public class DumbTest {

    public static void main(String[] args) {

        try {
            List l = new ArrayList();           
            Ent ent = new Ent();
           
            System.out.println(“Step 1”);
            System.out.println(ent + “\n”);
           
            Thread.sleep(100);
            l.add(0, ent);
            ent = new Ent();
           
            System.out.println(“Step 2”);
            System.out.println(ent + “\n”);
           
            Thread.sleep(100);           
            System.out.println(“Step 3”);
            System.out.println(l.get(0) + “\n”);
           
        } catch (Exception e) {
            System.err.println(“Error: ” + e.toString());
        }

    }

}

class Ent {
    private long val = 0;

    public Ent() {
        val = System.currentTimeMillis();
    }

    public String toString() {
        return “Ent Val: ” + val;
    }
}