Flush() in Asynchronous NIO Channels

I wrote an asynchronous client-server socket implementation based fully on NIO Channels. My implementation does include old Socket or ServerSocket classes, I used only SocketChannel and ServerSocketChannel classes, with ByteBuffer's to send/receive data on non-blocking channel mode.
Everything looks very comfortable except one thing, looks like old FLUSH() method from OutputStream is still required in NIO. My small write requests (3 bytes length) does not reach the destination. I call write() several times but the read() doesn't get any data. So it looks like I need a flush for Channel, but Channel class don't have any flush() method.
I tried two solutions to solve this situation and FAILED:
1-) In Channels class there are newInputStream() and newOutputStream() methods to get InputStream and OutputStream's of ByteChannels. I used OutputStream's flush() method, but as you guess non-blocking mode does not let you to use write/read methods since they are in blocking mode, but my channels are in non-blocking mode. So I failed here.
2) I watched the actual data transmitted from TCP stack using Ethereal, what I see is my packets are send to the destination address SUCCESSFULLY. The problem looks like the receiver side does not take them immediately. I decreased the size of ByteBuffer used in read() at the receiver but nothing changed.
The point is my packets are still not readable from the destination address.

Well, NIO implementation looks different from Stream
implementation for sockets. I solved my problem by
decreasing the buffer size at the receiver side.
Sometimes read() of socket channel returns completely
filled and sometimes with half filled data. I can not
distinguish which one will come but at this point it
is enoughfor me...Yes, but my intent was simply to determine whether the data is receivable at all. However, you've now determined that it is.
In your place I would not be comfortable with the situation that now pertains. The mere fact that reducing the buffer size seems to make it work in your testing environment is hardly a demonstration that it works 100% of the time, nor that it will work properly in production. You need to be able to explain why the change works, and why the code fails with the larger buffer size.
Sylvia

