ManagedBlocker Unblocks Pool Work

Wrap a blocking call in a ManagedBlocker so the common ForkJoinPool spawns compensation threads instead of starving queued parallel work.

JavaResilience

Code

snippet
import java.util.concurrent.ForkJoinPool;

public class BlockedParallelWork {

    public static void main(String[] args) {
        int parallelism = ForkJoinPool.getCommonPoolParallelism();
        System.out.println("common pool parallelism: " + parallelism);

        // 托管阻塞:managedBlock 会先补偿新线程再放行阻塞体
        ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker() {
            private boolean done = false;

            @Override
            public boolean block() {
                try {
                    Thread.sleep(200); // 模拟一次慢速外部调用
                    System.out.println("blocking section finished on "
                            + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                done = true;
                return true; // true 表示 block() 返回后不再阻塞
            }

            @Override
            public boolean isReleasable() {
                return done;
            }
        });

        System.out.println("pool kept draining while one worker parked");
    }
}

What the code does

ManagedBlocker Unblocks Pool Work is built around the class BlockedParallelWork and the functions main, block and isReleasable.

Applying it

Running the file prints labeled results such as common pool parallelism:, blocking section finished on, pool kept draining while one worker parked — each operation’s effect is visible in the output.

main sequences block and isReleasable; executing the file runs that flow once.

Statements that matter

return true; // true 表示 block() 返回后不再阻塞
}
Thread.currentThread().interrupt();
Thread.sleep(200); // 模拟一次慢速外部调用
System.out.println("blocking section finished on "
+ Thread.currentThread().getName());

Interactive Tools for This Topic

FAQ

What does ManagedBlocker Unblocks Pool Work print when run?
Invoke the file as-is — the `common pool parallelism:`, `blocking section finished on`, `pool kept draining while one worker parked` prefixes identify which step printed each line.