Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object init() and the Timer class

I was just writing some code, and it occurred to me. I am creating a Timer object and scheduling a repeating task via timer.scheduleAtFixedRate(...).

public class MyClass {
  ..
  public MyClass() {
    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            doStuffEachSecond();
        }
    }, (long)0, (long)1000);
    // more stuff
  }

Now, doStuffEachSecond() is an instance method on MyClass. Since my initial delay is zero, and there is more stuff that goes on in the constructor after my Timer is set up, how do I know that the first invocation of my timer won't occur before object initialization is complete? Or might that potentially be the case (which would of course not be good)?

For now my solution is that my timer's setup is the final step of the constructor, but that seems iffy at best. Any wisdom regarding this issue?

like image 511
fragorl Avatar asked Jul 18 '26 13:07

fragorl


1 Answers

If you really want to insure that MyClass is fully initialized before the timer starts, you can do the initialization and the timer start in two steps:

final MyClass myMlass = new MyClass();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
      myclass.doStuffEachSecond();
  }
}, 0L, 1000L);

Edit

After thinking about it, putting the above in a static factory method would be by far the best solution:

public class MyClass {
  private MyClass() { /* do stuff */ }
  public static MyClass createNew() {
    MyClass myClass = new MyClass();
    myClass.startRunning();
  }   
  private void startRunning() {
    new Timer(true).scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            doStuffEachSecond();
        }   
    }, 0L, 1000L);
  }   
}

This does everything you want. The only way to create a new MyClass is via its factory method, and whenever a new one is created its timer is started after it's initialized.

like image 94
Tim Pote Avatar answered Jul 20 '26 02:07

Tim Pote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!