I have implemented a token system which assigns a fixed number of tokens. Each token on assignment starts up a Timer which expires after a few number of minutes and clears that token slot for reuse. If the user validates the token before the timer expires the Timer is supposed to be cancelled and reset with another token validity period. I seem to be unable to cancel the timer from outside the timer thread, is this behaviour expected. Snippets follow:
/**
* Fills one of the available slots with a new session key
* @param sessionKey
* @return true on slot fill success - false on fail
*/
public boolean fillSlot(String sessionKey)
{
if(count<MAXCOUNT)
{
//Add key to slot
slots.add(sessionKey);
//Up the key count
upCount();
//Set up expiry timer
Timer timer = new Timer();
timer.schedule(new ExpiringTokentask(timer,sessionKey), EXPIRY_TIME);
timers.put(sessionKey, timer);
return true;
}
return false;
}
/**
* Check if a given key is stored in the slots
* reset timer every time key is checked
* @param sessionKey
* @return true on key found false on not found
*/
public boolean checkSlot(String sessionKey)
{
//TODO: More efficient key search and storage for larger user sets
//TODO: Upgrade from memory array to h2 embedded DB
for(int i=0;i<slots.size();i++)
{
if(sessionKey.equals(slots.get(i)))
{
//Reset timer
Timer timer = timers.get(sessionKey);
//Can't seem to do this
// timer.cancel();
timer.schedule(new ExpiringTokentask(timer,sessionKey), EXPIRY_TIME);
//Return token validation
return true;
}
}
return false;
}
private class ExpiringTokentask extends TimerTask
{
private Timer timer;
private String expireToken;
public ExpiringTokentask(Timer timer, String sessionKey)
{
this.timer = timer;
this.expireToken = sessionKey;
System.out.println(sessionKey);
}
public void run() {
System.out.format("Time's up!%n");
clearSlot(expireToken);
timer.cancel(); //Terminate the timer thread
}
}