Similar Messages

  • Java.nio.channels.IllegalBlockingModeException

    I am using selector for read and PrintWriter writer = new PrintWriter(new OutputStreamWriter(sc.getOutputStream()),true) for writing to the socket and I get this exception at write statement. Can anyone suggest me what should I do??
    java.nio.channels.IllegalBlockingModeException
    at java.nio.channels.Channels.write(Channels.java:59)
    at java.nio.channels.Channels.access$000(Channels.java:47)
    at java.nio.channels.Channels$1.write(Channels.java:134)
    at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:334)
    at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(StreamEncoder.java
    :402)
    at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(StreamEncoder.java:406)
    at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:150)
    at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:213)
    at java.io.PrintWriter.newLine(PrintWriter.java:256)
    at java.io.PrintWriter.println(PrintWriter.java:405)
    at java.io.PrintWriter.println(PrintWriter.java:516)
    at SktChannelTest3.run(SktChannelTest3.java:91)

    Hi,
    Thanx for the reply. I am using Selecotor for read and if it timesout I used PrintWriter to write to Socket ( Not socket channel). So, once it comes out of select loop, it'd excecute PrintWriter.println("Timeout message....") statement. And at this statement I/m getting exception.

  • DPS 11.1.1.5.0 java.nio.channels.ClosedChannelException

    Hi,
    I've upgraded today to 11.1.1.5.0 all my DS and DPS from 11.1.1.3.0 on Redhat 5.6 x64, Java(TM) SE Runtime Environment (build 1.6.0_27-b07)
    I get this on my proxy after a while:
    [29/Aug/2011:17:08:08 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:124 failed. java.nio.channels.ClosedChannelException
    [29/Aug/2011:17:08:08 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:124 failed. java.nio.channels.ClosedChannelException
    On the LDAP server I get
    [29/Aug/2011:17:22:49 +0300] conn=91 op=766568 msgId=1 - SRCH base="" scope=0 filter="(objectClass=*)" attrs="1.1"
    [29/Aug/2011:17:22:49 +0300] conn=91 op=766568 msgId=1 - RESULT err=0 tag=101 nentries=1 etime=0
    which is DOSing my log file.
    If I restart the proxy server the problem is gone for a while but it gets back after an hour or so thus making my whole LDAP infrastructure unusable.
    regards,
    Giannis

    I disabled proactive monitor for failed server and the problem didn't occur for 15 hours. Then I got the following.
    Just for the record, ldap.example.com is running on the same machine as DPS.
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:04 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:05 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Worker Thread 25. Abandon current operation.
    [30/Aug/2011:09:08:05 +0300] - BACKEND - WARN - Attempt to bind as to backend server ldap.example.com:389/ on connection server-example:165 failed. java.nio.channels.ClosedChannelException
    [30/Aug/2011:09:08:06 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Worker Thread 36. Abandon current operation.
    [30/Aug/2011:09:08:07 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Connection Handler 0 for Listener Thread 0.0.0.0:1636
    Exception thrown from thread Connection Handler 0 for Listener Thread 0.0.0.0:1636 java.lang.OutOfMemoryError: GC overhead limit exceeded
    [30/Aug/2011:09:08:07 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Connection Handler 0 for Listener Thread 0.0.0.0:1636. Disconnecting all client connections.
    [30/Aug/2011:09:08:08 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Connection Handler 1 for Listener Thread 0.0.0.0:1636
    Exception thrown from thread Connection Handler 1 for Listener Thread 0.0.0.0:1636 java.lang.OutOfMemoryError: GC overhead limit exceeded
    [30/Aug/2011:09:08:08 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Connection Handler 1 for Listener Thread 0.0.0.0:1636. Disconnecting all client connections.
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for ds.example.com:636/
    Exception thrown from thread Proactive Monitor for ds.example.com:636/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for dscc.example.com:3998/
    Exception thrown from thread Proactive Monitor for dscc.example.com:3998/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for dscc.example.com:3998/
    Exception thrown from thread Proactive Monitor for dscc.example.com:3998/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Proactive Monitor for ds.example.com:636/. No more monitoring running on ds.example.com:636/
    [30/Aug/2011:09:08:16 +0300] - EXCEPTION - ERROR - Fatal uncaughtException in Proactive Monitor for dscc.example.com:3998/. No more monitoring running on dscc.example.com:3998/
    [30/Aug/2011:09:08:17 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for ldap.example.com:2389/
    Exception thrown from thread Proactive Monitor for ldap.example.com:2389/ java.lang.OutOfMemoryError: Java heap space
    [30/Aug/2011:09:08:17 +0300] - EXCEPTION - INFO - Fatal uncaughtException in Proactive Monitor for ldapexample.com:3389/
    Exception thrown from thread Proactive Monitor for ldap.example.com:3389/ java.lang.OutOfMemoryError: GC overhead limit exceeded
    I changed all servers to reactive monitor and will see what's going on.
    Giannis

  • Java.nio.channels.ClosedChannelException using https

    Hello,
    I have deployed an application to the OC4J 10.1.3.40, it runs well as long as it is used by http. Since it is running under https an error comes randomly.
    Here is the text from the log.xml:
    <MSG_TEXT>Exception in NIOServerSocketDriver:selectForRead</MSG_TEXT>
    <SUPPL_DETAIL><![CDATA[java.nio.channels.ClosedChannelException
         at java.nio.channels.spi.AbstractSelectableChannel.configureBlocking(AbstractSelectableChannel.java:252)
         at oracle.oc4j.network.NIOServerSocketDriver$SelectorThreadTask.selectForRead(NIOServerSocketDriver.java:331)
         at oracle.oc4j.network.NIOServerSocketDriver.selectForRead(NIOServerSocketDriver.java:58)
         at oracle.oc4j.network.ServerSocketAcceptHandler.persistConnection(ServerSocketAcceptHandler.java:389)
         at oracle.oc4j.network.ServerSocketAcceptHandler.endReadHandlerRun(ServerSocketAcceptHandler.java:409)
         at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:275)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
         at java.lang.Thread.run(Thread.java:619)
    ]]></SUPPL_DETAIL>
    Can anybody help me?
    Regards
    Jens

    Jens,
    Can you turn up your debug level to FINEST? It appears that during the read operation an attempt to access a channel closed to read occurs.
    // Create binding -- set binding properties before you open the factory.
    OracleDBBinding odbBinding = new OracleDBBinding();
    // Create address.
    EndpointAddress odbAddress = new EndpointAddress("oracledb://ADAPTER/");
    // Create channel factory from binding and address.
    ChannelFactory<IRequestChannel> factory =
        new ChannelFactory<IRequestChannel>(odbBinding, odbAddress);
    // Specify credentials.
    factory.Credentials.UserName.UserName = "SCOTT";
    factory.Credentials.UserName.Password = "TIGER";
    // Open factory
    factory.Open();
    // Get channel and open it.
    IRequestChannel channel = factory.CreateChannel();
    channel.Open();-Michael

  • Java.nio.channels.NonWritableChannelException

    i have been facing this exception, please tell me how to remove it
    java.nio.channels.NonWritableChannelException
    here is my code
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    public class abc
         public static void main(String arg[])
              try
              File ff=new File("aaa.txt");
              FileInputStream fis=new FileInputStream(ff);
              FileChannel fc=fis.getChannel();
              FileLock lock=fc.lock();
              lock.release();
              fc.close();
              catch(Exception e)
                   System.out.println("hello22"+e);
    }

    what should i do then to make the channel writable . please tell me what to change in the code, i just want to lock the file and after that i will modify it.

  • Java.nio.channels.FileChannel jar file

    Hi
    I have used java.nio.channels.FileChannel package in my program.
    where can I get the jar file which has the above package?
    Thanx

    i give here sample code.. use this it will work fine..
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    public class copyImage
    public static void main(String [] args) throws IOException
    try {
    // Create channel on the source
    FileChannel srcChannel = new FileInputStream("dragonfly.jpg").getChannel();
    FileChannel dstChannel =new FileOutputStream("1.jpg").getChannel();
    // Copy file contents from source to destination
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    // Close the channels
    srcChannel.close();
    dstChannel.close();
    } catch (IOException e) {
    }

  • Java.nio.channels.Pipe?

    Someone explain what java.nio.channels.Pipe should be uses for, and how to use it?

    You can use this class to transfer the content of a channel from one thread to another thread.
    The writing thread blocks when the pipe is full.
    package com.desoft.pipetest;
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    public class PipeTest {
    public static void main (String args[])
    try
    FileInputStream fis = new FileInputStream(args[0]);
    FileChannel fc = fis.getChannel();
    Pipe p = Pipe.open();
    PipeReader pr = new PipeReader( p );
    Thread t = new Thread( pr );
    t.start();
    fc.transferTo(0, fc.size(), p.sink() );
    catch( IOException ioe )
    ioe.printStackTrace();
    * Read from a Pipe and write Content to System.out
    static class PipeReader implements Runnable
    Pipe p;
    public PipeReader( Pipe p )
    this.p = p;
    public void run()
    try
    ByteBuffer buffer = ByteBuffer.allocate( 10 );
    int len = 0;
    while( (len=p.source().read( buffer )) > 0 )
    buffer.rewind();
    for( int i = 0; i < len; i++ )
    System.out.print( (char)buffer.get());
    buffer.rewind();
    catch( IOException ioe )
    ioe.printStackTrace();

  • [svn] 1017: Bug: BLZ-95 - nio channels are not displayed in ds-console

    Revision: 1017
    Author: [email protected]
    Date: 2008-03-28 18:33:47 -0700 (Fri, 28 Mar 2008)
    Log Message:
    Bug: BLZ-95 - nio channels are not displayed in ds-console
    QA: Yes
    Doc: No
    Details:
    * Needed to update one of the containers in the ds-console client code for endpoint display, which contains a hardcoded list of endpoint types it pulls in.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/BLZ-95
    Modified Paths:
    blazeds/branches/3.0.x/apps/ds-console/console/containers/EndpointManager.as

    Addendum to original post - uncommenting the following code section and running both the client and the server eliminated the pauses, however the time required to perform the connections was slower than I hoped. The best I could achieve was about 1.25 seconds for 250 connections with a 20ms pause every 20 connections (dropping the pause less than 20ms or increasing the batch size more than 20 would result in connections taking 10-20 times longer!).
    /* if ((i % 20) == 0) {
    Thread.sleep(20);

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • Detect loss of socket connection using java.nio.channels.Selector

    I'm using the nio package to write a "proxy" type application, so I have a ServerSocketChannel listening for incoming connections from a client and then create a SocketChannel to connect to a server. Both SocketChannels are registered to the same Selector for OP_READ requests.
    All works fine, until either the client or server drops the connection. How can I detect this has happened, so my proxy app can drop the other end of the connection ?
    The Selector.select() method is not triggered by this event. I have tried using Selector.select(timeout) and then checking the status of each channel, but they still show isConnected()=true.
    Thanks,
    Phil Blake

    Please don't cross post.
    http://forum.java.sun.com/thread.jsp?thread=184411&forum=4&message=587874

  • Can I make Nio Channels non-interupptible ?

    I am writing modification to a series of files in turn using a FileChannel to make modifications to a file. I am trying to improve the performance of the code by multithreading it. But if a thread is interuppted (due to user cancelling task) whilst writing the the file it closes the FIleChannel, because nio is interuptible. I would rather an interruppt would allow files that are already being written to complete but would not start processing of any remaining files.
    I assuming this would leave the underlying file in a half written state, is this assumption right and if so is there any way I can make it not-interupptible.

    Hi, yes my code was in this form but I hadn't tried the Cancel. Cancel does work as required, but the problem is that I need to check each task to see if they encountered any errors , but if I make a get() call on a future task that has been cancelled it gives me a CancellationException.
    This is my code excerpt, if stopTask==true it indicates users wants to cancel, this can happen at any time.
    How can I improve this.
    boolean initiatedShutdown = false;
    for(Integer recNo:futures.keySet())
               if(!initiatedShutdown&&stopTask)
                    for(Integer recNo2:futures.keySet())
                           futures.get(recNo2).cancel(false);
                    initiatedShutdown=true;
                try
                    futures.get(recNo).get();
                catch(ExecutionException ee)
                      //handle error

  • Is java.nio.channels.FileLock thread safe ?

    Hello,
    I want to lock a file in exclusive mode. The 1.4.2 doc says the followings:
    File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
    File-lock objects are safe for use by multiple concurrent threads.
    I'm confused. If They are not suitable for controlling access to a file by multiple threads within the same virtual machine, How can they be safe for use by multiple concurrent threads ?
    thanks in advance...

    I think it means that you still need to synchronize your threads around the code that obtains the lock and writes data to the file.

  • Need an example of how to use java.nio.channels.FileLock

    Hi,
    I need to use the Filelock, but can�t find any examples on how to implement it -
    is it still used in Java 5.0?

    Would this be the correct way to check whether the file is already locked?
    public static void main(String[] args) throws Exception {
         FileOutputStream fos = new FileOutputStream("data.txt");
         FileLock fl = fos.getChannel().tryLock();
         if (fl != null) {
         System.out.println("Locked File");
         Thread.sleep(30000);
         fl.release();
         System.out.println("Released Lock");
         else{
              System.out.println("File is already locked!");
         fos.close();
         }

  • NIO verses IO

    Hi All,
    I am using java NIO socketchannel and ByteBuffers for my client/Server communication. It is in blocking mode and single threaded.
    Problem Description: From the results it seems that my NIO program is taking more time than old java io. It looks strange as i was expecting
    less time in communication using NIO.
    In my old IO program i am using underlying socket streams.
    Analysis results shows:
    1. sun.nio.ch.SocketChannelImpl.write() taking more time than java.io.ObjectOutputStream.writeObject().
    2. sun.nio.ch.SocketChannelImpl.read() taking more time than java.io.ObjectInputStream.readObject().
    Comparison report between IO and NIO are (for sending/receiving 10,000 messages of around 9K size, msg size is not fixed):
    Sender Program:
    NIO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 182635.0 ms - Sender_Final.main()
    100.0% - 182635.0 ms - Sender_Final.query()
    38.91% - 71078.0 ms - java.io.ObjectOutputStream.writeObject()
    36.31% - 66321.0 ms - SerializedData.<init>()
    *16.29% - 29769.0 ms - sun.nio.ch.SocketChannelImpl.write()*
    6.63% - 12119.0 ms - java.io.ByteArrayOutputStream.toByteArray()
    1.05% - 1935.0 ms - java.io.ObjectOutputStream.<init>()
    0.08% - 158.0 ms - java.io.ByteArrayOutputStream.<init>()
    0.07% - 138.0 ms - java.nio.DirectByteBuffer.put()
    IO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 23351.0 ms - SimpleSender.main()
    100.0% - 23351.0 ms - SimpleSender.query()
    *88.6% - 20690.0 ms - java.io.ObjectOutputStream.writeObject()*
    9.96% - 2327.0 ms - SerializedData.<init>()
    0.47% - 111.0 ms - java.io.ObjectOutputStream.reset()
    0.05% - 12.0 ms - java.io.ObjectOutputStream.flush()
    Receiver Programs:
    NIO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 176942.0 ms - Receiver_Final.main()
    100.0% - 176942.0 ms - Receiver_Final.serve()
    61.0% - 107935.0 ms - java.io.ObjectInputStream.readObject()
    *34.75% - 61494.0 ms - sun.nio.ch.SocketChannelImpl.read()*
    1.67% - 2957.0 ms - java.io.ObjectInputStream.<init>()
    0.39% - 707.0 ms - java.nio.DirectByteBuffer.get()
    0.09% - 163.0 ms - sun.nio.ch.ServerSocketChannelImpl.accept()
    0.05% - 103.0 ms - java.io.ByteArrayInputStream.<init>()
    IO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 27854.0 ms - SimpleReceiver.main()
    100.0% - 27854.0 ms - SimpleReceiver.serve()
    *98.78% - 27515.0 ms - java.io.ObjectInputStream.readObject()*
    0.13% - 37.0 ms - java.io.ObjectInputStream.<init>()
    0.08% - 25.0 ms - java.net.ServerSocket.accept()
    Any inputs here ? I am trying to achieve faster communication.
    Does NIO always guarantee speed improvement over old IO? If not under what conditions it is advice to use.
    I am using new InputStreams and OutputStreams for each message at both ends.
    For sending data( Few code snippet):==>
    while(true)
    ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    ObjectOutputStream oStream = new ObjectOutputStream( bStream );
    oStream.writeObject (serializedata);
    byteArray = bStream.toByteArray();
    objOutput.clear();
    objOutput.put(byteArray);
    objOutput.flip();
    numWrite = sc.write(objOutput);
    For receiving data ( Few code snippet):==>
    while(offset < limit)
    ByteArrayInputStream bStream = new ByteArrayInputStream(byteArray,offset ,limit - offset );
    ObjectInputStream iStream = new ObjectInputStream( bStream);
    serializeData = (SerializedData) iStream.readObject();
    offset = limit-bStream.available();
    }

    Hi Sorabain,
    I am not using ByteArrayOutputStream() in my old io programs and the code-snippet given here is for NIO program.
    You can see in the performance comparion that old io is not using
    ByteArrayOutputStream() or ByteArrayInputStream().
    Yes for one thing i have to look into that why SerializedData<init> is taking more time in NIO in compare to old IO. As this is my serialized data class.
    In my old IO program i am using underlying socket streams.
    Please see a more detailed report below which has the comparion of socketwrite in old and new io both, probably it may throw more light on the cause:
    Sender Program:
    NIO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 182635.0 ms - Sender_Final.main()
    100.0% - 182635.0 ms - Sender_Final.query()
    38.91% - 71078.0 ms - java.io.ObjectOutputStream.writeObject()
    36.31% - 66321.0 ms - SerializedData.<init>()
    *16.29% - 29769.0 ms - sun.nio.ch.SocketChannelImpl.write()*
    6.63% - 12119.0 ms - java.io.ByteArrayOutputStream.toByteArray()
    1.05% - 1935.0 ms - java.io.ObjectOutputStream.<init>()
    0.08% - 158.0 ms - java.io.ByteArrayOutputStream.<init>()
    0.07% - 138.0 ms - java.nio.DirectByteBuffer.put()
    Hot spots
    Name Percentage Time
    SerializedData.<init> 36.31 66321.0 ms
    java.io.ByteArrayOutputStream.write 34.38 62808.0 ms
    sun.nio.ch.SocketDispatcher.write  15.38  28094.0 ms
    java.io.ByteArrayOutputStream.toByteArray 6.63 12119.0 ms
    java.io.ObjectOutputStream$BlockDataOutputStream.getUTFLength 1.14 2098.0 ms
    java.io.ObjectOutputStream$BlockDataOutputStream.writeBytes 1.13 2076.0 ms
    Sender_Final.query 0.61 1117.0 ms
    java.nio.channels.spi.AbstractInterruptibleChannel.blockedOn 0.58 1076.0 ms
    java.io.ObjectOutputStream.writeObject0 0.56 1040.0 ms
    IO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 23351.0 ms - SimpleSender.main()
    100.0% - 23351.0 ms - SimpleSender.query()
    88.6% - 20690.0 ms - java.io.ObjectOutputStream.writeObject()
    9.96% - 2327.0 ms - SerializedData.<init>()
    0.47% - 111.0 ms - java.io.ObjectOutputStream.reset()
    0.05% - 12.0 ms - java.io.ObjectOutputStream.flush()
    Hot spots
    Name Percentage Time
    java.net.SocketOutputStream.socketWrite  85.86  20051.0 ms
    SerializedData.<init> 9.96 2327.0 ms
    SimpleSender.query 0.9 211.0 ms
    java.io.ObjectOutputStream$BlockDataOutputStream.writeBytes 0.8 188.0 ms
    java.io.ObjectOutputStream.defaultWriteFields 0.6 141.0 ms
    java.io.ObjectOutputStream$BlockDataOutputStream.writeInt 0.44 104.0 ms
    java.io.ObjectOutputStream$BlockDataOutputStream.getUTFLength 0.42 99.0 ms
    Receiver Programs:
    NIO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 176942.0 ms - Receiver_Final.main()
    100.0% - 176942.0 ms - Receiver_Final.serve()
    61.0% - 107935.0 ms - java.io.ObjectInputStream.readObject()
    *34.75% - 61494.0 ms - sun.nio.ch.SocketChannelImpl.read()* 1.67% - 2957.0 ms - java.io.ObjectInputStream.<init>()
    0.39% - 707.0 ms - java.nio.DirectByteBuffer.get()
    0.09% - 163.0 ms - sun.nio.ch.ServerSocketChannelImpl.accept()
    0.05% - 103.0 ms - java.io.ByteArrayInputStream.<init>()
    Hot spots
    Name Percentage Time
    java.io.ObjectInputStream$BlockDataInputStream.readUTFSpan 42.62 75425.0 ms
    sun.nio.ch.SocketDispatcher.read  34.27  60643.0 ms
    java.io.ObjectInputStream$BlockDataInputStream.readUTFBody 10.77 19071.0 ms
    Receiver_Final.serve 2.02 3583.0 ms
    java.io.ObjectInputStream.readClassDescriptor 1.06 1891.0 ms
    java.io.ObjectInputStream$BlockDataInputStream.<init> 0.85 1518.0 ms
    java.io.ObjectInputStream$PeekInputStream.readFully 0.64 1139.0 ms
    java.io.ByteArrayInputStream.read 0.63 1123.0 ms
    java.io.ObjectStreamClass$FieldReflectorKey.<init> 0.52 933.0 ms
    java.io.ObjectInputStream.readNonProxyDesc 0.48 855.0 ms
    java.io.ObjectInputStream.readSerialData 0.44 781.0 ms
    java.nio.DirectByteBuffer.get 0.39 707.0 ms
    java.nio.channels.spi.AbstractInterruptibleChannel.blockedOn 0.39 702.0 ms
    IO Program:
    Backtrace
    Description of CPU usage for thread main
    100.0% - 27854.0 ms - SimpleReceiver.main()
    100.0% - 27854.0 ms - SimpleReceiver.serve()
    98.78% - 27515.0 ms - java.io.ObjectInputStream.readObject()
    0.13% - 37.0 ms - java.io.ObjectInputStream.<init>()
    0.08% - 25.0 ms - java.net.ServerSocket.accept()
    Hot spots
    Name Percentage Time
    java.net.SocketInputStream.read  46.31  12900.0 ms
    java.io.ObjectInputStream$BlockDataInputStream.readUTFBody 16.81 4683.0 ms
    java.io.ObjectInputStream$BlockDataInputStream.readUTFSpan 14.5 4040.0 ms
    java.net.PlainSocketImpl.acquireFD 1.64 459.0 ms
    java.net.SocketInputStream.read 1.64 458.0 ms
    java.net.PlainSocketImpl.releaseFD 1.55 432.0 ms
    sun.security.provider.SHA.implCompress 1.09 305.0 ms
    SimpleReceiver.serve 0.99 277.0 ms
    java.io.ObjectInputStream.readString 0.95 266.0 ms
    java.util.HashMap$EntrySet.iterator 0.94 264.0 ms
    Edited by: herculeus on Oct 30, 2007 9:59 AM

  • Performance of java nio with dd in linux.

    Hi
    I ran this code in java to dump 0s in a file of size 1gb and tried the same with dd in linux.
    Java code : I use a preinitialized array (the data) and fill a mappedbytebuffer with it.
    package filePersistence.test;
    import java.io.File;
    import java.io.RandomAccessFile;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    public class TimeLineTest {
         private static final int BYTE_LENGTH = 1000;
         //this is the input
         static byte[] b = new byte[BYTE_LENGTH];
         public static void main(String[] arg) throws Exception
              //initializing the input
              for (int i=0;i<BYTE_LENGTH;i++)
                   b[i] = 0;
              File file = new File(arg[0]);
              RandomAccessFile raFile = new RandomAccessFile(file,"rw");
              FileChannel fChannel = raFile.getChannel();
              int loopCount = 1000000;
              MappedByteBuffer mbuffer = fChannel.map( FileChannel.MapMode.READ_WRITE ,0,loopCount * BYTE_LENGTH);
              //System.out.println(" going to fill in a file" + file.getName());
              long k = 0;
              long startTime = System.currentTimeMillis();
              for (int i=0;i<loopCount;i++)
         //populate the mapped buffer
                   mbuffer.put(b);
              //persist into the file
              mbuffer.force();
              long endTime = System.currentTimeMillis();
              System.out.println(" file filled size1 "+file.length());
              System.out.println(" time " + (endTime - startTime));
    On a linux machine this takes around 7 secs while dd used as
    "dd if=/dev/zero of=mytestfile.out bs=1000 count=1000000"
    1000000+0 records in
    1000000+0 records out
    1000000000 bytes (1.0 GB) copied, 4.618 seconds, 217 MB/s
    4.6 and 7 differ quite a lot. Is there a way the java code can be improved to match dd ?(-sever does not help)
    Thanks
    Sumanta

    Hi
    Can this be called a dd equivalent code ?
    package filePersistence.test;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.RandomAccessFile;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    public class TimeLineTest {
         private static final int BYTE_LENGTH = 1000;
         //this is the input
         static byte[] b = new byte[BYTE_LENGTH];
         public static void main(String[] arg) throws Exception
              //initializing the input
              for (int i=0;i<BYTE_LENGTH;i++)
                   b[i] = 0;
              String srcFile = arg[0] + "_src";
              FileOutputStream fos = new FileOutputStream(srcFile);
              fos.write(b);
              fos.getFD().sync();
              fos.flush();
              fos.close();
              RandomAccessFile srcraFile = new RandomAccessFile(srcFile,"rw");
              FileChannel srcChannel = srcraFile.getChannel();
              File file = new File(arg[0]);
              RandomAccessFile raFile = new RandomAccessFile(file,"rw");
              FileChannel raChannel = raFile.getChannel();
              int loopCount = 1000000;
              //MappedByteBuffer mbuffer = fChannel.map( FileChannel.MapMode.READ_WRITE ,0,loopCount * BYTE_LENGTH);
              //System.out.println(" going to fill in a file" + file.getName());
              long startTime = System.currentTimeMillis();
              for (int i=0,position=0;i<loopCount;i++,position+=BYTE_LENGTH)
         //populate the mapped buffer
                   //mbuffer.put(b);
                   raChannel.position(position);
                   srcChannel.transferTo(0, BYTE_LENGTH, raChannel);
              //persist into the file
              //mbuffer.force();
              raFile.getFD().sync();
              raChannel.close();
              raFile.close();
              long endTime = System.currentTimeMillis();
              System.out.println(" file filled size1 "+file.length());
              System.out.println(" time " + (endTime - startTime));
    }

Maybe you are looking for

  • Keyboard shortcuts not working in Photoshop CC

    I have photoshop CC through Creatuve cloud.  My keyboard shortcuts stop working, then photoshop really slows down, then crashes.  I've been through Adobe support five times now, and it works for about 1/2 hour, then acts up again.  Any suggestions/re

  • Re-installation fails for adobe acrobat 7.0 pro. No patch package present

    This patch package could not be obtained. Verify that this patch package exists and that you can access it, or contact the Application vendor to verify that this is a valid Windows installer patch package.Message when I try to reinstall after registr

  • BPM 11g Process Cubes dashboards limitations

    Hello, Does anybody knows if there is a time limit restriction for data stored in the Process Cube schema? Would it be available 'forever'? thanks Josue

  • Error in tiger

    I've upgraded to tiger 10.4.5. Now and then I get this error announcement - "the file is in use by another application". And It has happened in both final cut pro and Photoshop. No other application has been running though. Can it be the dahboard???

  • New Wildcard SSL certificate

    Guys, We had a certificate expire on our CAS servers that was used for webmail, autodiscover etc. WE had purchased a wildcard cert for use on the newly installed ADFS servers for our migration to office 365. Rather than renew the original SAN cert, I