Uses a single Thread per StunStack to expire StunServerTransactions in order to reduce the total number of utilized Threads.

This commit is contained in:
lubomir.marinov 2014-02-11 07:54:43 +00:00
parent 987512ede1
commit 58f9e29c82
3 changed files with 290 additions and 133 deletions

View File

@ -33,12 +33,11 @@ import org.ice4j.message.*;
* @author Emil Ivov * @author Emil Ivov
*/ */
class StunServerTransaction class StunServerTransaction
implements Runnable
{ {
/** /**
* The time that we keep server transactions active. * The time that we keep server transactions active.
*/ */
private static final long LIFETIME = 16000; static final long LIFETIME = 16000;
/** /**
* The <tt>StunStack</tt> that created us. * The <tt>StunStack</tt> that created us.
@ -76,14 +75,9 @@ class StunServerTransaction
private final TransactionID transactionID; private final TransactionID transactionID;
/** /**
* The date (in milliseconds) when the next retransmission should follow. * The time in milliseconds when the next retransmission should follow.
*/ */
private long expirationDate = -1; private long expirationTime = -1;
/**
* The thread that this transaction runs in.
*/
private Thread runningThread = null;
/** /**
* Determines whether or not the transaction has expired. * Determines whether or not the transaction has expired.
@ -116,35 +110,25 @@ class StunServerTransaction
this.transactionID = tranID; this.transactionID = tranID;
this.localListeningAddress = localListeningAddress; this.localListeningAddress = localListeningAddress;
this.requestSource = requestSource; this.requestSource = requestSource;
runningThread = new Thread(this, "StunServerTransaction@"+hashCode());
runningThread.setDaemon(true);
} }
/** /**
* Start the transaction. This launches the countdown to the moment the * Start the transaction. This launches the countdown to the moment the
* transaction would expire. * transaction would expire.
*/ */
public void start() public synchronized void start()
{
if (expirationTime == -1)
{ {
expired = false; expired = false;
runningThread.start(); expirationTime = LIFETIME + System.currentTimeMillis();
} }
else
/**
* Actually this method is simply a timer waiting for the server transaction
* lifetime to come to an end.
*/
public void run()
{ {
runningThread.setName("ServTran"); throw new IllegalStateException(
"StunServerTransaction " + getTransactionID()
schedule(LIFETIME); + " has already been started!");
waitNextScheduledDate(); }
//let's get lost
expire();
stackCallback.removeServerTransaction(this);
} }
/** /**
@ -200,7 +184,7 @@ class StunServerTransaction
{ {
//don't retransmit if we are expired or if the user application //don't retransmit if we are expired or if the user application
//hasn't yet transmitted a first response //hasn't yet transmitted a first response
if(expired || !isRetransmitting) if(isExpired() || !isRetransmitting)
return; return;
stackCallback.getNetAccessManager().sendMessage( stackCallback.getNetAccessManager().sendMessage(
@ -209,45 +193,47 @@ class StunServerTransaction
responseDestination); responseDestination);
} }
/**
* Waits until next retransmission is due or until the transaction is
* cancelled (whichever comes first).
*/
private synchronized void waitNextScheduledDate()
{
long timeout;
while (!expired
&& (timeout = expirationDate - System.currentTimeMillis()) > 0)
{
try
{
wait(timeout);
}
catch (InterruptedException ex)
{
}
}
}
/**
* Sets the expiration date for this server transaction.
*
* @param timeout the number of milliseconds to wait before expiration.
*/
private void schedule(long timeout)
{
this.expirationDate = System.currentTimeMillis() + timeout;
}
/** /**
* Cancels the transaction. Once this method is called the transaction is * Cancels the transaction. Once this method is called the transaction is
* considered terminated and will stop retransmissions. * considered terminated and will stop retransmissions.
*/ */
public synchronized void expire() public synchronized void expire()
{ {
this.expired = true; expired = true;
notifyAll(); /*
* StunStack has a background Thread running with the purpose of
* removing expired StunServerTransactions.
*/
}
/**
* Determines whether this <tt>StunServerTransaction</tt> is expired now.
*
* @return <tt>true</tt> if this <tt>StunServerTransaction</tT> is expired
* now; otherwise, <tt>false</tt>
*/
public boolean isExpired()
{
return isExpired(System.currentTimeMillis());
}
/**
* Determines whether this <tt>StunServerTransaction</tt> will be expired at
* a specific point in time.
*
* @param now the time in milliseconds at which the <tt>expired</tt> state
* of this <tt>StunServerTransaction</tt> is to be returned
* @return <tt>true</tt> if this <tt>StunServerTransaction</tt> will be
* expired at the specified point in time; otherwise, <tt>false</tt>
*/
public synchronized boolean isExpired(long now)
{
if (expirationTime == -1)
return false;
else if (expirationTime < now)
return true;
else
return expired;
} }
/** /**
@ -257,7 +243,7 @@ class StunServerTransaction
*/ */
public TransactionID getTransactionID() public TransactionID getTransactionID()
{ {
return this.transactionID; return transactionID;
} }
/** /**

View File

@ -72,6 +72,13 @@ public class StunStack
clientTransactions clientTransactions
= new Hashtable<TransactionID, StunClientTransaction>(); = new Hashtable<TransactionID, StunClientTransaction>();
/**
* The <tt>Thread</tt> which expires the <tt>StunServerTransaction</tt>s of
* this <tt>StunStack</tt> and removes them from
* {@link #serverTransactions}.
*/
private Thread serverTransactionExpireThread;
/** /**
* Currently open server transactions. The vector contains transaction ids * Currently open server transactions. The vector contains transaction ids
* for transactions corresponding to all non-answered received requests. * for transactions corresponding to all non-answered received requests.
@ -167,18 +174,50 @@ public class StunStack
{ {
synchronized (serverTransactions) synchronized (serverTransactions)
{ {
Collection<StunServerTransaction> sTrans long now = System.currentTimeMillis();
= serverTransactions.values();
for (StunServerTransaction tran : sTrans) for (Iterator<StunServerTransaction> i
= serverTransactions.values().iterator();
i.hasNext();)
{ {
if (tran.getTransactionID().equals(transactionID)) StunServerTransaction serverTransaction = i.next();
return tran;
if (serverTransaction.isExpired(now))
i.remove();
else if (serverTransaction.getTransactionID().equals(
transactionID))
return serverTransaction;
} }
} }
return null; return null;
} }
/**
* Returns the transaction with the specified <tt>transactionID</tt> or
* <tt>null</tt> if no such transaction exists.
*
* @param transactionID the ID of the transaction we are looking for.
*
* @return the {@link StunClientTransaction} we are looking for.
*/
protected StunServerTransaction getServerTransaction(
TransactionID transactionID)
{
StunServerTransaction serverTransaction;
synchronized (serverTransactions)
{
serverTransaction = serverTransactions.get(transactionID);
}
/*
* If a StunServerTransaction is expired, do not return it. It will be
* removed from serverTransactions soon.
*/
if ((serverTransaction != null) && serverTransaction.isExpired())
serverTransaction = null;
return serverTransaction;
}
/** /**
* Cancels the {@link StunClientTransaction} with the specified * Cancels the {@link StunClientTransaction} with the specified
* <tt>transactionID</tt>. Cancellation means that the stack will not * <tt>transactionID</tt>. Cancellation means that the stack will not
@ -210,49 +249,42 @@ public class StunStack
{ {
synchronized (clientTransactions) synchronized (clientTransactions)
{ {
Iterator<Map.Entry<TransactionID, StunClientTransaction>> Iterator<StunClientTransaction> clientTransactionsIter
clientTransactionsIter = clientTransactions.entrySet() = clientTransactions.values().iterator();
.iterator();
while (clientTransactionsIter.hasNext()) while (clientTransactionsIter.hasNext())
{ {
Map.Entry<TransactionID, StunClientTransaction> entry StunClientTransaction tran = clientTransactionsIter.next();
= clientTransactionsIter.next();
StunClientTransaction tran = entry.getValue();
if (tran.getLocalAddress().equals(localAddr)) if (tran.getLocalAddress().equals(localAddr))
{
clientTransactionsIter.remove(); clientTransactionsIter.remove();
tran.cancel(); tran.cancel();
} }
} }
}
synchronized (serverTransactions) synchronized (serverTransactions)
{ {
Iterator<Map.Entry<TransactionID, StunServerTransaction>> Iterator<StunServerTransaction> serverTransactionsIter
serverTransactionsIter = serverTransactions.entrySet() = serverTransactions.values().iterator();
.iterator();
while (serverTransactionsIter.hasNext()) while (serverTransactionsIter.hasNext())
{ {
Map.Entry<TransactionID, StunServerTransaction> entry StunServerTransaction tran = serverTransactionsIter.next();
= serverTransactionsIter.next();
StunServerTransaction tran = entry.getValue();
TransportAddress listenAddr = tran.getLocalListeningAddress(); TransportAddress listenAddr = tran.getLocalListeningAddress();
TransportAddress sendingAddr = tran.getSendingAddress(); TransportAddress sendingAddr = tran.getSendingAddress();
if (listenAddr.equals(localAddr) if (listenAddr.equals(localAddr)
|| (sendingAddr != null && sendingAddr.equals(localAddr)) ) || (sendingAddr != null
&& sendingAddr.equals(localAddr)))
{ {
serverTransactionsIter.remove(); serverTransactionsIter.remove();
}
tran.expire(); tran.expire();
} }
} }
} }
}
/** /**
* Initializes a new <tt>StunStack</tt> instance. * Initializes a new <tt>StunStack</tt> instance.
@ -534,7 +566,7 @@ public class StunStack
{ {
TransactionID tid TransactionID tid
= TransactionID.createTransactionID(this, transactionID); = TransactionID.createTransactionID(this, transactionID);
StunServerTransaction sTran = serverTransactions.get(tid); StunServerTransaction sTran = getServerTransaction(tid);
if(sTran == null) if(sTran == null)
{ {
@ -652,10 +684,13 @@ public class StunStack
* Method is used by StunClientTransaction-s themselves when a timeout occurs. * Method is used by StunClientTransaction-s themselves when a timeout occurs.
* @param tran the transaction to remove. * @param tran the transaction to remove.
*/ */
synchronized void removeClientTransaction(StunClientTransaction tran) void removeClientTransaction(StunClientTransaction tran)
{
synchronized (clientTransactions)
{ {
clientTransactions.remove(tran.getTransactionID()); clientTransactions.remove(tran.getTransactionID());
} }
}
/** /**
* Removes a server transaction from this provider's server transactions * Removes a server transaction from this provider's server transactions
@ -663,10 +698,13 @@ public class StunStack
* Method is used by StunServerTransaction-s themselves when they expire. * Method is used by StunServerTransaction-s themselves when they expire.
* @param tran the transaction to remove. * @param tran the transaction to remove.
*/ */
synchronized void removeServerTransaction(StunServerTransaction tran) void removeServerTransaction(StunServerTransaction tran)
{
synchronized (serverTransactions)
{ {
serverTransactions.remove(tran.getTransactionID()); serverTransactions.remove(tran.getTransactionID());
} }
}
/** /**
* Called to notify this provider for an incoming message. * Called to notify this provider for an incoming message.
@ -690,7 +728,7 @@ public class StunStack
logger.finest("parsing request"); logger.finest("parsing request");
TransactionID serverTid = ev.getTransactionID(); TransactionID serverTid = ev.getTransactionID();
StunServerTransaction sTran = serverTransactions.get(serverTid); StunServerTransaction sTran = getServerTransaction(serverTid);
if( sTran != null) if( sTran != null)
{ {
@ -740,7 +778,11 @@ public class StunStack
logger.info("STUN transaction thread start failed:" + t); logger.info("STUN transaction thread start failed:" + t);
return; return;
} }
synchronized (serverTransactions)
{
serverTransactions.put(serverTid, sTran); serverTransactions.put(serverTid, sTran);
maybeStartServerTransactionExpireThread();
}
} }
//validate attributes that need validation. //validate attributes that need validation.
@ -856,6 +898,8 @@ public class StunStack
{ {
eventDispatcher.removeAllListeners(); eventDispatcher.removeAllListeners();
synchronized (clientTransactions)
{
for (Iterator<StunClientTransaction> i for (Iterator<StunClientTransaction> i
= clientTransactions.values().iterator(); = clientTransactions.values().iterator();
i.hasNext();) i.hasNext();)
@ -866,7 +910,10 @@ public class StunStack
if (tran != null) if (tran != null)
tran.cancel(); tran.cancel();
} }
}
synchronized (serverTransactions)
{
for (Iterator<StunServerTransaction> i for (Iterator<StunServerTransaction> i
= serverTransactions.values().iterator(); = serverTransactions.values().iterator();
i.hasNext();) i.hasNext();)
@ -877,6 +924,7 @@ public class StunStack
if (tran != null) if (tran != null)
tran.expire(); tran.expire();
} }
}
netAccessManager.stop(); netAccessManager.stop();
} }
@ -1214,4 +1262,133 @@ public class StunStack
{ {
return mode; return mode;
} }
/**
* Initializes and starts {@link #serverTransactionExpireThread} if
* necessary.
*/
private void maybeStartServerTransactionExpireThread()
{
synchronized (serverTransactions)
{
if (!serverTransactions.isEmpty()
&& (serverTransactionExpireThread == null))
{
Thread t
= new Thread()
{
@Override
public void run()
{
runInServerTransactionExpireThread();
}
};
t.setDaemon(true);
t.setName(
getClass().getName()
+ ".serverTransactionExpireThread");
boolean started = false;
serverTransactionExpireThread = t;
try
{
t.start();
started = true;
}
finally
{
if (!started && (serverTransactionExpireThread == t))
serverTransactionExpireThread = null;
}
}
}
}
/**
* Runs in {@link #serverTransactionExpireThread} and expires the
* <tt>StunServerTransaction</tt>s of this <tt>StunStack</tt> and removes
* them from {@link #serverTransactions}.
*/
private void runInServerTransactionExpireThread()
{
try
{
long idleStartTime = -1;
do
{
synchronized (serverTransactions)
{
try
{
serverTransactions.wait(StunServerTransaction.LIFETIME);
}
catch (InterruptedException ie)
{
}
/*
* Is the current Thread still designated to expire the
* StunServerTransactions of this StunStack?
*/
if (Thread.currentThread() != serverTransactionExpireThread)
break;
long now = System.currentTimeMillis();
/*
* Has the current Thread been idle long enough to merit
* disposing of it?
*/
if (serverTransactions.isEmpty())
{
if (idleStartTime == -1)
idleStartTime = now;
else if (now - idleStartTime > 60 * 1000)
break;
}
else
{
// Expire the StunServerTransactions of this StunStack.
idleStartTime = -1;
for (Iterator<StunServerTransaction> i
= serverTransactions.values().iterator();
i.hasNext();)
{
StunServerTransaction serverTransaction = i.next();
if (serverTransaction == null)
{
i.remove();
}
else if (serverTransaction.isExpired(now))
{
i.remove();
serverTransaction.expire();
}
}
}
}
}
while (true);
}
finally
{
synchronized (serverTransactions)
{
if (serverTransactionExpireThread == Thread.currentThread())
serverTransactionExpireThread = null;
/*
* If serverTransactionExpireThread dies unexpectedly and yet it
* is still necessary, resurrect it.
*/
if (serverTransactionExpireThread == null)
maybeStartServerTransactionExpireThread();
}
}
}
} }

