Android timers leak
<p>In my application I'm trying to have particles emanating from possibly multiple touch locations.</p>

<p>I have a class for storing a point and an associated timer:</p>

<pre><code>private static class Touch
{
    public Timer timer = new Timer();
    public vec position = new vec();
}
</code></pre>

<p>Inside the onTouchEvent, in case of MotionEvent.ACTION_POINTER_DOWN I instance a new Touch:</p>

<pre><code>Touch t = new Touch();
t.position = new vec(event.getX(id), event.getY(id));
t.timer.scheduleAtFixedRate(new TimeredTouchTask(t.position, id), 0, SHOOTING_INTERVAL);
</code></pre>

<p>and store it inside a map, using the touch id as key.</p>

<p>If MotionEvent.ACTION_POINTER_UP gets fired I remove the touch by calling cancel() on the timer and by removing it from the map.</p>

<p>Finally, if the event is of type MotionEvent.ACTION_MOVE I simply iterate all the Touch instances inside the map and update the vector coordinates.</p>

<p>This works but sometimes timers won't get removed correctly, sometimes they are kept alive doing nothing and sometimes they keep on actually shooting particles even if I stopped touching the screen.</p>

<p>How could I make this code more robust so it will always behave correctly?</p>

<p>edit1: the code of ACTION_POINTER_UP</p>

<p>I call this method</p>

<pre><code>private void removeTouch(int id)
{
    Touch t = _touch.get(id);

    if(t != null)
    {
        if(t.timer != null)
        {
            t.timer.cancel();
            t.timer = null;
        }

        t = null;
        _touch.remove(id);
    }
}
</code></pre>

<p>edit2: the full listing <a href="http://pastebin.com/yjd1WwhH" rel="nofollow">LINK</a></p>

<p>By examining some logs I found out that for example:
Touch finger #1
Touch finger #2
Touch finger #3
Release finger #3
Release finger #2
Release finger #1</p>

<p>is ok but doing:</p>

<p>Touch finger #1
Touch finger #2
Touch finger #3
Release finger #1
Release finger #2
Release finger #3</p>

<p>leaks the last timer. I think I'm definitively messing with id's and indexes.</p>
