简体   繁体   中英

Timed functions throw null pointer exception

Hi I am creating a class in which I can pass down functions to be called either periodicity or once off. . The problem is that my functions I am passing down gets called immediately, after that when they are suppose to be called I get the following error:

java.lang.NullPointerException
at TimedFunction$2.run(TimedFunction.java:41)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)

The Base class is as follow (only relivant sections):

import java.util.concurrent.Callable;
...

    public TimedFunction () {}

    public void addSingleEvent (Callable func, int seconds){
        //Convert to seconds from miliseconds
                int time = seconds * 1000;

                //Create a new timer
                new java.util.Timer().schedule( 
                        new java.util.TimerTask() {
                            @Override
                            public void run() {
                                try {
                                    func.call();
                                } catch (Exception e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }, 
                        time 
                );
    }

I then do a testing class that looks like this:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    TimedFunction tm = new TimedFunction();

    tm.addSingleEvent(helloWorld(), 5);
    tm.addRepeatedEvent(dataWorld(), 1);
}

private static Callable helloWorld() {
    System.out.print("Hello world!");
    System.out.print(" ");
    return null;
}

Check your helloWorld method - it's returning null!

I think it needs to be something like

private static Callable helloWorld() {
    return new Callable<String>() {
        return "Hello world";
    }
}

If I had to guess, I think you're getting confused with how to use lambas. If that's the case, your syntax is wrong, it should be like this:

tm.addSingleEvent(() -> "hello world", 5);
tm.addRepeatedEvent(() -> "data world", 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM