Reduce number of threads created by ice4j. Eliminate StunKeepAliveThread. (#151)

* Use ScheduleExecutorService to run STUN keep alives.

* Mark threads as daemon threads.

* Fixed comments. Rearranged properties read in keep alive runnable.

* Added early check that keep alives must not be sent

* Renamed method to check keep alive condition.

* Fixed formatting.

* Renamed metrod which check if KA should run.

* Created CustomizableThreadFactory which support thread name prefixes and if threads are daemons.

* Created dedicated runnable class which perform STUN keep-alive checks.

* Minor comments fixes.

* Do not expose Runnable interface from StunKeepAliveRunner.

* Mark CustomizableThreadFactory fields as final.

* Added java doc to CustomizableThreadFactory
This commit is contained in:
Yury Yaroshevich 2018-10-30 02:47:20 +03:00 committed by bbaldino
parent ba7e30c189
commit 6bed63795f
2 changed files with 217 additions and 118 deletions

View File

@ -29,6 +29,7 @@ import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.harvest.*; import org.ice4j.ice.harvest.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.*;
import org.ice4j.util.Logger; // Disambiguation. import org.ice4j.util.Logger; // Disambiguation.
/** /**
@ -116,17 +117,20 @@ public class Agent
= "IceProcessingState"; = "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 static
{ {
CustomizableThreadFactory threadFactory
= new CustomizableThreadFactory("ice4j.Agent-", true);
final ScheduledThreadPoolExecutor terminationExecutor final ScheduledThreadPoolExecutor terminationExecutor
= new ScheduledThreadPoolExecutor(0); = new ScheduledThreadPoolExecutor(0, threadFactory);
terminationExecutor.setKeepAliveTime(10, TimeUnit.SECONDS); terminationExecutor.setKeepAliveTime(10, TimeUnit.SECONDS);
terminationExecutor.setRemoveOnCancelPolicy(true); terminationExecutor.setRemoveOnCancelPolicy(true);
agentTerminationScheduler agentTasksScheduler
= Executors.unconfigurableScheduledExecutorService( = Executors.unconfigurableScheduledExecutorService(
terminationExecutor); 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 * The LinkedHashMap used to store the media streams
* This map preserves the insertion order of 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(); 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 * 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 * 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 // keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests) // indications or requests)
if (stunKeepAliveThread == null scheduleStunKeepAlive();
&& !StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES,
false))
{
// schedule STUN checks for selected candidates
scheduleStunKeepAlive();
}
scheduleTermination(); scheduleTermination();
@ -2210,7 +2208,7 @@ public class Agent
if (terminationDelay > 0) if (terminationDelay > 0)
{ {
terminationFuture terminationFuture
= agentTerminationScheduler.schedule( = agentTasksScheduler.schedule(
terminationRunnable, terminationRunnable,
terminationDelay, terminationDelay,
TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS);
@ -2229,26 +2227,21 @@ public class Agent
} }
/** /**
* Initializes and starts the background <tt>Thread</tt> which is to send * Schedules repeated background task which sends STUN keep-alives
* STUN keep-alives once this <tt>Agent</tt> is <tt>COMPLETED</tt>. * once this <tt>Agent</tt> is <tt>COMPLETED</tt>.
*/ */
private void scheduleStunKeepAlive() private void scheduleStunKeepAlive()
{ {
if (stunKeepAliveThread == null) boolean noKeepAlives
= StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES,
false);
if (noKeepAlives || !stunKeepAliveRunner.shouldRunStunKeepAlive())
{ {
stunKeepAliveThread return;
= new Thread()
{
@Override
public void run()
{
runInStunKeepAliveThread();
}
};
stunKeepAliveThread.setDaemon(true);
stunKeepAliveThread.setName("StunKeepAliveThread");
stunKeepAliveThread.start();
} }
stunKeepAliveRunner.schedule();
} }
@ -2359,8 +2352,7 @@ public class Agent
shutdown = true; shutdown = true;
//stop sending keep alives (STUN Binding Indications). //stop sending keep alives (STUN Binding Indications).
if (stunKeepAliveThread != null) stunKeepAliveRunner.cancel();
stunKeepAliveThread.interrupt();
// cancel termination timer in case agent is freed // cancel termination timer in case agent is freed
// before termination timer is triggered // before termination timer is triggered
@ -2441,89 +2433,6 @@ public class Agent
this.generation = generation; 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 <tt>true</tt> if <tt>runInStunKeepAliveThread()</tt> is to run;
* otherwise, <tt>false</tt>
*/
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 * Returns the selected pair for the RTP component for the ICE media stream
* with name <tt>streamName</tt> of this Agent, or <tt>null</tt>. * with name <tt>streamName</tt> of this Agent, or <tt>null</tt>.
@ -2784,4 +2693,138 @@ public class Agent
{ {
return logger; 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 <tt>true</tt> if <tt>{@link #stunKeepAliveRunner}</tt>
* should run otherwise, <tt>false</tt>
*/
boolean shouldRunStunKeepAlive()
{
IceProcessingState state = Agent.this.state;
return
(IceProcessingState.COMPLETED.equals(state)
|| IceProcessingState.TERMINATED.equals(state))
&& !shutdown;
}
}
} }

View File

@ -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;
}
}