Cannot refer to a non-final variable inside an inner class defined in a different method

前端 未结 20 2220
一向
一向 2020-11-21 05:04

Edited: I need to change the values of several variables as they run several times thorugh a timer. I need to keep updating the values with every iteration through the timer

20条回答
  •  天涯浪人
    2020-11-21 05:50

    To avoid strange side-effects with closures in java variables referenced by an anonymous delegate must be marked as final, so to refer to lastPrice and price within the timer task they need to be marked as final.

    This obviously won't work for you because you wish to change them, in this case you should look at encapsulating them within a class.

    public class Foo {
        private PriceObject priceObject;
        private double lastPrice;
        private double price;
    
        public Foo(PriceObject priceObject) {
            this.priceObject = priceObject;
        }
    
        public void tick() {
            price = priceObject.getNextPrice(lastPrice);
            lastPrice = price;
        }
    }
    

    now just create a new Foo as final and call .tick from the timer.

    public static void main(String args[]){
        int period = 2000;
        int delay = 2000;
    
        Price priceObject = new Price();
        final Foo foo = new Foo(priceObject);
    
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                foo.tick();
            }
        }, delay, period);
    }
    

提交回复
热议问题