Reduce number of threads created by ice4j. Eliminate ICE PaceMaker thread & Timer. (#152)

* Eliminate "ICE PaceMaker" thread & Timer inside ConnectivityCheckClient.

* Fixed PaceMaker stop and cleaning.

* Added braces to have explicit blocks for one-liners if/else.
This commit is contained in:
Yury Yaroshevich 2018-10-31 02:11:48 +03:00 committed by bbaldino
parent 6bed63795f
commit 3fe34dcb97
2 changed files with 150 additions and 137 deletions

View File

@ -383,7 +383,7 @@ public class Agent
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
connCheckServer = new ConnectivityCheckServer(this); connCheckServer = new ConnectivityCheckServer(this);
connCheckClient = new ConnectivityCheckClient(this); connCheckClient = new ConnectivityCheckClient(this, agentTasksScheduler);
//add the FINGERPRINT attribute to all messages. //add the FINGERPRINT attribute to all messages.
System.setProperty(StackProperties.ALWAYS_SIGN, "true"); System.setProperty(StackProperties.ALWAYS_SIGN, "true");

View File

@ -19,6 +19,8 @@ package org.ice4j.ice;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
@ -54,6 +56,11 @@ class ConnectivityCheckClient
*/ */
private final Agent parentAgent; private final Agent parentAgent;
/**
* A scheduled executor service to perform scheduled task of the client
*/
private final ScheduledExecutorService scheduledExecutorService;
/** /**
* The <tt>StunStack</tt> that we will use for connectivity checks. * The <tt>StunStack</tt> that we will use for connectivity checks.
*/ */
@ -62,13 +69,15 @@ class ConnectivityCheckClient
/** /**
* The {@link PaceMaker}s that are currently running checks in this client. * The {@link PaceMaker}s that are currently running checks in this client.
*/ */
private final List<PaceMaker> paceMakers = new LinkedList<>(); private final Queue<PaceMaker> paceMakers
= new ConcurrentLinkedQueue<>();
/** /**
* Timer that is used to let some seconds before a CheckList is considered * Timer that is used to let some seconds before a CheckList is considered
* as FAILED. * as FAILED.
*/ */
private Map<String, Timer> timers = new HashMap<>(); private ConcurrentMap<String, ScheduledFuture<?>>
checkListCompletionCheckers = new ConcurrentHashMap<>();
/** /**
* A flag that determines whether we have received a STUN response or not. * A flag that determines whether we have received a STUN response or not.
@ -86,10 +95,15 @@ class ConnectivityCheckClient
* information such as user fragments for example. * information such as user fragments for example.
* *
* @param parentAgent the <tt>Agent</tt> that is creating this instance. * @param parentAgent the <tt>Agent</tt> that is creating this instance.
* @param scheduledExecutorService the <tt>ScheduledExecutorService</tt>
* to execute clients tasks
*/ */
public ConnectivityCheckClient(Agent parentAgent) public ConnectivityCheckClient(
Agent parentAgent,
ScheduledExecutorService scheduledExecutorService)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
this.scheduledExecutorService = scheduledExecutorService;
logger = new Logger(classLogger, parentAgent.getLogger()); logger = new Logger(classLogger, parentAgent.getLogger());
stunStack = this.parentAgent.getStunStack(); stunStack = this.parentAgent.getStunStack();
@ -149,12 +163,8 @@ class ConnectivityCheckClient
public void startChecks(CheckList checkList) public void startChecks(CheckList checkList)
{ {
PaceMaker paceMaker = new PaceMaker(checkList); PaceMaker paceMaker = new PaceMaker(checkList);
synchronized (paceMakers)
{
paceMakers.add(paceMaker); paceMakers.add(paceMaker);
} paceMaker.schedule();
paceMaker.start();
} }
/** /**
@ -431,14 +441,12 @@ class ConnectivityCheckClient
if ( !stream.validListContainsAllComponents()) if ( !stream.validListContainsAllComponents())
{ {
final String streamName = stream.getName(); final String streamName = stream.getName();
Timer timer = timers.get(streamName); if (!checkListCompletionCheckers.containsKey(streamName))
if (timer == null)
{ {
logger.info("CheckList will failed in a few seconds if no" + logger.info("CheckList will failed in a few seconds" +
"succeeded checks come"); " if no succeeded checks come");
TimerTask task = new TimerTask() Runnable checkLickCompletedChecker = new Runnable()
{ {
@Override @Override
public void run() public void run()
@ -453,9 +461,20 @@ class ConnectivityCheckClient
} }
} }
}; };
timer = new Timer();
timers.put(streamName, timer); final ScheduledFuture<?> scheduledCheckerFuture
timer.schedule(task, 5000); = scheduledExecutorService.schedule(
checkLickCompletedChecker,
5000,
TimeUnit.MILLISECONDS);
final ScheduledFuture<?> existingCheckerFuture
= checkListCompletionCheckers
.putIfAbsent(streamName, scheduledCheckerFuture);
if (existingCheckerFuture != null)
{
scheduledCheckerFuture.cancel(false);
}
} }
} }
@ -847,106 +866,38 @@ class ConnectivityCheckClient
} }
/** /**
* The thread that actually sends the checks for a particular check list * A class to control periodically scheduled runnable that actually sends
* in the pace defined in RFC 5245. * the checks for a particular check list in the pace defined in RFC 5245.
*/ */
private class PaceMaker private final class PaceMaker
extends Thread
{ {
/** /**
* Indicates whether this <tt>Thread</tt> should still be running. * Indicates whether this <tt>Runnable</tt> should continue running.
*/ */
boolean running = true; private final AtomicBoolean cancelled = new AtomicBoolean();
/**
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running
* checks for.
*/
private final CheckList checkList;
/**
* Creates a new {@link PaceMaker} for this
* <tt>ConnectivityCheckClient</tt>.
*
* @param checkList the {@link CheckList} that we'll be sending checks
* for
*/
public PaceMaker(CheckList checkList)
{
super("ICE PaceMaker: " + parentAgent.getLocalUfrag());
this.checkList = checkList;
/*
* Because PaceMaker does not seem to be a daemon at least on Ubuntu
* in the run-sample target and it looks like it should be from the
* standpoint of the application, explicitly tell it to be a daemon.
* Otherwise, it could prevent the application from exiting because
* of a problem in the ICE implementation.
*/
setDaemon(true);
}
/**
* Returns the number milliseconds to wait before we send the next
* check.
*
* @return the number milliseconds to wait before we send the next
* check.
*/
private long getNextWaitInterval()
{
int activeCheckLists = parentAgent.getActiveCheckListCount();
if (activeCheckLists < 1)
{
//don't multiply by 0. even when we no longer have active check
//lists we may still have nomination checks to
activeCheckLists = 1;
}
return parentAgent.calculateTa() * activeCheckLists;
}
/** /**
* Sends connectivity checks at the pace determined by the {@link * Sends connectivity checks at the pace determined by the {@link
* Agent#calculateTa()} method and using either the trigger check queue * Agent#calculateTa()} method and using either the trigger check queue
* or the regular check lists. * or the regular check lists.
*/ */
private final Runnable connectivityChecker = new Runnable()
{
@Override @Override
public synchronized void run() public void run()
{ {
try if (cancelled.get())
{ {
while(running) return;
{
long waitFor = getNextWaitInterval();
if (waitFor > 0)
{
/*
* waitFor will be 0 for the first check since we won't
* have any active check lists at that point yet.
*/
try
{
wait(waitFor);
}
catch (InterruptedException e)
{
logger.log(Level.FINER, "PaceMaker got interrupted",
e);
}
if (!running)
break;
} }
CandidatePair pairToCheck = checkList.popTriggeredCheck(); CandidatePair pairToCheck = checkList.popTriggeredCheck();
//if there are no triggered checks, go for an ordinary one. //if there are no triggered checks, go for an ordinary one.
if (pairToCheck == null) if (pairToCheck == null)
{
pairToCheck = checkList.getNextOrdinaryPairToCheck(); pairToCheck = checkList.getNextOrdinaryPairToCheck();
}
if (pairToCheck != null) if (pairToCheck != null)
{ {
@ -970,9 +921,11 @@ class ConnectivityCheckClient
pairToCheck.setStateFailed(); pairToCheck.setStateFailed();
} }
else else
{
pairToCheck.setStateInProgress(transactionID); pairToCheck.setStateInProgress(transactionID);
} }
} }
}
else else
{ {
/* /*
@ -983,18 +936,86 @@ class ConnectivityCheckClient
logger.finest("will skip a check beat."); logger.finest("will skip a check beat.");
checkList.fireEndOfOrdinaryChecks(); checkList.fireEndOfOrdinaryChecks();
} }
}
} if (!cancelled.get())
finally
{ {
synchronized (paceMakers) schedule();
}
}
};
/**
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running
* checks for.
*/
private final CheckList checkList;
/**
* Scheduled instance of {@link #connectivityChecker} runnable
*/
private ScheduledFuture<?> scheduledCheck;
/**
* Creates a new {@link PaceMaker} for this
* <tt>ConnectivityCheckClient</tt>.
*
* @param checkList the {@link CheckList} that we'll be sending checks
* for
*/
public PaceMaker(CheckList checkList)
{ {
synchronized (this) this.checkList = checkList;
}
/**
* Cancel execution of current and further connectivity checks
*/
void cancel()
{ {
paceMakers.remove(this); cancelled.set(true);
final ScheduledFuture<?> scheduledCheck = this.scheduledCheck;
if (scheduledCheck != null)
{
scheduledCheck.cancel(true);
} }
} }
/**
* Schedules execution of checks for check list
*/
void schedule()
{
if (cancelled.get())
{
return;
} }
scheduledCheck
= scheduledExecutorService.schedule(
connectivityChecker,
getNextWaitInterval(),
TimeUnit.MILLISECONDS);
}
/**
* Returns the number milliseconds to wait before we send the next
* check.
*
* @return the number milliseconds to wait before we send the next
* check.
*/
private long getNextWaitInterval()
{
int activeCheckLists = parentAgent.getActiveCheckListCount();
if (activeCheckLists < 1)
{
//don't multiply by 0. even when we no longer have active check
//lists we may still have nomination checks to
activeCheckLists = 1;
}
return parentAgent.calculateTa() * activeCheckLists;
} }
} }
@ -1003,22 +1024,14 @@ class ConnectivityCheckClient
*/ */
public void stop() public void stop()
{ {
synchronized (paceMakers) while (true)
{ {
Iterator<PaceMaker> paceMakersIter = paceMakers.iterator(); final PaceMaker paceMaker = paceMakers.poll();
if (paceMaker == null)
while(paceMakersIter.hasNext())
{ {
PaceMaker paceMaker = paceMakersIter.next(); break;
synchronized (paceMaker)
{
paceMaker.running = false;
paceMaker.notify();
}
paceMakersIter.remove();
} }
paceMaker.cancel();
} }
} }
} }