Fixes yet another deadlock involving StunClientTransaction#cancel(boolean). Reported by Carl Hasselskog.

This commit is contained in:
lubomir.marinov 2014-06-02 18:40:02 +00:00
parent 53d69cd963
commit 3b15ee7cb6
4 changed files with 167 additions and 87 deletions

View File

@ -7,7 +7,6 @@
*/ */
package org.ice4j; package org.ice4j;
import java.net.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;

View File

@ -46,7 +46,7 @@ public class Component
* mapping of components to component IDs. See Section 14 for additional * mapping of components to component IDs. See Section 14 for additional
* discussion on extending ICE to new media streams. * discussion on extending ICE to new media streams.
*/ */
private int componentID = -1; private final int componentID;
/** /**
* The component ID to use with RTP streams. * The component ID to use with RTP streams.

View File

@ -65,7 +65,7 @@ public class IceMediaStream
* address; a media stream may require multiple components, each of which * address; a media stream may require multiple components, each of which
* has to work for the media stream as a whole to work. * has to work for the media stream as a whole to work.
*/ */
private final LinkedHashMap<Integer, Component> components private final Map<Integer, Component> components
= new LinkedHashMap<Integer, Component>(); = new LinkedHashMap<Integer, Component>();
/** /**
@ -150,13 +150,14 @@ public class IceMediaStream
*/ */
protected Component createComponent(Transport transport) protected Component createComponent(Transport transport)
{ {
lastComponentID ++;
Component component; Component component;
synchronized( components )
synchronized (components)
{ {
component = new Component(lastComponentID, transport, this); component = new Component(++lastComponentID, transport, this);
components.put(new Integer(lastComponentID), component); components.put(
Integer.valueOf(component.getComponentID()),
component);
} }
return component; return component;
@ -222,7 +223,7 @@ public class IceMediaStream
{ {
synchronized(components) synchronized(components)
{ {
return new LinkedList<Component>(components.values()); return new ArrayList<Component>(components.values());
} }
} }
@ -252,7 +253,7 @@ public class IceMediaStream
{ {
synchronized(components) synchronized(components)
{ {
return new LinkedList<Integer>(components.keySet()); return new ArrayList<Integer>(components.keySet());
} }
} }
@ -265,10 +266,7 @@ public class IceMediaStream
*/ */
public int getStreamCount() public int getStreamCount()
{ {
synchronized(components) return getComponentCount();
{
return components.size();
}
} }
/** /**
@ -287,18 +285,24 @@ public class IceMediaStream
*/ */
protected void free() protected void free()
{ {
synchronized (components) List<Component> components;
{
for (Iterator<Component> i = components.values().iterator();
i.hasNext();)
{
Component component = i.next();
i.remove(); 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(); component.free();
} }
}
}
/** /**
* Removes <tt>component</tt> and all its <tt>Candidate</tt>s from the * Removes <tt>component</tt> and all its <tt>Candidate</tt>s from the
@ -312,8 +316,15 @@ public class IceMediaStream
synchronized (components) synchronized (components)
{ {
components.remove(component.getComponentID()); 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();
} }
/** /**

View File

@ -8,6 +8,7 @@ package org.ice4j.stack;
import java.io.*; import java.io.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
@ -159,6 +160,24 @@ class StunClientTransaction
*/ */
private boolean cancelled = false; private boolean cancelled = false;
/**
* The <tt>Lock</tt> 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
* <tt>cancel(boolean)</tt> may (and have be reported multiple times to)
* fall into a deadlock merely because they want to cancel this
* <tt>StunClientTransaction</tt>.
*/
private final Lock lock = new ReentrantLock();
/**
* The <tt>Condition</tt> of {@link #lock} which this instance uses to wait
* for either the next retransmission interval or the cancellation of this
* <tt>StunClientTransaction</tt>.
*/
private final Condition lockCondition = lock.newCondition();
/** /**
* Creates a client transaction. * Creates a client transaction.
* *
@ -236,16 +255,42 @@ class StunClientTransaction
* until a response is received, or a total of 7 requests have been sent. * 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 * If no response is received by 1.6 seconds after the last request has been
* sent, we consider the transaction to have failed. * sent, we consider the transaction to have failed.
* <p>
* The method acquires {@link #lock} and invokes {@link #runLocked()}.
* </p>
*/ */
public void run() 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.
* <p>
* The method assumes that the current thread has already acquired
* {@link #lock}.
* </p>
*/
private void runLocked()
{ {
// Indicates how many times we have retransmitted so far. // Indicates how many times we have retransmitted so far.
int retransmissionCounter = 0; int retransmissionCounter = 0;
// How much did we wait after our last retransmission? // How much did we wait after our last retransmission?
int nextWaitInterval = originalWaitInterval; int nextWaitInterval = originalWaitInterval;
synchronized(this)
{
for (retransmissionCounter = 0; for (retransmissionCounter = 0;
retransmissionCounter < maxRetransmissions; retransmissionCounter < maxRetransmissions;
retransmissionCounter ++) retransmissionCounter ++)
@ -263,18 +308,17 @@ class StunClientTransaction
try try
{ {
logger.fine( logger.fine(
"retrying STUN tid " + transactionID "retrying STUN tid " + transactionID + " from "
+ " from " + localAddress + localAddress + " to " + requestDestination
+ " to " + requestDestination + " waited " + curWaitInterval + " ms retrans "
+ " waited " + curWaitInterval + (retransmissionCounter + 1) + " of "
+ " ms retrans " + (retransmissionCounter + 1) + maxRetransmissions);
+ " of " + maxRetransmissions);
sendRequest0(); sendRequest0();
} }
catch (Exception ex) catch (Exception ex)
{ {
//I wonder whether we should notify anyone that a //I wonder whether we should notify anyone that a retransmission
//retransmission has failed // has failed
logger.log( logger.log(
Level.INFO, Level.INFO,
"A client tran retransmission failed", "A client tran retransmission failed",
@ -282,8 +326,8 @@ class StunClientTransaction
} }
} }
//before stating that a transaction has timeout-ed we should first //before stating that a transaction has timeout-ed we should first wait
//wait for a reception of the response //for a reception of the response
if(nextWaitInterval < maxWaitInterval) if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2; nextWaitInterval *= 2;
@ -298,7 +342,6 @@ class StunClientTransaction
stackCallback, stackCallback,
this.request, getLocalAddress(), transactionID)); this.request, getLocalAddress(), transactionID));
} }
}
/** /**
* Sends the request and schedules the first retransmission for after * Sends the request and schedules the first retransmission for after
@ -362,14 +405,19 @@ class StunClientTransaction
*/ */
void waitFor(long millis) void waitFor(long millis)
{ {
lock.lock();
try try
{ {
wait(millis); lockCondition.await(millis, TimeUnit.MILLISECONDS);
} }
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
finally
{
lock.unlock();
}
} }
/** /**
@ -393,9 +441,23 @@ class StunClientTransaction
if(!waitForResponse) 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,12 +477,15 @@ class StunClientTransaction
* *
* @param evt the event that contains the newly received message * @param evt the event that contains the newly received message
*/ */
synchronized void handleResponse(StunMessageEvent evt) void handleResponse(StunMessageEvent evt)
{
lock.lock();
try
{ {
TransactionID transactionID = getTransactionID(); TransactionID transactionID = getTransactionID();
logger.log(Level.FINE, "handleResponse tid " + transactionID); logger.log(Level.FINE, "handleResponse tid " + transactionID);
if( !Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE) ) if(!Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE))
cancel(); cancel();
responseCollector.processResponse( responseCollector.processResponse(
@ -431,6 +496,11 @@ class StunClientTransaction
request, request,
transactionID)); transactionID));
} }
finally
{
lock.unlock();
}
}
/** /**
* Returns the ID of the current transaction. * Returns the ID of the current transaction.