tags:

views:

111

answers:

2

I'm working on a Java project where I have created a class that looks like this (abridged version):

public class Daemon {
  private static Timer[] timerarray=null;
  private static Daemon instance=null;

  protected Daemon() {
    ArrayList<Timer> timers = new ArrayList<Timer>();
    Timer t = new Timer("My application");
    t.schedule(new Worker(), 10000,30000);
    timers.add(t);
    //...
    timerarray = timers.toArray(new Timer[]{});
  }
  public static Daemon getInstance() { 
    if(instance==null) instance=new Daemon(); 
    return instance;
  }
  public SomeClass getSomeValueFromWorker(int i) {
    if(timerarray==null || i>=timerarray.length) return null;
    /* 
     * **HOW TO ACCESS THE Worker INSTANCE IN THE Timer ARRAY HERE!? **
     */
    return theValue;
  }

  /////////////////////////////////////////////
  private class Worker extends TimerTask {
    public Worker() {}
    public void run() {
      // do some work
    }
    public SomeReturnClass someMethod(SomeType someParameter) {
      //
      return something;
    }
  }
  /////////////////////////////////////////////
}

I start this class, e.g. by invoking daemon.getInstance();.

However, I'd like to have some way to access the running task objects' methods (for example, for monitoring the objects' state). The Java class java.util.Timer does not seem to provide the means to access the running object, it just schedules the object instance extending TimerTask.

Are there ways to access the "running" object instanciated within a Timer? Do I have to subclass the Timer class with the appropriate methods to somehow access the instance (this "feels" strange, somehow)? I suppose someone might have done this before ... where can I find examples of this "procedure"?

Thank you in advance for your feedback.

A: 

Don't use Timer. The ScheduledExecutorService implementations are much better and provide the functionality you want with some extra work. See 409932 for some reasons why to avoid Timer.

scompt.com
A: 

In the Daemon constructor, you can collect the instances of Worker into some kind of collection, and add a getter for that collection. This requires increasing the access level to the inner Worker class, as well as making sure that Worker's methods are thread safe.

Another thing: Why do you create a new Timer per job? if your jobs finish quickly, and you don't have too many of them, consider registering all of them in a single Timer. As an alternative, use ScheduledThreadPoolExecutor, where you have a pool of threads of a size you choose.

Eyal Schneider
I create a new Timer per job because each job does a lot of things underneath. I omitted what I thought was irrelevant for my question.
jbatista