Timer already canceled

I have two timers for controlling inputs (en-queue) and output (dequeue) from the FIFO queue, but I continue to get an exception for dequeueing java.lang.IllegalStateException: The timer is already canceled. I cannot put a stop on the debug line, where it is alleged that a line 83 error occurs. I do not know what I am missing, so any help would be appreciated.

import java.util.Random; import java.util.Timer; import java.util.TimerTask; /** * RunSim */ public class RunSim { private double arrivalRate = 600; private double y; private Timer t; private Timer t2; private Queue fifoQueue; private long xy; private long fact = 10; private int count; private int pId; public RunSim() { Random r = new Random(); long n = System.currentTimeMillis(); r.setSeed(n); double i = r.nextDouble(); y = ((1 / arrivalRate) * (Math.log(i))); xy = (long) y; t = new Timer(); t2 = new Timer(); fifoQueue = new Queue(); count = 0; pId = 0; } public static void main() { RunSim rs = new RunSim(); rs.start(); } public void start() { class sendPacket extends TimerTask { public void run() { Packet p = new Packet(); p.setId(pId); fifoQueue.insert(p); p.setArrivalTime(); System.out.println("ID: " + p.getId() + " Arrival Time: " + p.getArrivalTime() / fact); pId++; } } class removePacket extends TimerTask { public void run() { fifoQueue.first().setDepartureTime(); System.out.println("ID: " + fifoQueue.first().getId() + " Departure Time: " + fifoQueue.first().getDepartureTime() / fact); fifoQueue.remove(); } } while (count < 1000) { long v = fact * (1 + Math.abs(xy)); t.schedule(new sendPacket(), 0, v); count++; t2.schedule(new removePacket(), 5, 5); } } } 
+6
source share
1 answer

Immediately after planning all the timers, you cancel them. This does not work like an ExecutorService , where you can schedule everything you need and then call shutdown - this actually cancels the timer and all scheduled tasks.

Another problem with your code is that you immediately call System.exit , preventing you from running scheduled tasks.

In addition to these problems, you can get a Timer already canceled exception if the previous task threw an exception. The exception will not be visible anywhere, but it will cancel the timer. Be sure to collapse timer tasks into a test catch-all statement.

+8
source

All Articles