Search code examples
javathreadpoolrunnablescheduledexecutorservice

ScheduledExecutorService - Task stops running


private ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(20);

I'm running a task

public void run() {
    if (queue.isEmpty()) return;

    ArrayDeque<Profile> current = new ArrayDeque<Profile>();
    this.queue.drainTo(current, 20);

    MySQLStatement statement = this.wrapper.prepare();

    while (!current.isEmpty()) {
        if (statement.isClosed()) return;

        Profile profile = current.poll();
        statement.addBatch(profile.getId().toString(), ProfileBuilder.toJson(profile));
    }

    statement.executeBatchAsync();
}

using a ScheduledExecutorService

pool.scheduleAtFixedRate(new VerboseRunnable(runnable = new MySQLRunnable(this)), 250, 50, TimeUnit.MILLISECONDS);  

The MySQLRunnable stops working after some runs with a full queue, but it runs more or less infinite when the queue is empty.
First i thought the stops could be because of silently caught exception, so i added the VerboseRunnable

public void run() {
    try {
        runnable.run();
    } catch (Throwable e) {
        System.err.println("Error in runnable!");
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

But it still stops running. Also the ScheduledFuture tells me that the task is neither done nor cancelled.

Any help would be nice.


Solution

  • You should always be careful to close resources as you use them, especially I/O resources like connections, statements, and result sets. In a pooled environment, you can very easily end up depleting the pool of connections, and subsequent tasks will end up blocking, waiting for a connection that may never be available (if you're lucky, depending on implementation etc, maybe connections will start closing themselves after a few minutes... or longer).