View File

@ -30,7 +30,7 @@ public class TransactionID
/** /**
* The id itself * The id itself
*/ */
private final byte transactionID[]; private final byte[] transactionID;
/** /**
* Any object that the application would like to correlate to a transaction. * Any object that the application would like to correlate to a transaction.
@ -53,7 +53,7 @@ public class TransactionID
*/ */
private TransactionID() private TransactionID()
{ {
transactionID = new byte[RFC5389_TRANSACTION_ID_LENGTH]; this(false);
} }
/** /**
@ -63,14 +63,11 @@ public class TransactionID
*/ */
private TransactionID(boolean rfc3489Compatibility) private TransactionID(boolean rfc3489Compatibility)
{ {
if(rfc3489Compatibility) transactionID
{ = new byte[
transactionID = new byte[RFC3489_TRANSACTION_ID_LENGTH]; rfc3489Compatibility
} ? RFC3489_TRANSACTION_ID_LENGTH
else : RFC5389_TRANSACTION_ID_LENGTH];
{
transactionID = new byte[RFC5389_TRANSACTION_ID_LENGTH];
}
} }
/** /**
@ -211,11 +208,10 @@ public class TransactionID
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(!(obj instanceof TransactionID))
return false;
if(this == obj) if(this == obj)
return true; return true;
if(!(obj instanceof TransactionID))
return false;
byte targetBytes[] = ((TransactionID)obj).transactionID; byte targetBytes[] = ((TransactionID)obj).transactionID;
@ -234,7 +230,7 @@ public class TransactionID
/** /**
* Returns the first four bytes of the transactionID to ensure proper * Returns the first four bytes of the transactionID to ensure proper
* retrieval from hashtables; * retrieval from hashtables.
* @return the hashcode of this object - as advised by the Java Platform * @return the hashcode of this object - as advised by the Java Platform
* Specification * Specification
*/ */
@ -262,19 +258,17 @@ public class TransactionID
*/ */
public static String toString(byte[] transactionID) public static String toString(byte[] transactionID)
{ {
StringBuffer idStr = new StringBuffer(); StringBuilder idStr = new StringBuilder();
idStr.append("0x"); idStr.append("0x");
for(int i = 0; i < transactionID.length; i++) for(int i = 0; i < transactionID.length; i++)
{ {
if((transactionID[i] & 0xFF) <= 15) if((transactionID[i] & 0xFF) <= 15)
{
idStr.append("0"); idStr.append("0");
}
idStr.append(Integer.toHexString(transactionID[i] & 0xff) idStr.append(
.toUpperCase()); Integer.toHexString(transactionID[i] & 0xFF).toUpperCase());
} }
return idStr.toString(); return idStr.toString();