tags:

views:

79

answers:

2

This is really basic, but I can't figure out why it keeps resetting the creation date. I'm using a simple expiration cache on the object. If it is expired, then I will create a new object. If it isn't, then just use the one that exists. However, every time I go to check the creation date on the object, it is the current date.

public class MyObjectImpl implements MyObjectInterface {

    private static final long serialVersionUID = -3542728718515350246L; // auto generated from Eclipse...

    public MyObjectImpl() {
        this.creationDate = new Date().getTime();
    }

    public boolean hasExpired(BigInteger millesecondsToExpiration) {
        if (millesecondsToExpiration == null) {
            millesecondsToExpiration = new BigInteger("2592000000"); // 30 Days
        }
        if (getCreationDate() + millesecondsToExpiration.longValue() < new Date().getTime()) {
            return true;
        } else {
            return false;
        }
    }

    private Long creationDate;

    public Long getCreationDate() {
        return this.creationDate;
    }
}

Here is how I call it:

MyObjectInterface myObject = (MyObjectInterface)session.getAttribute("MY_OBJECT");

if (myObject == null || (myObject != null && myObject.hasExpired(null))) {
    session.setAttribute("MY_OBJECT", new myObjectImpl());
}
A: 

I think the simplest answer is that your constructor is getting called, and you don't think it is. Have you tried logging in the constructor?

hvgotcodes
+3  A: 

hasExpired returns true for young objects, it is the wrong way around:

if (getCreationDate() + millesecondsToExpiration.longValue() < new Date().getTime()) {
        return true;
    } else {
        return false;
    }

So you recreate the object each time.

starblue