Cancelling an Executor thread

Discussion in 'Java' started by iksrazal, Jun 21, 2004.

  1. iksrazal

    iksrazal Guest

    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();
    }
    }
    }
    iksrazal, Jun 21, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kenneth P. Turvey

    Executor

    Kenneth P. Turvey, Sep 19, 2005, in forum: Java
    Replies:
    8
    Views:
    837
    Kenneth P. Turvey
    Sep 20, 2005
  2. Prafulla T
    Replies:
    5
    Views:
    557
    Chris Uppal
    Feb 7, 2007
  3. howa
    Replies:
    8
    Views:
    2,567
  4. Rakesh
    Replies:
    1
    Views:
    529
    Knute Johnson
    Oct 13, 2008
  5. Sven Marnach

    Cancelling a python thread (revisited...)

    Sven Marnach, Nov 8, 2009, in forum: Python
    Replies:
    10
    Views:
    2,426
    Antoine Pitrou
    Nov 9, 2009
Loading...

Share This Page