Use ReadWriteLock to split receive and close execution in SafeCloseDatagramSocket. (#166)

* Use ReadWriteLock to split receive and close execution in SafeCloseDatagramSocket.

* Me into authors lists.

* Removed empty try/finally
This commit is contained in:
Yury Yaroshevich 2018-12-19 21:29:42 +03:00 committed by bbaldino
parent 8b43209b8d
commit c56fcc3a3f

View File

@ -19,6 +19,7 @@ package org.ice4j.socket;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.concurrent.locks.*;
/** /**
* Represents a <tt>DatagramSocket</tt> which fixes the following problem: when * Represents a <tt>DatagramSocket</tt> which fixes the following problem: when
@ -29,22 +30,17 @@ import java.net.*;
* returns. * returns.
* *
* @author Lubomir Marinov * @author Lubomir Marinov
* @author Yura Yaroshevich
*/ */
public class SafeCloseDatagramSocket public class SafeCloseDatagramSocket
extends DelegatingDatagramSocket extends DelegatingDatagramSocket
{ {
/** /**
* The number of {@link #receive(DatagramPacket)} calls that have to return * A reader-writer lock to prevent {@link #close()} completion if any thread
* before {@link #close()} returns. * is blocked within {@link #receive(DatagramPacket)}.
*/ */
private int inReceive = 0; private final ReadWriteLock receiveCloseLock
= new ReentrantReadWriteLock();
/**
* The <tt>Object</tt> which synchronizes the access to {@link #inReceive}
* and implements the related inter-thread communication.
*/
private final Object inReceiveSyncRoot = new Object();
/** /**
* Initializes a new <tt>SafeCloseDatagramSocket</tt> instance and binds it * Initializes a new <tt>SafeCloseDatagramSocket</tt> instance and binds it
@ -143,22 +139,10 @@ public class SafeCloseDatagramSocket
{ {
super.close(); super.close();
synchronized (inReceiveSyncRoot) final Lock closeLock = receiveCloseLock.writeLock();
{ closeLock.lock();
boolean interrupted = false; // we now know all read threads have finished
closeLock.unlock();
while (inReceive > 0)
try
{
inReceiveSyncRoot.wait();
}
catch (InterruptedException iex)
{
interrupted = true;
}
if (interrupted)
Thread.currentThread().interrupt();
}
} }
/** /**
@ -182,21 +166,15 @@ public class SafeCloseDatagramSocket
public void receive(DatagramPacket p) public void receive(DatagramPacket p)
throws IOException throws IOException
{ {
synchronized (inReceiveSyncRoot) final Lock receiveLock = receiveCloseLock.readLock();
{ receiveLock.lock();
inReceive++;
}
try try
{ {
super.receive(p); super.receive(p);
} }
finally finally
{ {
synchronized (inReceiveSyncRoot) receiveLock.unlock();
{
inReceive--;
inReceiveSyncRoot.notifyAll();
}
} }
} }
} }