Self expiring object - any better alternative

java

Solution

Each Timer creates a thread and this is a very expensive object. I suggest you just have the expiry time in the object and have a thread which periodically removes expired objects.

public class ExpiringObject {

    private long expiresMS;
    // other properties

    public void setValidity(final int seconds) {
        expiresMS = System.currentTimeMillis() + seconds * 1000;
    }

    public boolean isExpired() {
        return System.currentTimeMillis() >= expireMS;
    }
}

The thread which monitors these items can update Drools when it has expired.

Problem

Please find below the class that I have created and intend to use as a self-expiring object. ``` public class SelfExpiringObject { private boolean expired; // other properties public void setValidity(final int seconds) { new Timer().schedule(new TimerTask() { public void run() { expired = true; } }, TimeUnit.SECONDS.toMillis(seconds)); } public boolean isExpired() { return expired; } } ``` Any better alternative that anybody can suggest? Want to use this in a rule engine for processing events. One of the scenarios would be when the events are received, they are put into the session (using object with self-expiring property). I want them to be in the session only as per the validity set up in the rules. Once they expire, they would be removed from the session.

Original source