diff --git a/src/main/java/org/ice4j/ice/Agent.java b/src/main/java/org/ice4j/ice/Agent.java index 8b9d9e5..901bb9c 100644 --- a/src/main/java/org/ice4j/ice/Agent.java +++ b/src/main/java/org/ice4j/ice/Agent.java @@ -22,6 +22,7 @@ import java.io.*; import java.math.*; import java.net.*; import java.security.*; +import java.time.*; import java.util.*; import java.util.concurrent.*; import java.util.logging.*; @@ -121,7 +122,14 @@ public class Agent */ private static final ScheduledExecutorService agentTasksScheduler = ExecutorFactory.createCPUBoundScheduledExecutor( - "ice4j.Agent-", 60, TimeUnit.SECONDS); + "ice4j.Agent-timer-", 60, TimeUnit.SECONDS); + + /** + * The ExecutorService to execute Agent's tasks + */ + private static final ExecutorService agentTasksExecutor + = Executors.newCachedThreadPool( + new CustomizableThreadFactory("ice4j.Agent-executor-", true)); /** * Termination task which will be scheduled with timeout @@ -2685,7 +2693,7 @@ public class Agent /** * A class to schedule and perform Stun keep-alive checks */ - private final class StunKeepAliveRunner + private final class StunKeepAliveRunner extends PeriodicRunnable { private final long consentFreshnessInterval = Long.getLong( StackProperties.CONSENT_FRESHNESS_INTERVAL, @@ -2703,97 +2711,62 @@ public class Agent StackProperties.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS, DEFAULT_CONSENT_FRESHNESS_MAX_RETRANSMISSIONS); - /** - * The scheduled task which sends periodic STUN keep-alive checks. - */ - private ScheduledFuture stunKeepAliveFuture; + private int keepAliveSent = 0; - /** - * The object used to synchronize access to {@link #stunKeepAliveFuture}. - */ - private final Object stunKeepAliveFutureSyncRoot = new Object(); - - /** - * Execute STUN keep-alive checks - */ - private final Runnable runnableCheck = new Runnable() + StunKeepAliveRunner() { - @Override - public void run() - { - for (IceMediaStream stream : getStreams()) - { - for (Component component : stream.getComponents()) - { - for (CandidatePair pair : component.getKeepAlivePairs()) - { - if (pair != null) - { - if (performConsentFreshness) - { - connCheckClient.startCheckForPair( - pair, - originalConsentFreshnessWaitInterval, - maxConsentFreshnessWaitInterval, - consentFreshnessMaxRetransmissions); - } - else - { - connCheckClient - .sendBindingIndicationForPair(pair); - } - } - } - } - } + super(agentTasksScheduler, agentTasksExecutor); + } - if (!shouldRunStunKeepAlive()) - { - cancel(); - } + @Override + protected Duration getDelayUntilNextRun() + { + if (shouldRunStunKeepAlive()) + { + return Duration.ofMillis(keepAliveSent == 0 ? 0 : consentFreshnessInterval); } - }; + return Duration.ofMillis(-1); + } - /** - * Schedules execution of periodic task which performs - * STUN keep-alive checks - */ - void schedule() + @Override + protected void run() { - if (stunKeepAliveFuture == null) + try { - synchronized (stunKeepAliveFutureSyncRoot) - { - if (stunKeepAliveFuture == null) - { - logger.info("Starting periodic Stun Keep Alive."); - - stunKeepAliveFuture - = agentTasksScheduler.scheduleWithFixedDelay( - runnableCheck, - 0, - consentFreshnessInterval, - TimeUnit.MILLISECONDS); - } - } + sendKeepAlive(); + } + catch (Exception e) + { + logger.log(Level.WARNING, "Error while sending keep alive", e); } } - /** - * Cancel scheduled periodic task which performs - * STUN keep-alive checks - */ - void cancel() + private void sendKeepAlive() { - if (stunKeepAliveFuture != null) + ++keepAliveSent; + + for (IceMediaStream stream : getStreams()) { - synchronized (stunKeepAliveFutureSyncRoot) + for (Component component : stream.getComponents()) { - if (stunKeepAliveFuture != null) + for (CandidatePair pair : component.getKeepAlivePairs()) { - stunKeepAliveFuture.cancel(false); - stunKeepAliveFuture = null; - logger.info("Stop periodic Stun Keep Alive."); + if (pair != null) + { + if (performConsentFreshness) + { + connCheckClient.startCheckForPair( + pair, + originalConsentFreshnessWaitInterval, + maxConsentFreshnessWaitInterval, + consentFreshnessMaxRetransmissions); + } + else + { + connCheckClient + .sendBindingIndicationForPair(pair); + } + } } } } diff --git a/src/main/java/org/ice4j/util/PeriodicRunnable.java b/src/main/java/org/ice4j/util/PeriodicRunnable.java new file mode 100644 index 0000000..73e28fd --- /dev/null +++ b/src/main/java/org/ice4j/util/PeriodicRunnable.java @@ -0,0 +1,252 @@ +package org.ice4j.util; + +import java.time.*; +import java.util.concurrent.*; + +/** + * A base class for runnables which should be periodically executed on + * specified executor service. + * + * @author Yura Yaroshevich + */ +public abstract class PeriodicRunnable +{ + /** + * A timer to perform periodic scheduling of {@link #run()} execution + * on {@link #executor}'s thread. + */ + private final ScheduledExecutorService timer; + + /** + * An executor service to perform actual execution of {@link #run()}. + */ + private final ExecutorService executor; + + /** + * A synchronization object to synchronize scheduling, execution and + * cancellation of {@link #run()}. + */ + private final Object syncRoot = new Object(); + + /** + * Indicates if execution of {@link #run()} scheduled and should + * be further continued. + */ + private volatile boolean running = false; + + /** + * Store a reference to last runnable submitted to {@link #timer} + */ + private ScheduledFuture scheduledSubmit; + + /** + * Store a reference to last runnable submitted to {@link #executor} + */ + private Future submittedExecute; + + /** + * Create instance of {@link PeriodicRunnable} with specified timer and + * executor. + * @param timer an {@link ScheduledExecutorService} which is used to + * periodic triggering of {@link #run()} execution. + * @param executor an {@link ExecutorService} to perform actual execution + * of {@link #run()}. + */ + protected PeriodicRunnable( + ScheduledExecutorService timer, + ExecutorService executor) + { + if (timer == null) + { + throw new IllegalArgumentException("timer is null"); + } + if (executor == null) + { + throw new IllegalArgumentException("executor is null"); + } + this.timer = timer; + this.executor = executor; + } + + /** + * Get delay before next execution of {@link #run()}. + * @return non-negative value if execution of {@link #run()} should be + * performed with specified delay, negative value if execution should not + * be done. + */ + protected abstract Duration getDelayUntilNextRun(); + + /** + * Periodically executed method on {@link #executor}'s thread. + */ + protected abstract void run(); + + /** + * Schedules periodic execution of {@link #run()} on {@link #executor}'s + * thread. + */ + public void schedule() + { + if (running) + { + return; + } + + final Duration delay = + getDelayUntilNextRun(); + + scheduleNextRun(delay); + } + + /** + * Cancels periodic execution of {@link #run()} on {@link #executor}'s + * thread. + */ + public void cancel() + { + if (!running) + { + return; + } + + synchronized (syncRoot) + { + if (running) + { + running = false; + + if (scheduledSubmit != null) + { + scheduledSubmit.cancel(true); + scheduledSubmit = null; + } + + if (submittedExecute != null) + { + submittedExecute.cancel(true); + submittedExecute = null; + } + } + } + } + + /** + * Perform either cancellation or actual scheduling based on delay until + * next run. + * @param delay delay before next execution of {@link #run()}. + */ + private void scheduleNextRun(Duration delay) + { + synchronized (syncRoot) + { + final boolean isRecurrentRun = submittedExecute != null; + if (isRecurrentRun && !running) + { + // was cancelled + return; + } + + if (delay.isNegative()) + { + running = false; + scheduledSubmit = null; + submittedExecute = null; + return; + } + + running = true; + + if (delay.isZero()) + { + submitExecuteRun(); + } + else + { + scheduledSubmit = timer.schedule( + this::submitExecuteRun, + delay.toNanos(), + TimeUnit.NANOSECONDS); + } + } + } + + /** + * Submit execution of {@link #run()} into {@link #executor}'s thread + * if not cancelled. + */ + private void submitExecuteRun() + { + if (!running) + { + return; + } + synchronized (syncRoot) + { + if (!running) + { + return; + } + submittedExecute = this.executor.submit(this::executeRun); + } + } + + /** + * Perform execution of {@link #run()} with further re-schedule of + * execution if not cancelled + */ + private void executeRun() + { + if (!running) + { + return; + } + + try + { + this.run(); + } + finally + { + if (running) + { + final Duration delayMillis = + getDelayUntilNextRun(); + + scheduleNextRun(delayMillis); + } + } + } + + /** + * Constructs {@link PeriodicRunnable} for {@link Runnable} with provided + * timer, executor and fixed delay. + * fixed delay. + * @param timer {@link ScheduledExecutorService} to be used as timer + * @param executor {@link ExecutorService} to execute provided runnable + * @param period delay between subsequent execution of runnable + * @param r {@link Runnable} to for periodic execution. + * @return {@link PeriodicRunnable} instance constructed with provided + * arguments + */ + static PeriodicRunnable create( + ScheduledExecutorService timer, + ExecutorService executor, + Duration period, + Runnable r) + { + return new PeriodicRunnable(timer, executor) + { + @Override + protected Duration getDelayUntilNextRun() + { + return period; + } + + @Override + protected void run() + { + r.run(); + } + }; + } +} diff --git a/src/test/java/org/ice4j/util/PeriodicRunnableTests.java b/src/test/java/org/ice4j/util/PeriodicRunnableTests.java new file mode 100644 index 0000000..65e61cd --- /dev/null +++ b/src/test/java/org/ice4j/util/PeriodicRunnableTests.java @@ -0,0 +1,165 @@ +package org.ice4j.util; + +import org.junit.*; + +import java.time.*; +import java.util.concurrent.*; + +/** + * Test various aspects of {@link PeriodicRunnable} implementation. + * + * @author Yura Yaroshevich + */ +public class PeriodicRunnableTests +{ + @Test + public void scheduleExecutesSpecifiedRunnableMultipleTimes() + throws InterruptedException + { + final ScheduledExecutorService timer + = Executors.newSingleThreadScheduledExecutor(); + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch latch = new CountDownLatch(10); + final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( + timer, + executor, + Duration.ofMillis(100), + latch::countDown); + + scheduledRunnable.schedule(); + + // Give 20 extra milliseconds to avoid possible failures due to + // slight timer inaccuracy + latch.await(1020, TimeUnit.MILLISECONDS); + Assert.assertEquals(0, latch.getCount()); + + scheduledRunnable.cancel(); + executor.shutdownNow(); + timer.shutdownNow(); + } + + @Test + public void scheduleWithNegativeDelayDoesNotExecuteRunnable() + throws InterruptedException + { + final ScheduledExecutorService timer + = Executors.newSingleThreadScheduledExecutor(); + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch latch = new CountDownLatch(1); + final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( + timer, + executor, + Duration.ofMillis(-1), + latch::countDown); + + scheduledRunnable.schedule(); + + latch.await(1000, TimeUnit.MILLISECONDS); + Assert.assertEquals(1, latch.getCount()); + + scheduledRunnable.cancel(); + executor.shutdownNow(); + timer.shutdownNow(); + } + + @Test + public void negativeDelayStopsFurtherExecution() + throws InterruptedException + { + final ScheduledExecutorService timer + = Executors.newSingleThreadScheduledExecutor(); + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch latch = new CountDownLatch(5); + final PeriodicRunnable scheduledRunnable = + new PeriodicRunnable(timer, executor) + { + @Override + protected Duration getDelayUntilNextRun() + { + return Duration.ofMillis(latch.getCount() > 1 ? 100 : -1); + } + + @Override + protected void run() + { + latch.countDown(); + } + }; + + scheduledRunnable.schedule(); + + latch.await(1000, TimeUnit.MILLISECONDS); + Assert.assertEquals(1, latch.getCount()); + + scheduledRunnable.cancel(); + executor.shutdownNow(); + timer.shutdownNow(); + } + + @Test + public void cancelStopFurtherExecution() + throws InterruptedException + { + final ScheduledExecutorService timer + = Executors.newSingleThreadScheduledExecutor(); + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch latch = new CountDownLatch(2); + final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( + timer, + executor, + Duration.ofMillis(500), + latch::countDown); + + scheduledRunnable.schedule(); + latch.await(520, TimeUnit.MILLISECONDS); + + // Check runnable executed once + Assert.assertEquals(1, latch.getCount()); + + scheduledRunnable.cancel(); + + latch.await(1000, TimeUnit.MILLISECONDS); + // Check runnable was not executed after cancel. + Assert.assertEquals(1, latch.getCount()); + + scheduledRunnable.cancel(); + executor.shutdownNow(); + timer.shutdownNow(); + } + + @Test + public void scheduleExecuteRunnableIfPreviouslyCancelled() + throws InterruptedException + { + final ScheduledExecutorService timer + = Executors.newSingleThreadScheduledExecutor(); + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final CountDownLatch latch = new CountDownLatch(5); + final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( + timer, + executor, + Duration.ofMillis(200), + latch::countDown); + + scheduledRunnable.schedule(); + latch.await(220, TimeUnit.MILLISECONDS); + + // Check runnable executed once + Assert.assertEquals(4, latch.getCount()); + + scheduledRunnable.cancel(); + + latch.await(1000, TimeUnit.MILLISECONDS); + // Check runnable was not executed after cancel. + Assert.assertEquals(4, latch.getCount()); + + // Schedule again + scheduledRunnable.schedule(); + latch.await(1000, TimeUnit.MILLISECONDS); + Assert.assertEquals(0, latch.getCount()); + + scheduledRunnable.cancel(); + executor.shutdownNow(); + timer.shutdownNow(); + } +}