Question

I am trying to implement a cached thread pool in Java to read data coming in off of a bus. Everything works great... so long as I have data coming in on that bus.

If I leave the data cable disconnected, the program starts generating endless threads from the pool. I intermittently check /proc/{PID}/fd and it goes from 8 to 100+ in about an hour. Eventually the system crashes.

I am submitting a timeout value for these threads (30 seconds) and they do trigger a TimeoutException Catch which I see in my log file. Shouldn't these threads be ending when they time out?

Some code:

private static ExecutorService executorService = Executors.newCachedThreadPool();

(I later supply a callable)

long[] rawFrame;
Future<long[]> future = executorService.submit(callable);
try {
    rawFrame = future.get(timeout, timeUnit); // timeout is 30 seconds
    // Do some things with the raw frame and store as parsedFrame
    return parsedFrame;
} catch (TimeoutException e) {
    LOGGER.error("Bus timeout. Check connection");
    return null;
} finally {
    future.cancel(true);
}

I am just learning how to do concurrent processing in Java but as far as I know, these processes should be timing out but instead it appears they just sit there waiting for data on a bus that isn't spitting data.

What am I missing?

EDIT: Thanks for helping me narrow it down.

Here is my callable

private class BusCallable implements Callable<long[]> {

private long messageId;
private boolean readAnyFrame = false;

public BusCallable() {
    super();
    readAnyFrame = true;
}

public BusCallable(long id) {
    super();
    this.messageId = id;
    readAnyFrame = false;
}

@Override
public long[] call() throws Exception() {
    if (readAnyFrame) {
        return read(busInterface);
    }
    return readFrame(busInterface, messageId);
 }
Was it helpful?

Solution

Calling Future.get() with a timeout will timeout the get(), not the thread (ie.whataver is in the callable's call() method). If your callable doesn't end, it will remain in the service and callables will accumulate if you keep adding more. It's in the callable's thread that you should put a timeout mechanism in place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top