How can I timeout the value of a variable to null when it's not updated in a specific interval of time in Java?

Rafael Muynarsk :

I have a class with set and get methods like the following:

public class MyClass {
    private Double variable = null;

    // set method
    public void setVariable(Double value){
        this.variable = value;
    }

    // get method
    public Double getVariable(){
        return this.variable;
    }
}

I'd like to make my set method in a way that it goes back to null if I don't update its value after a timeframe since it was settled. For example, let's say I create an instance of MyClass and use the method setVarible(2.2) inside it, if I don't update its value using the set method again inside 1 second I want it to go back to null. Is there any standard way of solving a problem like this in Java? What approach should I use to solve it?


Context:

I've thought of solving this problem declaring a global variable with a counter and always resetting the counter when the set method is run, but I got stuck because it would require asynchronous calls or threads for not stopping the main thread. Besides that, I didn't manage to make it work this way too and it seems like an overcomplicated solution to follow for a simple problem. I think the approach I'm trying to use is the wrong one to solve it.

Joachim Sauer :

You don't actually need to set the field to null actively, as long as it looks like you did on the outside (assuming of course that all access to the field goes through the appropriate getter):

public class MyClass {
    private static final long VARIABLE_FRESHNESS_THRESHOLD = 1 * 1000l;

    private Double variable = null;
    private long variableUpdateMillis = Long.MAX_VALUE;

    public void setVariable(Double value){
        this.variable = value;
        this.variableUpdateMillis = System.currentTimeMillis();
    }

    public Double getVariable(){
        if (System.currentTimeMillis() - this.variableUpdateMillis >= VARIABLE_FRESHNESS_THRESHOLD) {
          return null;
        }
        return this.variable;
    }
}

You can optimize that to avoid the currentTimeMillis() call if the last one already timed out (by setting the variable to null in the return null case and checking that first):

    public Double getVariable(){
        if (this.variable != null &&
            System.currentTimeMillis() - this.variableUpdateMillis >= VARIABLE_FRESHNESS_THRESHOLD) {
          this.variable = null;
        }
        return this.variable;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193607&siteId=1