1

Java init () and the Timer class

 2 years ago
source link: https://www.codesd.com/item/java-init-and-the-timer-class.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java init () and the Timer class

advertisements

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?


I would use something similar to what threads in Java do. Have a constructor, then call a method like start to begin the timer.

Resolving race issues here seems a bit overkill when you can just construct the object then immediately begin timing. If you have a Factory to create the objects this could be part of the construction process.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK