From 58f9e29c82f9e0e667db5ec17270bfbb959d5600 Mon Sep 17 00:00:00 2001 From: "lubomir.marinov" Date: Tue, 11 Feb 2014 07:54:43 +0000 Subject: [PATCH] Uses a single Thread per StunStack to expire StunServerTransactions in order to reduce the total number of utilized Threads. --- .../ice4j/stack/StunServerTransaction.java | 118 ++++---- src/org/ice4j/stack/StunStack.java | 273 +++++++++++++++--- src/org/ice4j/stack/TransactionID.java | 32 +- 3 files changed, 290 insertions(+), 133 deletions(-) diff --git a/src/org/ice4j/stack/StunServerTransaction.java b/src/org/ice4j/stack/StunServerTransaction.java index 79f0a6f..e2590f6 100644 --- a/src/org/ice4j/stack/StunServerTransaction.java +++ b/src/org/ice4j/stack/StunServerTransaction.java @@ -33,12 +33,11 @@ import org.ice4j.message.*; * @author Emil Ivov */ class StunServerTransaction - implements Runnable { /** * The time that we keep server transactions active. */ - private static final long LIFETIME = 16000; + static final long LIFETIME = 16000; /** * The StunStack that created us. @@ -76,14 +75,9 @@ class StunServerTransaction 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; - - /** - * The thread that this transaction runs in. - */ - private Thread runningThread = null; + private long expirationTime = -1; /** * Determines whether or not the transaction has expired. @@ -116,35 +110,25 @@ class StunServerTransaction this.transactionID = tranID; this.localListeningAddress = localListeningAddress; this.requestSource = requestSource; - - runningThread = new Thread(this, "StunServerTransaction@"+hashCode()); - runningThread.setDaemon(true); } /** * Start the transaction. This launches the countdown to the moment the * transaction would expire. */ - public void start() + public synchronized void start() { - expired = false; - runningThread.start(); - } - - /** - * Actually this method is simply a timer waiting for the server transaction - * lifetime to come to an end. - */ - public void run() - { - runningThread.setName("ServTran"); - - schedule(LIFETIME); - waitNextScheduledDate(); - - //let's get lost - expire(); - stackCallback.removeServerTransaction(this); + if (expirationTime == -1) + { + expired = false; + expirationTime = LIFETIME + System.currentTimeMillis(); + } + else + { + throw new IllegalStateException( + "StunServerTransaction " + getTransactionID() + + " has already been started!"); + } } /** @@ -200,7 +184,7 @@ class StunServerTransaction { //don't retransmit if we are expired or if the user application //hasn't yet transmitted a first response - if(expired || !isRetransmitting) + if(isExpired() || !isRetransmitting) return; stackCallback.getNetAccessManager().sendMessage( @@ -209,45 +193,47 @@ class StunServerTransaction 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 * considered terminated and will stop retransmissions. */ public synchronized void expire() { - this.expired = true; - notifyAll(); + expired = true; + /* + * StunStack has a background Thread running with the purpose of + * removing expired StunServerTransactions. + */ + } + + /** + * Determines whether this StunServerTransaction is expired now. + * + * @return true if this StunServerTransaction is expired + * now; otherwise, false + */ + public boolean isExpired() + { + return isExpired(System.currentTimeMillis()); + } + + /** + * Determines whether this StunServerTransaction will be expired at + * a specific point in time. + * + * @param now the time in milliseconds at which the expired state + * of this StunServerTransaction is to be returned + * @return true if this StunServerTransaction will be + * expired at the specified point in time; otherwise, false + */ + 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() { - return this.transactionID; + return transactionID; } /** diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 544fda4..03da7f7 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -72,6 +72,13 @@ public class StunStack clientTransactions = new Hashtable(); + /** + * The Thread which expires the StunServerTransactions of + * this StunStack and removes them from + * {@link #serverTransactions}. + */ + private Thread serverTransactionExpireThread; + /** * Currently open server transactions. The vector contains transaction ids * for transactions corresponding to all non-answered received requests. @@ -167,18 +174,50 @@ public class StunStack { synchronized (serverTransactions) { - Collection sTrans - = serverTransactions.values(); + long now = System.currentTimeMillis(); - for (StunServerTransaction tran : sTrans) + for (Iterator i + = serverTransactions.values().iterator(); + i.hasNext();) { - if (tran.getTransactionID().equals(transactionID)) - return tran; + StunServerTransaction serverTransaction = i.next(); + + if (serverTransaction.isExpired(now)) + i.remove(); + else if (serverTransaction.getTransactionID().equals( + transactionID)) + return serverTransaction; } } return null; } + /** + * Returns the transaction with the specified transactionID or + * null 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 * transactionID. Cancellation means that the stack will not @@ -208,48 +247,41 @@ public class StunStack */ private void cancelTransactionsForAddress(TransportAddress localAddr) { - synchronized(clientTransactions) + synchronized (clientTransactions) { - Iterator> - clientTransactionsIter = clientTransactions.entrySet() - .iterator(); + Iterator clientTransactionsIter + = clientTransactions.values().iterator(); while (clientTransactionsIter.hasNext()) { - Map.Entry entry - = clientTransactionsIter.next(); + StunClientTransaction tran = clientTransactionsIter.next(); - StunClientTransaction tran = entry.getValue(); if (tran.getLocalAddress().equals(localAddr)) + { clientTransactionsIter.remove(); - - tran.cancel(); + tran.cancel(); + } } } - synchronized(serverTransactions) + synchronized (serverTransactions) { - Iterator> - serverTransactionsIter = serverTransactions.entrySet() - .iterator(); + Iterator serverTransactionsIter + = serverTransactions.values().iterator(); while (serverTransactionsIter.hasNext()) { - Map.Entry entry - = serverTransactionsIter.next(); - - StunServerTransaction tran = entry.getValue(); - + StunServerTransaction tran = serverTransactionsIter.next(); TransportAddress listenAddr = tran.getLocalListeningAddress(); TransportAddress sendingAddr = tran.getSendingAddress(); - if ( listenAddr.equals(localAddr) - || (sendingAddr != null && sendingAddr.equals(localAddr)) ) + if (listenAddr.equals(localAddr) + || (sendingAddr != null + && sendingAddr.equals(localAddr))) { serverTransactionsIter.remove(); + tran.expire(); } - - tran.expire(); } } } @@ -534,7 +566,7 @@ public class StunStack { TransactionID tid = TransactionID.createTransactionID(this, transactionID); - StunServerTransaction sTran = serverTransactions.get(tid); + StunServerTransaction sTran = getServerTransaction(tid); if(sTran == null) { @@ -652,9 +684,12 @@ public class StunStack * Method is used by StunClientTransaction-s themselves when a timeout occurs. * @param tran the transaction to remove. */ - synchronized void removeClientTransaction(StunClientTransaction tran) + void removeClientTransaction(StunClientTransaction tran) { - clientTransactions.remove(tran.getTransactionID()); + synchronized (clientTransactions) + { + clientTransactions.remove(tran.getTransactionID()); + } } /** @@ -663,9 +698,12 @@ public class StunStack * Method is used by StunServerTransaction-s themselves when they expire. * @param tran the transaction to remove. */ - synchronized void removeServerTransaction(StunServerTransaction tran) + void removeServerTransaction(StunServerTransaction tran) { - serverTransactions.remove(tran.getTransactionID()); + synchronized (serverTransactions) + { + serverTransactions.remove(tran.getTransactionID()); + } } /** @@ -690,7 +728,7 @@ public class StunStack logger.finest("parsing request"); TransactionID serverTid = ev.getTransactionID(); - StunServerTransaction sTran = serverTransactions.get(serverTid); + StunServerTransaction sTran = getServerTransaction(serverTid); if( sTran != null) { @@ -740,7 +778,11 @@ public class StunStack logger.info("STUN transaction thread start failed:" + t); return; } - serverTransactions.put(serverTid, sTran); + synchronized (serverTransactions) + { + serverTransactions.put(serverTid, sTran); + maybeStartServerTransactionExpireThread(); + } } //validate attributes that need validation. @@ -856,26 +898,32 @@ public class StunStack { eventDispatcher.removeAllListeners(); - for (Iterator i - = clientTransactions.values().iterator(); - i.hasNext();) + synchronized (clientTransactions) { - StunClientTransaction tran = i.next(); + for (Iterator i + = clientTransactions.values().iterator(); + i.hasNext();) + { + StunClientTransaction tran = i.next(); - i.remove(); - if(tran != null) - tran.cancel(); + i.remove(); + if (tran != null) + tran.cancel(); + } } - for (Iterator i - = serverTransactions.values().iterator(); - i.hasNext();) + synchronized (serverTransactions) { - StunServerTransaction tran = i.next(); + for (Iterator i + = serverTransactions.values().iterator(); + i.hasNext();) + { + StunServerTransaction tran = i.next(); - i.remove(); - if(tran != null) - tran.expire(); + i.remove(); + if (tran != null) + tran.expire(); + } } netAccessManager.stop(); @@ -1214,4 +1262,133 @@ public class StunStack { 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 + * StunServerTransactions of this StunStack 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 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(); + } + } + } } diff --git a/src/org/ice4j/stack/TransactionID.java b/src/org/ice4j/stack/TransactionID.java index d856509..ab5ccad 100644 --- a/src/org/ice4j/stack/TransactionID.java +++ b/src/org/ice4j/stack/TransactionID.java @@ -30,7 +30,7 @@ public class TransactionID /** * The id itself */ - private final byte transactionID[]; + private final byte[] transactionID; /** * Any object that the application would like to correlate to a transaction. @@ -53,7 +53,7 @@ public class TransactionID */ private TransactionID() { - transactionID = new byte[RFC5389_TRANSACTION_ID_LENGTH]; + this(false); } /** @@ -63,14 +63,11 @@ public class TransactionID */ private TransactionID(boolean rfc3489Compatibility) { - if(rfc3489Compatibility) - { - transactionID = new byte[RFC3489_TRANSACTION_ID_LENGTH]; - } - else - { - transactionID = new byte[RFC5389_TRANSACTION_ID_LENGTH]; - } + transactionID + = new byte[ + rfc3489Compatibility + ? RFC3489_TRANSACTION_ID_LENGTH + : RFC5389_TRANSACTION_ID_LENGTH]; } /** @@ -211,11 +208,10 @@ public class TransactionID */ public boolean equals(Object obj) { - if(!(obj instanceof TransactionID)) - return false; - if(this == obj) return true; + if(!(obj instanceof TransactionID)) + return false; byte targetBytes[] = ((TransactionID)obj).transactionID; @@ -234,7 +230,7 @@ public class TransactionID /** * 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 * Specification */ @@ -262,19 +258,17 @@ public class TransactionID */ public static String toString(byte[] transactionID) { - StringBuffer idStr = new StringBuffer(); + StringBuilder idStr = new StringBuilder(); idStr.append("0x"); for(int i = 0; i < transactionID.length; i++) { if((transactionID[i] & 0xFF) <= 15) - { idStr.append("0"); - } - idStr.append(Integer.toHexString(transactionID[i] & 0xff) - .toUpperCase()); + idStr.append( + Integer.toHexString(transactionID[i] & 0xFF).toUpperCase()); } return idStr.toString();