0
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;
public class SecondsTimer{
     private ScheduledExecutorService timer;
     private int seconds=0;
     public SecondsTimer(){
          long second=1000;
          timer.scheduleAtFixedRate(new Runnable(){public void run(){seconds++;}},
                                    second, second, TimeUnit.MILLISECONDS);
     }
     public int getSeconds(){return seconds;}
}

In the above code, I am attempting to create code to count seconds as they pass. I'm getting a runtime error, NullPointerException for line 9. Is there an easier way to do this, or am I missing something obvious?

Insederec
  • 303
  • 1
  • 3
  • 10

1 Answers1

0

The problem is that you never set the variable timer, so it is null when you try to use it.

For guidance on how to instantiate the ScheduledExecutorService Interface, have a look at the docs.

You would have to set it before line 9, thus before you try to access it.


Side note: since you are working with multiple threads that all write-access one variable, you should also look into the concept of thread safety.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94