开发者

timer uses large amount of memory

For my MIDI player, I wanted to print 10 times in a second to get an accuracy of the timing but, the program consume quite a large amount of memory, how do I fix the code?

public void tick(int seconds) {
    timer = new Timer();
    timer.schedule(new tickcount(), seconds * 100);
}

class tickcount extends TimerTask {
    public void run() {
        if(sequence开发者_如何学编程r != null) {
            System.out.println("sec"+sequencer.getMicrosecondPosition()/1000000);
            timer = null;
            tick(1);
        } else {
            timer.cancel();
        }
    }
}


I don't really see how this code could be causing any kind of large memory consumption, unless it has to do with the incredible rate at which it'll be creating new threads.

At any rate, you should use a ScheduledExecutorService... Timer is kind of outdated (though even using it, you shouldn't be creating a new Timer each time your task runs). If you want the code in your tickcount task to run once every 0.1 seconds, you could do it like this:

private final ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

private Future<?> timingTask;

public void tick(long milliseconds) {
  timingTask = scheduler.scheduleAtFixedRate(new Runnable() {
    public void run() {
      System.out.println("sec"+sequencer.getMicrosecondPosition()/1000000);
    }
  }, 0, milliseconds, TimeUnit.MILLISECONDS);
}

Here, the tick method will start your timer running, calling the Runnable every milliseconds ms, starting immediately. It also assigns a Future<?> to a field... this allows you to call timingTask.cancel(true) to cancel the scheduled task from running prior to setting sequencer to null.


Other than creating Timer object every time in tick() method call use a global timer object instance and reuse it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