trebor iksrazal

Greenhorn
+ Follow
since Jun 28, 2004
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by trebor iksrazal

Hi all,

The code below attempts to do InetAddress.isReachable() on all possible IP's in a subnet, and try to do snmp walk on those that respond. This code works ok, albeit slowly - 25 seconds on a class A subnet. Even worse, on a big class A subnet, I get "java.net.ConnectException: No buffer space available" after around 1000 InetAddress.isReachable() calls.

Any ideas? You can look at the unabriged version here:

http://www.braziloutsource.com/random/PerfSnmpScan.java

Thanks,
iksrazal

[ added [code] tags - Jim ]
[ May 30, 2006: Message edited by: Jim Yingst ]
The problem:

1) Tomcat 3.3, struts, web client.
2) Launch the printing of 1000 (yes, one thousand) pdf files.

One developers idea is to return a response immediately - after
launching background threads to complete the tasks.

My intuition is that this a bad idea for at least one reason:

The servlet spec, as I understand it, allows a servlet container to
stop (destroy) an inactive servlet thread anytime it feels like it.

My question: what happens to background threads if the servlet is
detroyed by the container? Is this a likely scenerio in this
situation? Does the choice of daemon or non-daemon threads make the
solution any cleaner?

My immediate suggestion was to use JMS, which I myself have used a lot
in servlets but this project is a bit scared of JMS. I also have
doubts Tomcat 3.3 could support it. (I've used openJMS a lot with
tomcat 4.x).

iksrazal
This seems to be something that can work. Thanks!

I have two questions I am trying to solve on my own. Perhaps you can explain:

1)

if(t!= null || t1.isActive())

This doen't compile because t1 is not in scope, and also Thread does not have an isActive() method. Sometimes socket implementations have an isActive(), or perhaps you meant isAlive() - I'm not sure.

2) This code catches the Interrupted exception in the Runnable, but never exits. I'm not sure how to force an exit here.

Outside of that, I do appreciate everything and I'm working through your idea.

Thanks again!
iksrazal
I appreciate your help. Sorry if I'm not expressing my self clearly.

"Why are u trying to use Timer?"

I have two problems:

1) I need to do multiple client socket invokations simulatenously, which can time out.
2) I want to use threads for these calls.

I can get sockets to time out:

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

