Proyb2
Proyb2

Reputation: 993

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(sequencer != null) {
            System.out.println("sec"+sequencer.getMicrosecondPosition()/1000000);
            timer = null;
            tick(1);
        } else {
            timer.cancel();
        }
    }
}

Upvotes: 2

Views: 3532

Answers (2)

ColinD
ColinD

Reputation: 110094

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.

Upvotes: 6

asela38
asela38

Reputation: 4654

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

Upvotes: 3

Related Questions