What does this paragraph straight from http://java.sun.com/j2se/1.4.2/docs/api/java/nio/channels/Selector.html javadocs on NIO mean regarding how to interrupt a select using close()?:
[quote]A thread blocked in one of the select() or select(long) methods may be interrupted by some other thread in one of three ways:
By invoking the selector’s wakeup method,
By invoking the selector’s close method, or
By invoking the blocked thread’s interrupt method, in which case its interrupt status will be set and the selector’s wakeup method will be invoked.
The close method synchronizes on the selector and all three key sets in the same order as in a selection operation.
[/quote]
The first part says that selector.close() will interupt the select(), but then it says that close() locks on the same keys as select(), meaning that it will wait forever until the select() is complete before closing. So which should it be. What I am seeing is that close() does not interrupt the select, but waits for select to finish. Is this a bug, or by design?
Then down below in the close() method it states:
[quote]If a thread is currently blocked in one of this selector’s selection methods then it is interrupted as if by invoking the selector’s wakeup method.
Any uncancelled keys still associated with this selector are invalidated, their channels are deregistered, and any other resources associated with this selector are released.
[/quote]
However, this is not the case. Simple example:
import java.nio.channels.Selector;
public class SelectorDeadlock implements Runnable
{
Thread _thisThread = null;
Selector _selector = null;
public SelectorDeadlock( )
{
}
public static void main(String[] args)
{
SelectorDeadlock sd = null;
try
{
sd = new SelectorDeadlock( );
sd.start();
// wait 3 seconds
Thread.currentThread().sleep( 3000 );
// now try to close and see the deadlock
sd.closeSelector();
}catch( Exception e )
{
sd.stop();
e.printStackTrace();
}
}
public void start( )throws Exception
{
if ( _selector == null )
{
_selector = Selector.open();
}
if ( _thisThread == null )
{
_thisThread = new Thread( this, "SelectorDeadlock" );
_thisThread.start();
}
}
protected void stop()
{
if ( _thisThread != null )
{
Thread threadTemp = _thisThread;
_thisThread = null;
threadTemp.interrupt( );
}
}
public void closeSelector( )throws Exception
{
if ( _selector != null )
{
System.out.println("Attempting to close selector");
_selector.close();
System.out.println("Selector has been successfully closed");
}
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run()
{
while ( _thisThread != null )
{
try
{
_selector.select();
}catch( Exception e )
{
e.printStackTrace();
}
}
}
}
This is on windows running 1.4.2beta and 1.4.2_01
Any feedback. I just checked java bug report and didnt see this anywhere. It seems too obvious to be wrong.