package org.warp.commonutils.concurrency.executor; import java.util.concurrent.Semaphore; import javax.annotation.Nonnull; public final class PermitReleasingRunnableDecorator extends RunnableDecorator { @Nonnull private final Runnable queueSizeUpdater; @Nonnull private final Semaphore semaphore; PermitReleasingRunnableDecorator(@Nonnull final Runnable task, @Nonnull final Runnable queueSizeUpdater, @Nonnull final Semaphore semaphoreToRelease) { super(task); this.queueSizeUpdater = queueSizeUpdater; this.semaphore = semaphoreToRelease; } @Override public void run() { try { queueSizeUpdater.run(); } finally { // however execution goes, release permit for next task this.semaphore.release(); super.run(); } } @Override public final String toString() { return String.format("%s[delegate='%s']", getClass().getSimpleName(), super.toString()); } }