views:

77

answers:

2

Hi all,

I was told that any data going out over an output stream (i'm using tcp/ip in my case) could block. In that case, I would not want to halt the application by having to wait for data to go out.

I need a model of how to do this.

I need to send message objects over this stream.

I am thinking I need a blocking queue that contains these message objects. The thread's run() method would grab any message objects that are available and send them, while true.

My questions are 1) Is there a better way to do this than a while true loop? Perhaps in the while true loop if there are no messages to send, I can tell the thread to yield/sleep.

2) Is there a better model to use? I am concerned that if I have a while(true) in my code that it will eat processor cycles waiting for messages.

Please, someone who has experience with this, let me know if there's a better way about this.

Thanks, jbu

A: 

That's a fine mechanism, as long as your queue is a blocking one. You will automatically yield the processor while waiting for another message to arrive on the queue.

If you read the queue in a non-blocking fashion, then you will waste a lot of CPU time. You generally have to try harder to do that, but it all depends on the type of Queue you use.

Chris Arguin
A: 

hi...

Java has implemented two ways of doing this: by blocking methods (which you have already addressed) or by non-blocking methods.

For the easiest way to get to asynchronous communication by blocking methods you can take a look at this answer: question 1041014

If you want to use non-blocking methods, you have to take a look at the NIO framework. It is not particularly easy to implement in the beggining because it uses several complicated concepts, but once you get to understand how to handle the communication events it is pretty simple to make powerfull implementations. At the end you will end up using blocking methods because the CPU time is unnecesary to waste, but the NIO framework will let you create a single thread communication implementation which will be very optimal for cpu and memory usages.

Take a look at the O'reilly NIO book.

Oso