Note that there are some explanatory texts on larger screens.

plurals
  1. POResettable timer performance in Java
    text
    copied!<p>When profiling my app, I found a source of frequent allocations... I am utilizing multiple timers to check for timeouts (~2ms, varies with app state).</p> <p>According to <a href="https://stackoverflow.com/a/32057/884677">this SO answer</a>, <code>ScheduledThreadPoolExecutor</code> is preferable to <code>Timer</code>. So, I made class very similar to <a href="https://stackoverflow.com/a/2142661/884677">this other SO answer</a> that schedules tasks as recommended. I use it like so:</p> <pre><code>private final ResettableTimer timer = new ResettableTimer(new Runnable() { public void run() { //timeout, do something } }); timer.reset(2, TimeUnit.MILLISECONDS); </code></pre> <p>I found that every time a task is scheduled, java allocates the following:</p> <p><code>java.util.concurrent.LinkedBlockingQueue$Node</code> - 16 bytes <code>java.util.concurrent.Executors$RunnableAdapter</code> - 16 bytes <code>java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask</code> - 64 bytes <code>java.util.concurrent.locks.AbstractQueuedSynchronizer$node</code> - 28 bytes</p> <p>For example: 2 timers at 500 tasks/s = 124kB/s</p> <p>This is small, but it causes very frequent garbage collection. It doesn't seem to be causing me problems right now, although it may be the cause of some stuttering I'm seeing on older devices. Should I be worried? </p> <p>More importantly, these allocations seem pretty unnecessary since these tasks are doing the same thing over &amp; over again. Is there any way to avoid this re-allocation?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload