Cancelling an Executor thread

I

iksrazal

I'm trying to timeout a thread using Doug Lea's concurrent package,
which has become Tiger's java.util.concurrent . Unfortunately I cannot
use tiger in this project. This code hangs and never exits. The
timeout is being called though.

Any ideas?
iksrazal

import java.util.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

import EDU.oswego.cs.dl.util.concurrent.Executor;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import EDU.oswego.cs.dl.util.concurrent.ThreadFactory;

/**
Times out a client socket call using nio
*/
class RunnableNIO
{
static final int TIMEOUT = 10000;

public static void main(String[] args)
{
java.lang.Runnable command = new Runnable()
{
private Charset ascii = Charset.forName("US-ASCII");
private SocketChannel sChannel = null;

public void run()
{
java.util.TimerTask task = new TimerTask()
{
Thread thread = Thread.currentThread();
public void run()
{
thread.interrupt(); // interrupt work
}
};

Timer timer = new Timer();
timer.schedule(task, TIMEOUT);
try
{
// do interruptible work ...
// Create a non-blocking socket channel on port 2501
sChannel = createSocketChannel("10.200.200.144", 2501);

//ASYNCHRONOUS - do something else HERE while waiting for
connection

// Before the socket is usable, the connection must be
completed
// by calling finishConnect(), which is non-blocking
while (!sChannel.finishConnect())
{
Thread.sleep(100);
//ASYNCHRONOUS - do something else HERE while waiting for
connection
}

System.out.println("first screen:");
Thread.sleep(5000);
System.out.println(readFromChannel(sChannel));

StringBuffer dataToSend = new StringBuffer();
dataToSend.append("someuser");
dataToSend.append("/");
dataToSend.append("somepasswd");
dataToSend.append("\r\r");
simpleWriteToChannel(sChannel, dataToSend.toString());

System.out.println("Wrote to " +
sChannel.socket().getInetAddress());

System.out.println("next screen:");
Thread.sleep(5000);
System.out.println(readFromChannel(sChannel));
}
catch (Exception e)
{
if (e instanceof InterruptedException)
{
System.err.println("Connecton timed out!");
}
else
{
e.printStackTrace();
}
}
finally
{
task.cancel();
Thread.interrupted(); // clear interrupt flag
try
{
if (null != sChannel)
{
sChannel.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.err.println("Finally executed...");
}
}

public SocketChannel createSocketChannel(String hostName, int
port) throws IOException
{
// Create a non-blocking socket channel
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
// Send a connection request to the server; this method is
non-blocking
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}

private String readFromChannel (SocketChannel sChannel) throws
IOException
{
CharsetDecoder decoder = this.ascii.newDecoder();
ByteBuffer buffer = ByteBuffer.allocate(1024);
CharBuffer charBuffer = CharBuffer.allocate(1024);
StringBuffer dataRead = new StringBuffer();
Selector selector = Selector.open();
boolean hasRead = false;
// Register read activity on socket
sChannel.register(selector, SelectionKey.OP_READ);
// Read response with 2000 mililiseconds timeout
while (selector.select(2000) > 0)
{
System.out.println("selector looping...");
// Get set of ready objects
Set readyKeys = selector.selectedKeys();
Iterator readyItor = readyKeys.iterator();
// Walk through set
while (readyItor.hasNext())
{
System.out.println("iterator looping...");
// Get key from set
SelectionKey key = (SelectionKey)readyItor.next();
// Remove current entry
readyItor.remove();
// Get channel
SocketChannel keyChannel = (SocketChannel)key.channel();
if ((key.readyOps() & SelectionKey.OP_READ) != 0)
{
// Read what's ready in response
while (keyChannel.read(buffer) > 0)
{
// Make buffer readable
buffer.flip();
// Decode buffer
decoder.decode(buffer, charBuffer, false);
// Build string recieved
charBuffer.flip();
dataRead.append(charBuffer);
// Clear for next pass
buffer.clear();
charBuffer.clear();
hasRead = true;
}
}//end key.readyOps()
}//end while iterator
}//end while selector

if (false == hasRead)
{
throw new IllegalStateException ("Socket read operation
timed out");
}

return dataRead.toString();
}

private void simpleWriteToChannel (SocketChannel sChannel,
String send) throws IOException
{
CharBuffer cbuf = CharBuffer.wrap(send);
ByteBuffer buf = this.ascii.encode(cbuf);
sChannel.write(buf);
}
}; //end interface definition Runnable

PooledExecutor executor = new PooledExecutor(1);
try
{
executor.execute(command);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top