/**
Times out a socket using nio
*/
class NIOTest extends Object
{
static final int TIMEOUT = 10000;

public static void main(String[] args)
{
Thread task = new Thread(new Task());
TimerOut to = new TimerOut(task);
new Timer(true).schedule((TimerTask) to,TIMEOUT);
System.out.println(TIMEOUT + " milliseconds to socket timeout...");
task.start();
}

static class TimerOut extends TimerTask
{
Thread threadToTimeOut;

public TimerOut(Thread threadToTimeOut)
{
this.threadToTimeOut = threadToTimeOut;
}

public void run()
{
System.out.println("TimerOut running...");
threadToTimeOut.interrupt();
}
}

static class Task implements Runnable
{
Charset ascii = Charset.forName("US-ASCII");
String sendme;

public Task ()
{
;
}

public Task (String var)
{
this.sendme = var;
}

public void run()
{
SocketChannel sChannel = null;
try
{
// Create a non-blocking socket channel on port 2510
sChannel = createSocketChannel("10.200.200.144", 2510);

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

Thread.sleep(5000);
System.out.println(readFromChannel(sChannel));
Thread.sleep(15000);
}
catch (Exception e)
{
if (e instanceof InterruptedException)
{
System.err.println("Connecton timed out!");
}
else
{
e.printStackTrace();
}
}
finally
{
try
{
if (null != sChannel)
{
sChannel.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

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 void writeToChannel (SocketChannel sChannel, String send) throws IOException
{
CharBuffer cbuf = CharBuffer.wrap(send);
ByteBuffer buf = this.ascii.encode(cbuf);
sChannel.write(buf);
}

private String readFromChannel (SocketChannel sChannel) throws IOException
{
CharsetDecoder decoder = this.ascii.newDecoder();
ByteBuffer buf = ByteBuffer.allocate(1024);

sChannel.read(buf);
buf.flip();
CharBuffer cbuf = ascii.decode(buf);
return cbuf.toString();
}
}
}

Excuse the nio, but this is a simple example. It reads the data successfully
and then simulates a timeout.

Now, _WHY_ did I think I can do this in PooledExecutor?

http://altair.cs.oswego.edu/pipermail/concurrency-interest/2003-June/000459.html

It's a simple example, but I thought was possible to do this. Maybe not.

Thanks for your paitence,
iksrazal
"U need to have Runnable to start by timer. Timer is a thread. So once you pass task to the Timer, it will run at the scheduled time. You dont need to pass it a thread and try to start that thread later."

Actually in the traditional timer example I gave, it times out:

class TimerOut extends TimerTask {

Thread threadToTimeOut;

public TimerOut(Thread threadToTimeOut) {
this.threadToTimeOut = threadToTimeOut;
}

public void run() {
System.out.println("TimerOut running...");
threadToTimeOut.interrupt();
}
}

At the scheduled time, instead of running a task, I want to call Thread.interrupt() and cancel the operation.

What I want is the task that does the work, MyRunnable, to time out. Now I can do this by using the traditional example, by passing MyRunnable to the timer as you suggest:

Thread task = new Thread(new MyRunnable());
TimerOut to = new TimerOut(task);
new Timer(true).schedule((TimerTask) to,TIMEOUT);
task.start();

This works. But that only allows for one thread. What I want is multiple threads from a thread pool, working on MyRunnable. For example:

PooledExecutor pe = new PooledExecutor(3);
pe.execute(new MyRunnable());
pe.execute(new MyRunnable());
pe.execute(new MyRunnable());

How can I have multiple threads that can timeout a Runnable?
iksrazal
I want to do an operation inside a Runnable that could time out. I want to have several of these running at the same time. Timer/Timer task typically works like:

Thread task = new Thread(new Task());
TimerOut to = new TimerOut(task); //extends TimerTask
new Timer(true).schedule((TimerTask) to,TIMEOUT);
task.start();

However, I can't call Thread.start() inside a Runnable. Here's my idea, but unfortunately it never completes.

import java.util.*;
import java.io.*;

public class RunnableTimer
{
class MyRunnable implements Runnable
{
public void run()
{
java.util.TimerTask task = new TimerTask()
{
Thread thread = Thread.currentThread();
public void run()
{
System.out.println("Inside TimerTask run...");
thread.interrupt(); // interrupt work
}
};

Timer timer = new Timer();
timer.schedule(task, 3000);
try
{
// do interruptible work ...
System.out.println("Inside MyRunnable...");
}
finally
{
task.cancel();
Thread.interrupted(); // clear interrupt flag
}
}
}

public static void main(String args[])
{
new RunnableTimer();
}

public RunnableTimer()
{
try
{
(new Thread(new MyRunnable())).start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Any help would be greatly appreciated.
iksrazal
I'm having problems tuning a read operation. This method actually is
invoked by a client call, so it doesn't register OP_ACCEPT or anything
like that.

The problem is that this method's completion time is equivalent to the
Selector.select(milliseconds) time. If its 5000, it completes in 5
seconds. 1000 results in one second. I'd really like it do the read
and break out of the loop when its ready, somehow.

private String readFromChannel (SocketChannel
sChannel) throws IOException
{
CharsetDecoder decoder =
this.ascii.newDecoder();
ByteBuffer buffer = ByteBuffer.allocate(2048);
CharBuffer charBuffer =
CharBuffer.allocate(2048);
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 1000 mililiseconds timeout
while (selector.select(1000) > 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.isReadable())
{
// 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();
// Indicate successful operation
System.out.println("length of data read:
" + dataRead.toString().length());
hasRead = true;
}
}//end key.isReadable()
}//end while iterator
}//end while selector

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

return dataRead.toString();
}

Any ideas?
iksrazal