From 3b15ee7cb6a6231c905a9eb25d950c8b98b06d27 Mon Sep 17 00:00:00 2001 From: "lubomir.marinov" Date: Mon, 2 Jun 2014 18:40:02 +0000 Subject: [PATCH] Fixes yet another deadlock involving StunClientTransaction#cancel(boolean). Reported by Carl Hasselskog. --- src/org/ice4j/StackProperties.java | 1 - src/org/ice4j/ice/Component.java | 2 +- src/org/ice4j/ice/IceMediaStream.java | 57 ++--- .../ice4j/stack/StunClientTransaction.java | 194 ++++++++++++------ 4 files changed, 167 insertions(+), 87 deletions(-) diff --git a/src/org/ice4j/StackProperties.java b/src/org/ice4j/StackProperties.java index 6da1912..db0920b 100644 --- a/src/org/ice4j/StackProperties.java +++ b/src/org/ice4j/StackProperties.java @@ -7,7 +7,6 @@ */ package org.ice4j; -import java.net.*; import java.util.*; import java.util.logging.*; diff --git a/src/org/ice4j/ice/Component.java b/src/org/ice4j/ice/Component.java index b96362e..f5b7013 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -46,7 +46,7 @@ public class Component * mapping of components to component IDs. See Section 14 for additional * discussion on extending ICE to new media streams. */ - private int componentID = -1; + private final int componentID; /** * The component ID to use with RTP streams. diff --git a/src/org/ice4j/ice/IceMediaStream.java b/src/org/ice4j/ice/IceMediaStream.java index cc3dc8a..8ab668f 100644 --- a/src/org/ice4j/ice/IceMediaStream.java +++ b/src/org/ice4j/ice/IceMediaStream.java @@ -65,8 +65,8 @@ public class IceMediaStream * address; a media stream may require multiple components, each of which * has to work for the media stream as a whole to work. */ - private final LinkedHashMap components - = new LinkedHashMap(); + private final Map components + = new LinkedHashMap(); /** * An ordered set of candidate pairs for a media stream that have been @@ -150,13 +150,14 @@ public class IceMediaStream */ protected Component createComponent(Transport transport) { - lastComponentID ++; - Component component; - synchronized( components ) + + synchronized (components) { - component = new Component(lastComponentID, transport, this); - components.put(new Integer(lastComponentID), component); + component = new Component(++lastComponentID, transport, this); + components.put( + Integer.valueOf(component.getComponentID()), + component); } return component; @@ -222,7 +223,7 @@ public class IceMediaStream { synchronized(components) { - return new LinkedList(components.values()); + return new ArrayList(components.values()); } } @@ -252,7 +253,7 @@ public class IceMediaStream { synchronized(components) { - return new LinkedList(components.keySet()); + return new ArrayList(components.keySet()); } } @@ -265,10 +266,7 @@ public class IceMediaStream */ public int getStreamCount() { - synchronized(components) - { - return components.size(); - } + return getComponentCount(); } /** @@ -287,17 +285,23 @@ public class IceMediaStream */ protected void free() { - synchronized (components) - { - for (Iterator i = components.values().iterator(); - i.hasNext();) - { - Component component = i.next(); + List components; - i.remove(); - component.free(); - } + synchronized (this.components) + { + components = getComponents(); + this.components.clear(); } + /* + * Free the components outside the synchronized block because a deadlock + * has been reported (by Carl Hasselskog). The execution flow is not the + * same as when freeing the components inside the synchronized block + * because in the latter case an exception thrown by Component#free() + * will leave subsequent components in IceMediaStream#componenets. But + * there is no idication that such behaviour is expected. + */ + for (Component component : components) + component.free(); } /** @@ -312,8 +316,15 @@ public class IceMediaStream synchronized (components) { components.remove(component.getComponentID()); - component.free(); } + /* + * There is no known reason why the component should be freed with + * synchronization by components. However, the freeing outside the + * synchronization block will surely decrease the chances of a deadlock. + * Besides, Component#free() has really been reported involved in a + * deadlock. + */ + component.free(); } /** diff --git a/src/org/ice4j/stack/StunClientTransaction.java b/src/org/ice4j/stack/StunClientTransaction.java index 19cd20f..074dc8d 100644 --- a/src/org/ice4j/stack/StunClientTransaction.java +++ b/src/org/ice4j/stack/StunClientTransaction.java @@ -8,6 +8,7 @@ package org.ice4j.stack; import java.io.*; import java.util.concurrent.*; +import java.util.concurrent.locks.*; import java.util.logging.*; import org.ice4j.*; @@ -159,6 +160,24 @@ class StunClientTransaction */ private boolean cancelled = false; + /** + * The Lock which synchronizes the access to the state of this + * instance. Introduced along with {@link #lockCondition} in order to allow + * the invocation of {@link #cancel(boolean)} without a requirement to + * acquire the synchronization root. Otherwise, callers of + * cancel(boolean) may (and have be reported multiple times to) + * fall into a deadlock merely because they want to cancel this + * StunClientTransaction. + */ + private final Lock lock = new ReentrantLock(); + + /** + * The Condition of {@link #lock} which this instance uses to wait + * for either the next retransmission interval or the cancellation of this + * StunClientTransaction. + */ + private final Condition lockCondition = lock.newCondition(); + /** * Creates a client transaction. * @@ -236,68 +255,92 @@ class StunClientTransaction * until a response is received, or a total of 7 requests have been sent. * If no response is received by 1.6 seconds after the last request has been * sent, we consider the transaction to have failed. + *

