Is a thread from ThreadPool always available right after return in Java?

Viewed 56

I need to take a thread from the ThreadPoolExecutor if one is free, otherwise I save the data for later (the ThreadPool has a 0-sized queue). In the following code:

ThreadPoolExecutor executor = new ThreadPoolExecutor(n, n,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
Object lock = new Object();

// ...

executor.execute(() -> {
    // ...
    synchronized(lock) {
        // ...
        if (...) {
            return;
        }
    }
    // ...
});

// ...

synchronized(lock) {
    if (executor.getCorePoolSize() - executor.getActiveCount() > 0) {
        // ...
    } else {
        // ...
    }
}

Can I be certain that the thread is considered not active once return statement is reached ? Can the process pause for any reason leading to the situation where:

  • return is done, thus lock is free (but thread still active)
  • we check for free threads and find out there is none
  • thread's run() method terminates (thread is now free)

In other words, can it take time for the process to go from the end of the first synchronized block's return to the end of the Runnable (even if there is no statement in-between) ?

0 Answers
Related