Question on asynchronous AsynchronousSocketChannel#write

Leon Finker leonfin at optonline.net
Fri Apr 24 11:04:26 PDT 2009


Thank you. I will look at the example. I'm not 100% sure. I'm positive I'm
not using the buffer concurrently.

-----Original Message-----
From: Alan.Bateman at Sun.COM [mailto:Alan.Bateman at Sun.COM] 
Sent: Friday, April 24, 2009 1:43 PM
To: Leon Finker
Cc: nio-discuss at openjdk.java.net
Subject: Re: Question on asynchronous AsynchronousSocketChannel#write

Leon Finker wrote:
>
> Hi,
>
> Are there any samples on properly using:
>
> AsynchronousSocketChannel#write(ByteBuffer src, A attachment, 
> CompletionHandler<Integer,? *super* A> handler) ?
>
> I'm looking for a best practice example for completed() callback for 
> async write. Can Integer result that is passed to us (in completed 
> callback) be less than the ByteBuffer size that we specified in the 
> write method call? I actually see a case that the result I get in 
> completed callback() for write is bigger than the original ByteBuffer 
> capacity under stress. I'm probably doing something wrong, so I wanted 
> to see a best practice example. I'm on b56. Thank you
>
We don't have any "best practice" documentation but a good idea to have. 
The Grizzly repository [1] has a port to this API and may be a useful 
place to find example code. Short writes are possible (meaning a write 
may complete having written less than the remaining bytes). You are 
probably using hasRemaining to check this in the handler and if there 
are remaining bytes you can initiate another write on the buffer with 
"this" as the handler. It's hard to say much about the problem you are 
seeing. A write attempts to write the remaining bytes and it would be a 
serious overflow bug if it actually wrote more than the buffer's 
capacity. Are you 100% sure this is really happenin.g? You'll see a 
number of warnings in the javadoc about ByteBuffers not being safe for 
use by concurrent threads. Any chance you have a bug where you are using 
the same buffer for two or more concurrent I/O operations. The 
implementation defends against changes to the buffer position during I/O 
operations to prevent attacks but if you are using the same buffer 
concurrently then you may see strange results.

-Alan.

[1] https://grizzly.dev.java.net/source/browse/grizzly/




More information about the nio-discuss mailing list