+ * The method acquires {@link #lock} and invokes {@link #runLocked()}. + *

*/ public void run() + { + lock.lock(); + try + { + runLocked(); + } + finally + { + lock.unlock(); + } + } + + /** + * Implements the retransmissions algorithm. Retransmits the request + * starting with an interval of 100ms, doubling every retransmit until the + * interval reaches 1.6s. Retransmissions continue with intervals of 1.6s + * until a response is received, or a total of 7 requests have been sent. + * If no response is received by 1.6 seconds after the last request has been + * sent, we consider the transaction to have failed. + *

+ * The method assumes that the current thread has already acquired + * {@link #lock}. + *

+ */ + private void runLocked() { // Indicates how many times we have retransmitted so far. int retransmissionCounter = 0; // How much did we wait after our last retransmission? int nextWaitInterval = originalWaitInterval; - synchronized(this) + for (retransmissionCounter = 0; + retransmissionCounter < maxRetransmissions; + retransmissionCounter ++) { - for (retransmissionCounter = 0; - retransmissionCounter < maxRetransmissions; - retransmissionCounter ++) - { - waitFor(nextWaitInterval); - - //did someone tell us to get lost? - if(cancelled) - return; - - int curWaitInterval = nextWaitInterval; - if(nextWaitInterval < maxWaitInterval) - nextWaitInterval *= 2; - - try - { - logger.fine( - "retrying STUN tid " + transactionID - + " from " + localAddress - + " to " + requestDestination - + " waited " + curWaitInterval - + " ms retrans " + (retransmissionCounter + 1) - + " of " + maxRetransmissions); - sendRequest0(); - } - catch (Exception ex) - { - //I wonder whether we should notify anyone that a - //retransmission has failed - logger.log( - Level.INFO, - "A client tran retransmission failed", - ex); - } - } - - //before stating that a transaction has timeout-ed we should first - //wait for a reception of the response - if(nextWaitInterval < maxWaitInterval) - nextWaitInterval *= 2; - waitFor(nextWaitInterval); + //did someone tell us to get lost? if(cancelled) return; - stackCallback.removeClientTransaction(this); - responseCollector.processTimeout( - new StunTimeoutEvent( - stackCallback, - this.request, getLocalAddress(), transactionID)); + int curWaitInterval = nextWaitInterval; + if(nextWaitInterval < maxWaitInterval) + nextWaitInterval *= 2; + + try + { + logger.fine( + "retrying STUN tid " + transactionID + " from " + + localAddress + " to " + requestDestination + + " waited " + curWaitInterval + " ms retrans " + + (retransmissionCounter + 1) + " of " + + maxRetransmissions); + sendRequest0(); + } + catch (Exception ex) + { + //I wonder whether we should notify anyone that a retransmission + // has failed + logger.log( + Level.INFO, + "A client tran retransmission failed", + ex); + } } + + //before stating that a transaction has timeout-ed we should first wait + //for a reception of the response + if(nextWaitInterval < maxWaitInterval) + nextWaitInterval *= 2; + + waitFor(nextWaitInterval); + + if(cancelled) + return; + + stackCallback.removeClientTransaction(this); + responseCollector.processTimeout( + new StunTimeoutEvent( + stackCallback, + this.request, getLocalAddress(), transactionID)); } /** @@ -362,14 +405,19 @@ class StunClientTransaction */ void waitFor(long millis) { + lock.lock(); try { - wait(millis); + lockCondition.await(millis, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { throw new RuntimeException(ex); } + finally + { + lock.unlock(); + } } /** @@ -393,9 +441,23 @@ class StunClientTransaction if(!waitForResponse) { - synchronized (this) + /* + * Try to interrupt #waitFor(long) if possible. But don't risk a + * deadlock. It is not a problem if it is not possible to interrupt + * #waitFor(long) here because it will complete in finite time and + * this StunClientTransaction will eventually notice that it has + * been cancelled. + */ + if (lock.tryLock()) { - notifyAll(); + try + { + lockCondition.signal(); + } + finally + { + lock.unlock(); + } } } } @@ -415,21 +477,29 @@ class StunClientTransaction * * @param evt the event that contains the newly received message */ - synchronized void handleResponse(StunMessageEvent evt) + void handleResponse(StunMessageEvent evt) { - TransactionID transactionID = getTransactionID(); + lock.lock(); + try + { + TransactionID transactionID = getTransactionID(); - logger.log(Level.FINE, "handleResponse tid " + transactionID); - if( !Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE) ) - cancel(); + logger.log(Level.FINE, "handleResponse tid " + transactionID); + if(!Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE)) + cancel(); - responseCollector.processResponse( - new StunResponseEvent( - stackCallback, - evt.getRawMessage(), - (Response) evt.getMessage(), - request, - transactionID)); + responseCollector.processResponse( + new StunResponseEvent( + stackCallback, + evt.getRawMessage(), + (Response) evt.getMessage(), + request, + transactionID)); + } + finally + { + lock.unlock(); + } } /**