Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Cancelling an Executor thread

Reply
Thread Tools

Cancelling an Executor thread

 
 
iksrazal
Guest
Posts: n/a
 
      06-21-2004
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();
}
}
}
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
An Executor-like structure providing more than threads Tom Anderson Java 12 01-21-2010 11:51 PM
Is Executor class thread-safe Rakesh Java 1 10-13-2008 02:07 AM
Parallel processing using Executor? howa Java 8 08-15-2007 10:37 AM
Looking for Program Executor class in java Prafulla T Java 5 02-07-2007 07:05 PM
Executor Kenneth P. Turvey Java 8 09-20-2005 08:33 PM



Advertisments