diff --git a/src/main/java/org/ice4j/ice/Agent.java b/src/main/java/org/ice4j/ice/Agent.java
index cabea59..d6d33d8 100644
--- a/src/main/java/org/ice4j/ice/Agent.java
+++ b/src/main/java/org/ice4j/ice/Agent.java
@@ -29,6 +29,7 @@ import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.stack.*;
+import org.ice4j.util.*;
import org.ice4j.util.Logger; // Disambiguation.
/**
@@ -116,17 +117,20 @@ public class Agent
= "IceProcessingState";
/**
- * The ScheduledExecutorService to execute planned agent termination
+ * The ScheduledExecutorService to execute Agent's scheduled tasks
*/
- private static final ScheduledExecutorService agentTerminationScheduler;
+ private static final ScheduledExecutorService agentTasksScheduler;
static
{
+ CustomizableThreadFactory threadFactory
+ = new CustomizableThreadFactory("ice4j.Agent-", true);
+
final ScheduledThreadPoolExecutor terminationExecutor
- = new ScheduledThreadPoolExecutor(0);
+ = new ScheduledThreadPoolExecutor(0, threadFactory);
terminationExecutor.setKeepAliveTime(10, TimeUnit.SECONDS);
terminationExecutor.setRemoveOnCancelPolicy(true);
- agentTerminationScheduler
+ agentTasksScheduler
= Executors.unconfigurableScheduledExecutorService(
terminationExecutor);
}
@@ -147,6 +151,12 @@ public class Agent
}
};
+ /**
+ * An instance to schedule STUN checks for selected pair.
+ */
+ private final StunKeepAliveRunner stunKeepAliveRunner
+ = new StunKeepAliveRunner();
+
/**
* The LinkedHashMap used to store the media streams
* This map preserves the insertion order of the media streams.
@@ -288,11 +298,6 @@ public class Agent
*/
private final Object terminationFutureSyncRoot = new Object();
- /**
- * The thread that we use for STUN keep-alive.
- */
- private Thread stunKeepAliveThread;
-
/**
* Some protocols, such as XMPP, need to be able to distinguish the separate
* ICE sessions that occur as a result of ICE restarts, which is why we need
@@ -1975,14 +1980,7 @@ public class Agent
// keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests)
- if (stunKeepAliveThread == null
- && !StackProperties.getBoolean(
- StackProperties.NO_KEEP_ALIVES,
- false))
- {
- // schedule STUN checks for selected candidates
- scheduleStunKeepAlive();
- }
+ scheduleStunKeepAlive();
scheduleTermination();
@@ -2210,7 +2208,7 @@ public class Agent
if (terminationDelay > 0)
{
terminationFuture
- = agentTerminationScheduler.schedule(
+ = agentTasksScheduler.schedule(
terminationRunnable,
terminationDelay,
TimeUnit.MILLISECONDS);
@@ -2229,26 +2227,21 @@ public class Agent
}
/**
- * Initializes and starts the background Thread which is to send
- * STUN keep-alives once this Agent is COMPLETED.
+ * Schedules repeated background task which sends STUN keep-alives
+ * once this Agent is COMPLETED.
*/
private void scheduleStunKeepAlive()
{
- if (stunKeepAliveThread == null)
+ boolean noKeepAlives
+ = StackProperties.getBoolean(
+ StackProperties.NO_KEEP_ALIVES,
+ false);
+ if (noKeepAlives || !stunKeepAliveRunner.shouldRunStunKeepAlive())
{
- stunKeepAliveThread
- = new Thread()
- {
- @Override
- public void run()
- {
- runInStunKeepAliveThread();
- }
- };
- stunKeepAliveThread.setDaemon(true);
- stunKeepAliveThread.setName("StunKeepAliveThread");
- stunKeepAliveThread.start();
+ return;
}
+
+ stunKeepAliveRunner.schedule();
}
@@ -2359,8 +2352,7 @@ public class Agent
shutdown = true;
//stop sending keep alives (STUN Binding Indications).
- if (stunKeepAliveThread != null)
- stunKeepAliveThread.interrupt();
+ stunKeepAliveRunner.cancel();
// cancel termination timer in case agent is freed
// before termination timer is triggered
@@ -2441,89 +2433,6 @@ public class Agent
this.generation = generation;
}
- /**
- * Schedule STUN checks for selected pair.
- */
- private void runInStunKeepAliveThread()
- {
- long consentFreshnessInterval = Long.getLong(
- StackProperties.CONSENT_FRESHNESS_INTERVAL,
- DEFAULT_CONSENT_FRESHNESS_INTERVAL);
-
- int originalConsentFreshnessWaitInterval = Integer.getInteger(
- StackProperties.CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL,
- DEFAULT_CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL);
-
- int maxConsentFreshnessWaitInterval = Integer.getInteger(
- StackProperties.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL,
- DEFAULT_CONSENT_FRESHNESS_MAX_WAIT_INTERVAL);
-
- int consentFreshnessMaxRetransmissions = Integer.getInteger(
- StackProperties.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS,
- DEFAULT_CONSENT_FRESHNESS_MAX_RETRANSMISSIONS);
-
- while (runInStunKeepAliveThreadCondition())
- {
- 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);
- }
- }
- }
- }
- }
-
- if (!runInStunKeepAliveThreadCondition())
- {
- break;
- }
-
- try
- {
- Thread.sleep(consentFreshnessInterval);
- Thread.yield();
- }
- catch(InterruptedException e)
- {
- }
- }
- logger.info(Thread.currentThread().getName() + " ends.");
- }
-
- /**
- * Determines whether {@link #runInStunKeepAliveThread()} is to run.
- *
- * @return true if runInStunKeepAliveThread() is to run;
- * otherwise, false
- */
- private boolean runInStunKeepAliveThreadCondition()
- {
- IceProcessingState state = this.state;
-
- return
- (IceProcessingState.COMPLETED.equals(state)
- || IceProcessingState.TERMINATED.equals(state))
- && !shutdown;
- }
-
/**
* Returns the selected pair for the RTP component for the ICE media stream
* with name streamName of this Agent, or null.
@@ -2784,4 +2693,138 @@ public class Agent
{
return logger;
}
+
+ /**
+ * A class to schedule and perform Stun keep-alive checks
+ */
+ private final class StunKeepAliveRunner
+ {
+ private final long consentFreshnessInterval = Long.getLong(
+ StackProperties.CONSENT_FRESHNESS_INTERVAL,
+ DEFAULT_CONSENT_FRESHNESS_INTERVAL);
+
+ private final int originalConsentFreshnessWaitInterval = Integer.getInteger(
+ StackProperties.CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL,
+ DEFAULT_CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL);
+
+ private final int maxConsentFreshnessWaitInterval = Integer.getInteger(
+ StackProperties.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL,
+ DEFAULT_CONSENT_FRESHNESS_MAX_WAIT_INTERVAL);
+
+ private final int consentFreshnessMaxRetransmissions = Integer.getInteger(
+ StackProperties.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS,
+ DEFAULT_CONSENT_FRESHNESS_MAX_RETRANSMISSIONS);
+
+ /**
+ * The scheduled task which sends periodic STUN keep-alive checks.
+ */
+ private ScheduledFuture> stunKeepAliveFuture;
+
+ /**
+ * 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()
+ {
+ @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);
+ }
+ }
+ }
+ }
+ }
+
+ if (!shouldRunStunKeepAlive())
+ {
+ cancel();
+ }
+ }
+ };
+
+ /**
+ * Schedules execution of periodic task which performs
+ * STUN keep-alive checks
+ */
+ void schedule()
+ {
+ if (stunKeepAliveFuture == null)
+ {
+ synchronized (stunKeepAliveFutureSyncRoot)
+ {
+ if (stunKeepAliveFuture == null)
+ {
+ logger.info("Starting periodic Stun Keep Alive.");
+
+ stunKeepAliveFuture
+ = agentTasksScheduler.scheduleWithFixedDelay(
+ runnableCheck,
+ 0,
+ consentFreshnessInterval,
+ TimeUnit.MILLISECONDS);
+ }
+ }
+ }
+ }
+
+ /**
+ * Cancel scheduled periodic task which performs
+ * STUN keep-alive checks
+ */
+ void cancel()
+ {
+ if (stunKeepAliveFuture != null)
+ {
+ synchronized (stunKeepAliveFutureSyncRoot)
+ {
+ if (stunKeepAliveFuture != null)
+ {
+ stunKeepAliveFuture.cancel(false);
+ stunKeepAliveFuture = null;
+ logger.info("Stop periodic Stun Keep Alive.");
+ }
+ }
+ }
+ }
+
+ /**
+ * Determines whether {@link #stunKeepAliveRunner} should run.
+ *
+ * @return true if {@link #stunKeepAliveRunner}
+ * should run otherwise, false
+ */
+ boolean shouldRunStunKeepAlive()
+ {
+ IceProcessingState state = Agent.this.state;
+
+ return
+ (IceProcessingState.COMPLETED.equals(state)
+ || IceProcessingState.TERMINATED.equals(state))
+ && !shutdown;
+ }
+ }
}
diff --git a/src/main/java/org/ice4j/util/CustomizableThreadFactory.java b/src/main/java/org/ice4j/util/CustomizableThreadFactory.java
new file mode 100644
index 0000000..3d2b913
--- /dev/null
+++ b/src/main/java/org/ice4j/util/CustomizableThreadFactory.java
@@ -0,0 +1,56 @@
+/*
+ * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
+ *
+ * Copyright @ 2018 Jitsi.org
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.ice4j.util;
+
+import java.util.concurrent.*;
+
+/**
+ * A thread factory which supports customizing name prefix of created threads
+ * and if produced threads are daemons or not.
+ */
+public final class CustomizableThreadFactory implements ThreadFactory
+{
+ private final ThreadFactory defaultThreadFactory
+ = Executors.defaultThreadFactory();
+
+ private final String threadNamePrefix;
+
+ private final boolean isDaemon;
+
+ public CustomizableThreadFactory(String threadNamePrefix, boolean isDaemon)
+ {
+ this.threadNamePrefix = threadNamePrefix;
+ this.isDaemon = isDaemon;
+ }
+
+ @Override
+ public Thread newThread(Runnable r)
+ {
+ Thread thread = this.defaultThreadFactory.newThread(r);
+ if (this.threadNamePrefix != null && !threadNamePrefix.isEmpty())
+ {
+ thread.setName(this.threadNamePrefix + thread.getName());
+ }
+ if (thread.isDaemon() != this.isDaemon)
+ {
+ thread.setDaemon(this.isDaemon);
+ }
+ return thread;
+ }
+}