How to increase write speed using queues

Hi,
    I am using a vi to read in two sets of data over a serial port.  I then write the data to a spreadsheet.  I do this by sending the data to a queue when I depress a record data button on the vi.  The queue then  writes the data to a file in another loop.  I based this off of a producer consumer architecture.  The setup works great but I have noticed that when record data for long periods of time (2 minutes or more) it takes an extremely long time after I have stopped recording data for the information to be written to a file.  Is there anyway to improve my write to file speed?  Thanks for all of your help and I am attatching my VI.
Solved!
Go to Solution.
Attachments:
Read_Write_Transmit_Record_IMU_V_4.vi ‏89 KB

Yes. you could definitely accumulate the data in a 2-D array in the producer.
What I would do, since now you are adding more requirements to the code, would be to turn to add an enum along with the data you send through the queue to the consumer loop.  The enum would be commands such as Open File, close file, log data, write to file, exit loop.  Attached is an example of one I wrote that I encapsulated in a subVI that runs parallel to other code.
Attachments:
CTA Data Logger text.vi ‏55 KB

Similar Messages

  • How to increase the speed of video (avi file) using labview

    How to increase the speed of video (.avi file) using labview? I have  tried this by skiping alternate frames. also I have used  minimum time delay.Is there  any other option for which i can go?
    please suggest me........... 

    Are you using NI Vision IMAQ AVI Read Frame or anther method to read the AVI file?
    Matthew Fitzsimons
    Certified LabVIEW Architect
    LabVIEW 6.1 ... 2013, LVOOP, GOOP, TestStand, DAQ, and Vison

  • How to increase execution speed ??

    Hi,
    i want to know (if it is possible...) how to increase the speed execution of an application ??
    Thanks in advance
    Steve

    Depends on what kind of application it is, where you want the speed increase, and whether you can pay for it with additional memory usage.
    On general optimisations, there are two schools of thought.
    The academic side says, write your application without doing any optimisations, and then optimise the bits that ou can show to be bottle necks. While this produces elegant code, the result can be very hard to optimise when you need to.
    So I say; design with optimisation in the back of your mind. For example, if you need to access objects with great speed, then avoid interfaces if you can, because they will slow your code considerably, even if they do make it reuseable. Avoid massive creation of objects - for example string concatenation using + is very slow - use a stringbuffer instead if you have many to do.
    For smaller increases in speed in algorithms and such, consider creating a local reference in a method to a class object, and using short in place of int in loops. Unroll as many loops as you can. Avoid making repeated reads to the same value in an array - hold it in a temporary variable instead.
    For every optimisation you make, your program will get increasingly hard to read and maintain.
    Do you have some more detail on what it is you want to speed up?

  • How to increase the speed of Zoom on TIFF image

    Hi everyone,
    i m doing zooming operation on tiff image.
    when i applied zoom in operation on image which have properties
    Bit per sample =1
    Image Length = 2200 Pixel
    Image Width = 1700 Pixel
    Resolution(x) = 200 dpi
    Resolution(y) = 200 dpi
    then it require 2 sec.
    then i apply the same code with tiff image which have properties like,
    Bit per sample =1
    Image Length = 3300 Pixel
    Image Width = 2500 Pixel
    Resolution(x) = 300 dpi
    Resolution(y) = 300 dpi
    then it require 9 to 10 sec.
    my code is:
    RenderedImage src= oriRndImage[selectedButtonIndex];(orirndImage is Rendered
    Iamge)
    //Transfer Current RenderedImage object into BufferedImage object
    Raster ra= currRimage.getData(); //it take time.
    DataBuffer db = ra.getDataBuffer();
    SampleModel sa = ra.getSampleModel();
    ColorModel cm = currRimage.getColorModel();
    final BufferedImage currImage = new
    BufferedImage(cm,Raster.createWritableRaster(sa,db,null), false, new
    Hashtable());
    //Create new Bufferred Image
    BufferedImage bi = new BufferedImage(zoomW,zoomH, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    double scaleW = (double)(zoomW)/(double)(prev_width);
    double scaleH = (double)(zoomH)/(double)(prev_height);
    transAtZoom = AffineTransform.getScaleInstance(scaleW,scaleH);
    g.drawRenderedImage(src, transAtZoom);
    can any one plz suggest me the way ,how to increase the speed. of Zoom effect?
    how to handle this problem?
    thnxs..

    Are you using NI Vision IMAQ AVI Read Frame or anther method to read the AVI file?
    Matthew Fitzsimons
    Certified LabVIEW Architect
    LabVIEW 6.1 ... 2013, LVOOP, GOOP, TestStand, DAQ, and Vison

  • How to increase the speed of producer-c​onsumer architectu​re

    Hey everyone -
    This is a follow-up to a previous thread that I had posted (
    http://forums.ni.com/t5/LabVIEW/How-to-use-a-dynam​ic-true-false-signal-with-a-case-structure/m-p/114​...
    ), but my next question has taken a bit of a different direction so I have made a new thread. 
    Following tbob's suggestion, I am trying to use a producer-consumer architecture to start and stop data acquisition from a simulated NI 9237 device.  I have attached the current version of our code to this post (Producer_Consumer_architecture.vi).  Our main problem is that there is a significant lag between when elements get added to the queue using the Enqueue function, and when they are removed from the queue using the Dequeue function. As a result, the signals from our simulated DAQ channels run for much longer than they are supposed to, and the start-and-stop of data acquisition is not keeping in time with the simulated square wave signal (we would like our NI 9237 device to acquire data when the square wave has an amplitude over 3, and stop acquiring when the amplitude is under 3).  If you allow the program to run for about 30 seconds, you will see what I mean (press the stop button twice to quit the program).
    If anybody has any suggestions as to how we can increase the speed of the program, they would be very much appreciated!
    Thanks in advance!
    Attachments:
    Producer_Consumer_architecture.vi ‏122 KB
    Save_data.vi ‏14 KB

    hello,
    i don't have tools needed but , i see one thing is that you enqueue 
    every time you are greater 3 that means about every 2-3 ms so consumer is really   sought
    is it really what you want ?
    may be you want to start on a treshold so you can use a treshold fonction 
    if i don't make mistake your square is 10 hz and the daq is configured 25000 sample 25000 hz
    so you aquire 1s of signal every 100ms , there is something to correct
    make tests and tell us
    Regards
    Tinnitus
    CLAD / Labview 2011, Win Xp
    Mission d'une semaine- à plusieurs mois laissez moi un MP...
    RP et Midi-pyrénées .Km+++ si possibilité de télétravail
    Kudos always accepted / Les petits clicks jaunes sont toujours appréciés
    Don't forget to valid a good answer / pensez à valider une réponse correcte

  • How to increase the speed of my producer loop?

    Hi,
    I try to monitor two CAN channels and to compare values online. That's why I use a producer loop to collect all CAN messages and a consumer loop to calculate some stuff. But the producer is to slow. The queues of my CANCard are full after some minutes. The queues are already set to maximum.
    The first Channel runs with 500 kBit/s, the second one with 125 kBit/s.
    Should I use two Producer loops or how can I increase the speed of my existing producer?
    How should I handle the different speed of the channels?
    Enclosed screenshots from my VI.
    Thanks,
    Thomas
    Attachments:
    producer.jpg ‏66 KB
    receive.jpg ‏38 KB

    Andy,
    thanks for your support!
    Goal of my project is to measure both CAN channels. Between these channels is a real electronic control unit (ecu) which is able to route CAN messages between the channels. My VI has to check weather the routing works fine or not.
    Each message has an identifier and I kow which messages are routed. That means I have to measure both channels, look for routed messages and compare the data and the timestamp of the messages. I try that in my consumer loop. The data are stored in several 2d arrays. And I have to look for specific data in these arrays. I think the loops over the arrays are to slow. but I have no other chance - I have to buffer the messages somehow and then to compare by their timestamps to find the right order. But that's very difficult because the order of the messages in my producer queue is not ordered by the timestamp...
    If you have any idea how to solve the problem better, let me know - I would be happy!
    Thanks,
    Thomas

  • How to increase download speed on osx mountain lion imac

    My internet connection is 4mbps wired broadband.previously I downloaded at the speed of 300 to 415 kbps.now it reduced to 50 to 60 kbps.how to increase the download speed on my imac.

    This isn't a function of your Mac; it's either your ISP or your router that is causing slow performance.
    Make certain that you really are using a wired - only connection. Turn off AirPort to be sure.
    Try resetting your router. If that doesn't fix things complain to your ISP. They will want you to connect a computer directly to your modem and run whatever speed testing software they use. Their responsibility ends with the equipment they provide.

  • Increasing Write Speeds while saving files?...

    While i love Photoshop, its performance can be a huge concern. Lately, i upgraded my workstation from a 4 year old desktop and went all out...
    Here are the specs of the new system.
    2 x X5670 (12 Nehalem 2.93Ghz cores)
    48GB of ECC RAM
    3 x 50GB (raid 0 on LSI 5150 sata 3 raid card) Sandforce SSD drives that give me sequential read/write speeds of approx 800MBps.
    My issue is that i hate the way photoshop writes data while saving PSD files. I cant seem to see photoshop write to disk at speeds greater than 12-15 MBps. This has become the slowest link in the entire photoshop work flow and is slowing me down considerably.
    The other option i was trying to investigate is to edit loads of files and then do an equivalent of a bulk save but i cant find a trick to do that.
    thoughts?

    thanks Noel for the speedy response. I will admit that i oversimplified my setup but here is the full info for my setup...
    I gave the save as tiff a go but DID see a dramatic increase!!
    C Drive:
    T Drive: 40GB Fusion i/o PCI card. Photoshop uses this as the scratch disk (under preferences --> general --> performance).
    P.S: my systems temp variables (user and env) etc are all redirected to this drive.
    I have a D Drive (Raid 5 across 6 x 2TB drives that i use purely for storage)
    Here is what all i am doing...
    Open a raw nef file,
    Use define to reduce noise (automatic profile)
    Use Viveza to adjust brightness/contrast/structure/warmth
    save the file
    These are some timings...
    Loading photoshop --> 4.5 sec
    Opening a D7000 16MPix raw image --> 8.5 sec (file opens in camera raw and then i click open to open in photoshop)
    Times to save processed files...
    PSD: 28.5 seconds!!!!
    Tiff: 2.5 seconds!!! yes 2.5 seconds (you barely see it save!!)
    You are the man...
    i would assume that i have the CPU and RAM horsepower to have photoshop do a good job at the compression while saving but the diffrence is huge!!!
    now please tell me what do i lose (if anything) in moving to the Tiff format (preserving all layers)

  • How to increase the Speed of USB Devices (6501 and 6009)?

    Hy guys!
    My question is:
    In datasheets of the USB devices, the only reference about the speed of
    these boards is the Bus Interface speed (12Mbit/s). But in my
    application (i'm trying to use delphi to control the device), each
    instruction, doesn't matter if is a write or a read function, is taking
    1ms to execute. Could i increase this speed?? What could be wrong?
    OBS: I updated the Ni-DaqmxBase 1.4 to the new NI-DaqMx 7.5, and notting has changed.
    Functions used:
    istatus := DAQmxWriteDigitalU32(TaskEscrever, 1, 0, -1, DAQmx_Val_GroupByChannel, @writedata,nil, nil);
    istatus := DAQmxReadDigitalU32(taskLer, -1, 10, DAQmx_Val_GroupByChannel, @readdata[j], 1,nil, nil);

    Hello,
    The two usb DAQ from NI are full speed interface (as you said 12M/s bus speed). The full speed interface has a frame size of 1ms, the root hub transmits a packet every 1.0 ms and this is the minimum time that you can read/write from/to usb device, normally because of the windows scheduling, 1ms is very tight, windows may miss it in some occasions, some usb device designers would prefer to use something between 2ms - 10ms polling period, which means some devices may even react to commands within 2ms - 10ms. But it looks like the two NI usb DAQ use the 1ms polling period and that is the shortest time you can get in software paced mode. If you need very fast digital update rate, you may need to look at PWM output, it generates digital pulses at very fast rate as the link given below, the iUSBDAQ - U120816 can generate PWM pulse from 3kHZ - 333kHZ.
    NI USB DAQ maybe good, but it wouldn't hurt to look at some other company's product too. the below link of usb daq gives the best price/performance ratio, LabVIEW vis are very easy to use and you avoid the pre-configuration in a separate application for DAQs which sometimes may be big deal if your customers are not engineer or scientist, but regular computer users. You are welcome to compare.
    http://www.hytekautomation.com/Products/IUSBDAQ.html
    Thank you.
    Irene

  • How to increase scroll speed in multi-record block

    My form displays 15 record at a time.
    I'm expecting that query will return approximate 100-1000 records. Scrolling between this records is very slow.
    Now i'm asking how can or must i set "Query array size","Number of Records Buffered" or can i set "Query All Records" to increase scrolling speed?

    Denis,
    Query All Records will go the other way. It might be faster when scrolling, but will take ages before being loaded to the Forms client (from the database to the server). Best would be if you can limit the number of returned records using the where condition of a block before querying it.
    Beside of that, using a different value of "Query array size","Number of Records Buffered" is the way to go.
    Frank

  • Satellite A665 - How to increase WLAN speed?

    Hi There
    I have 2 notebooks at home. One is A300 (Windows Vista 32bit) and the newer one is A665 (Windows 7/64 bit). My wireless router is US Robotics USR 9108A compatible for the both systems.
    A300's wireless internet speed is about 8Mbs but A665' s speed is about 0,7Mbs. How can I increase the speed of A665? What can cause this?
    Any help will be appretiated.

    Hi buddy,
    I had a similar problem on my new Satellite A660 and the problem was power saving mode of WLAN card...
    In Windows Power Management you can choose different power saving modes for WLAN card. You have to turn off power saving (=> High Performance) for WLAN card and then you will have the highest possible WLAN speed.
    This article explains all functions about Power Saving:

  • How to increase the speed on my mini mac

    What is the best way to increase the speed for my mini mac?
    10.4.11
    1.33 ghz
    512 MB drsd ram

    The max RAM for your Mac Mini http://www.everymac.com/systems/apple/mac_mini/specs/mac_mini_g4_1.33.html is 1GB. Increasing to the max RAM will help.
    How much free space do you have on your hard drive. An almost full HD can cause slowness.
    Mac OS X: System maintenance
    http://discussions.apple.com/thread.jspa?messageID=607640
    Mac Tune-up: 34 Software Speedups
    http://www.macworld.com/article/49489/2006/02/softwarespeed.html
    52 Ways to Speed Up OS X
    http://www.imafish.co.uk/articles/post/articles/130/52-ways-to-speed-up os-x/
    Tuning Mac OS X Performance
    http://www.thexlab.com/faqs/performance.html
    11 Ways to Optimize Your Mac's Performance
    http://lowendmac.com/eubanks/07/0312.html
    The Top 7 Free Utilities To Maintain A Mac.
    http://mac360.com/index.php/mac360/comments/the_top_7_free_utilities_to_maintain _a_mac/
     Cheers, Tom

  • How to increase cal. speed

    Dear Lab VIEW Engineer
    I used lab VIEW to make machine vision system.
    The analog mage graber  from interface with max frame is 30 /s was used.
    I am using computer with Core i7 3.4 Ghz, 8GB Memory and  windows 7 32 bit.
    My question is, why maximum calculation for measurement is only 15 data/s?
    How to increase up to 30 data/s?
    Herewith the machine vision program to capture the image and for image processing.
    Thank you
    Best regards
    Sugeng
    添付:
    Capture2 (1)-ok-realtime-macro-vertical-for calibration-simple-toNI.vi ‏40 KB
    Vertical_macro_lens-8-1position-sobel-3.vi ‏29 KB

    Dear sugeng
    I examined your VI but there are many ways you can improve the performance.
    Firstly, you have a while loop enclosing the whole code which may lead to unnecessary code repetition.
    You seem to be using an old IMAQ VI to acquire images from a camera,
    but VIs such as ImgOpen.vi should able to be left outside the loop.
    Especially if there is an ImgClose.vi, you should be able to leave those two VIs outside the loop
    and only call them when you start and finish the code.
    The same can be said for IMAQ Create and IMAQ Dispose.
    IMAQ Create creates a buffer for an image so it takes some processing time.
    You seem to be trying to use the same buffer for your image,
    (i.e. once processing is completed, you do not need the image from the previous loop)
    but if that is the case, I suggest leaving IMAQ Create and IMAQ Dispose outside the loop,
    in order to use the same image buffer and not keep recreating it.
    You have successfully done this with your File I/O function so you should do the same with other functions.
    However, in terms of memory performance, I suggest placing a Close File function outside the loop after writing into your file.
    If you do not close your file after opening it, this may lead to memory leaks and file access issues.
    You can find the Close File in your functions palette; Programming>>File I/O.
    On a memory performance note,
    you have some coercion dots (the red dot displayed on an input of a function/VI) near the end of your code,
    but they take up memory and may in turn decrease the performance of your VI,
    so I recommend converting wires to appropriate datatypes before connecting them to inputs with a different datatype.
    You can use the functions in Programming>>Numeric>>Conversion from the functions palette.
    Kind regards
    Taiki Hoshi
    Applications Engineer
    NI Japan

  • M30: Connect only with 42.6K - How to increase the speed

    My M30 connect only with 42.6K speed. I try all options to increase the speed but success. If any one have the solution, please send me email at [email protected]
    I try the other series on my telephone line and those connect at 52 to 54K speed. Even Desktop connect at 54K.

    Hello
    Please go to the device manager and choose the modem. Then right click and properties.
    There you will find a many tabs. Please check if the option Maximum port speed in the Modem tab is set to highest value.
    Furthermore you can check in the Advanced tab the button Advanced Port settings The controller should be also set to the high (max).
    Please check these possibilities.
    Bye

  • How to increase the speed of network file transfer

    hi ,
    In my application i want to use the file from one system to another system.
    i am using stream reader to get the file over the network , its working fine for small file,
    but i want to access file size exceed 10 MB then i faced the problem. Its get very slow the file transfer over the network.
    so i am try to use java NIO for transfer file,
    Using NIO , While i am make server and client both are same system then the file tranfer is 10MB file in 10 seconds , but i am making server and client are different machine then its take so long to transfer file ie (10 MB file in 3 minutes).
    I want to reduce the time . If any chance to reduced the file transfer time then please suggest me.
    my code is
    Server Code :
    public class NioServer implements Runnable {
      // The host:port combination to listen on
      private InetAddress hostAddress;
      private int port;
      // The channel on which we'll accept connections
      private ServerSocketChannel serverChannel;
      // The selector we'll be monitoring
      private Selector selector;
      // The buffer into which we'll read data when it's available
      private ByteBuffer readBuffer = ByteBuffer.allocate(10000);
      private EchoWorker worker;
      // A list of PendingChange instances
      private List pendingChanges = new LinkedList();
      // Maps a SocketChannel to a list of ByteBuffer instances
      private Map pendingData = new HashMap();
      public NioServer(InetAddress hostAddress, int port, EchoWorker worker) throws IOException {
        this.hostAddress = hostAddress;
        this.port = port;
        this.selector = this.initSelector();
        this.worker = worker;
      public void send(SocketChannel socket, byte[] data) {
        System.out.println("Server Send ");
        synchronized (this.pendingChanges) {
          // Indicate we want the interest ops set changed
          this.pendingChanges.add(new ChangeRequest(socket, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE));
          // And queue the data we want written
          synchronized (this.pendingData) {
            List queue = (List) this.pendingData.get(socket);
            if (queue == null) {
              queue = new ArrayList();
              this.pendingData.put(socket, queue);
            queue.add(ByteBuffer.wrap(data));
        // Finally, wake up our selecting thread so it can make the required changes
        this.selector.wakeup();
      public void run() {
        while (true) {
          try {
            // Process any pending changes
            synchronized (this.pendingChanges) {
              Iterator changes = this.pendingChanges.iterator();
              while (changes.hasNext()) {
                ChangeRequest change = (ChangeRequest) changes.next();
                switch (change.type) {
                case ChangeRequest.CHANGEOPS:
                  SelectionKey key = change.socket.keyFor(this.selector);
                  key.interestOps(change.ops);
              this.pendingChanges.clear();
            // Wait for an event one of the registered channels
            this.selector.select();
            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
              SelectionKey key = (SelectionKey) selectedKeys.next();
              selectedKeys.remove();
              if (!key.isValid()) {
                continue;
              // Check what event is available and deal with it
              if (key.isAcceptable()) {
                this.accept(key);
              } else if (key.isReadable()) {
                this.read(key);
              } else if (key.isWritable()) {
                this.write(key);
          } catch (Exception e) {
            e.printStackTrace();
      private void accept(SelectionKey key) throws IOException {
        System.out.println("Server Accept ");
        // For an accept to be pending the channel must be a server socket channel.
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        // Accept the connection and make it non-blocking
        SocketChannel socketChannel = serverSocketChannel.accept();
        Socket socket = socketChannel.socket();
        socketChannel.configureBlocking(false);
        // Register the new SocketChannel with our Selector, indicating
        // we'd like to be notified when there's data waiting to be read
        socketChannel.register(this.selector, SelectionKey.OP_READ);
      private void read(SelectionKey key) throws IOException {
        System.out.println("server Read : ");
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // Clear out our read buffer so it's ready for new data
        readBuffer.clear();
    //    readFully( readBuffer , socketChannel ) ;
        // Attempt to read off the channel
        int numRead;
        try {
          numRead = socketChannel.read(readBuffer);
        } catch (IOException e) {
          // The remote forcibly closed the connection, cancel
          // the selection key and close the channel.
          key.cancel();
          socketChannel.close();
          return;
        if (numRead == -1) {
          // Remote entity shut the socket down cleanly. Do the
          // same from our end and cancel the channel.
          key.channel().close();
          key.cancel();
          return;
        // Hand the data off to our worker thread
        this.worker.processData(this, socketChannel, this.readBuffer.array(), numRead);
      private void write(SelectionKey key) throws IOException {
        System.out.println("Server Write ");
        SocketChannel socketChannel = (SocketChannel) key.channel();
        synchronized (this.pendingData) {
          List queue = (List) this.pendingData.get(socketChannel);
          // Write until there's not more data ...
          while (!queue.isEmpty()) {
            ByteBuffer buf = (ByteBuffer) queue.get(0);
            socketChannel.write(buf);
            if (buf.remaining() > 0) {
              System.out.println( "buf.remaining() " + buf.remaining() ) ;
              // ... or the socket's buffer fills up
              break;
            queue.remove(0);
          if (queue.isEmpty()) {
            // We wrote away all data, so we're no longer interested
            // in writing on this socket. Switch back to waiting for
            // data.
            key.interestOps(SelectionKey.OP_READ);
      private Selector initSelector() throws IOException {
        // Create a new selector
        Selector socketSelector = SelectorProvider.provider().openSelector();
        // Create a new non-blocking server socket channel
        this.serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        // Bind the server socket to the specified address and port
        InetSocketAddress isa = new InetSocketAddress(this.hostAddress, this.port);
        serverChannel.socket().bind(isa);
        // Register the server socket channel, indicating an interest in
        // accepting new connections
        serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
        return socketSelector;
      private static void readFully(ByteBuffer buf, SocketChannel socket) throws IOException
        int len = buf.limit() - buf.position();
        while (len > 0)
          len -= socket.read(buf);
      public static void main(String[] args) {
        try {
          EchoWorker worker = new EchoWorker();
          new Thread(worker).start();
          new Thread(new NioServer(null, 9090, worker)).start();
        } catch (IOException e) {
          e.printStackTrace();
    }Client Code :
    public class NioClient implements Runnable {
      // The host:port combination to connect to
      private InetAddress hostAddress;
      private int port;
      // The selector we'll be monitoring
      private Selector selector;
      // The buffer into which we'll read data when it's available
      private ByteBuffer readBuffer = ByteBuffer.allocate( 10596 ) ;
      // A list of PendingChange instances
      private List pendingChanges = new LinkedList();
      // Maps a SocketChannel to a list of ByteBuffer instances
      private Map pendingData = new HashMap();
      private byte[] bufferByteA = null ;
      // Maps a SocketChannel to a RspHandler
      private Map rspHandlers = Collections.synchronizedMap(new HashMap());
      public NioClient(InetAddress hostAddress, int port) throws IOException {
        this.hostAddress = hostAddress;
        this.port = port;
        this.selector = this.initSelector();
      public void send(byte[] data, RspHandler handler) throws IOException {
        // Start a new connection
        SocketChannel socket = this.initiateConnection();
        // Register the response handler
        this.rspHandlers.put(socket, handler);
        // And queue the data we want written
        synchronized (this.pendingData) {
          List queue = (List) this.pendingData.get(socket);
          if (queue == null) {
            queue = new ArrayList();
            this.pendingData.put(socket, queue);
          queue.add(ByteBuffer.wrap(data));
        // Finally, wake up our selecting thread so it can make the required changes
        this.selector.wakeup();
      public void run()
        while (true)
          try
            // Process any pending changes
            synchronized (this.pendingChanges)
              Iterator changes = this.pendingChanges.iterator();
              while (changes.hasNext())
                ChangeRequest change = (ChangeRequest) changes.next();
                switch (change.type)
                  case ChangeRequest.CHANGEOPS:
                    SelectionKey key = change.socket.keyFor(this.selector);
                    key.interestOps(change.ops);
                    break;
                  case ChangeRequest.REGISTER:
                    change.socket.register(this.selector, change.ops);
                    break;
              this.pendingChanges.clear();
            // Wait for an event one of the registered channels
            this.selector.select();
            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext())
            System.out.println( " ----run 5 " ) ;
              SelectionKey key = (SelectionKey) selectedKeys.next();
              selectedKeys.remove();
              if (!key.isValid())
                continue;
              // Check what event is available and deal with it
              if (key.isConnectable())
                this.finishConnection(key);
              else if (key.isReadable())
                this.read(key);
              else if (key.isWritable())
                this.write(key);
          catch (Exception e)
            e.printStackTrace();
      private void read(SelectionKey key) throws IOException {
        System.out.println( "---------read 1 " ) ;
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // Clear out our read buffer so it's ready for new data
        this.readBuffer.clear();
        System.out.println( "---------read 2 " + readBuffer.capacity()) ;
         readBuffer = ByteBuffer.allocate( bufferByteA.length  ) ;
        // Attempt to read off the channel
    //    int numRead;
        try {
    //      numRead = socketChannel.read(this.readBuffer);
          readFully( readBuffer , socketChannel ) ;
        } catch (IOException e) {
          // The remote forcibly closed the connection, cancel
          // the selection key and close the channel.
          key.cancel();
          socketChannel.close();
          return;
    //    if (numRead == -1) {
    //      // Remote entity shut the socket down cleanly. Do the
    //      // same from our end and cancel the channel.
    //      key.channel().close();
    //      key.cancel();
    //      return;
        // Handle the response
        this.handleResponse(socketChannel, this.readBuffer.array(), readBuffer.capacity() );
      private void handleResponse(SocketChannel socketChannel, byte[] data, int numRead) throws IOException {
        // Make a correctly sized copy of the data before handing it
        // to the client
        byte[] rspData = new byte[numRead];
        // Look up the handler for this channel
        RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
        // And pass the response to it
        if (handler.handleResponse(rspData)) {
          // The handler has seen enough, close the connection
          socketChannel.close();
          socketChannel.keyFor(this.selector).cancel();
      private void write(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        readBuffer.flip() ;
        List queue = null ;
        synchronized (this.pendingData) {
          queue = (List) this.pendingData.get(socketChannel);
          writeFully( readBuffer , socketChannel ) ;
          // Write until there's not more data ...
          while (!queue.isEmpty()) {
    //        ByteBuffer buf = (ByteBuffer) queue.get(0);
    //        socketChannel.write(buf);
    //        writeFully( buf , socketChannel ) ;
    //        if (buf.remaining() > 0) {
    //          // ... or the socket's buffer fills up
    //          break;
            queue.remove(0);
          if (queue.isEmpty()) {
            // We wrote away all data, so we're no longer interested
            // in writing on this socket. Switch back to waiting for
            // data.
            key.interestOps(SelectionKey.OP_READ);
      private void finishConnection(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // Finish the connection. If the connection operation failed
        // this will raise an IOException.
        try {
          socketChannel.finishConnect();
        } catch (IOException e) {
          // Cancel the channel's registration with our selector
          System.out.println(e);
          key.cancel();
          return;
        // Register an interest in writing on this channel
        key.interestOps(SelectionKey.OP_WRITE);
      private SocketChannel initiateConnection() throws IOException {
        // Create a non-blocking socket channel
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(this.hostAddress, this.port));
    //    socketChannel.finishConnect() ;
        // Queue a channel registration since the caller is not the
        // selecting thread. As part of the registration we'll register
        // an interest in connection events. These are raised when a channel
        // is ready to complete connection establishment.
        synchronized(this.pendingChanges) {
          this.pendingChanges.add(new ChangeRequest(socketChannel, ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
        return socketChannel;
      private Selector initSelector() throws IOException {
        // Create a new selector
        return SelectorProvider.provider().openSelector();
      public static void main(String[] args) {
        try {
          NioClient client = new NioClient(InetAddress.getByName("healsoft1"), 9090);
          Thread t = new Thread(client);
          t.setDaemon(true);
          t.start();
          RspHandler handler = new RspHandler();
          client.readBytesFromFile( handler ) ;
        } catch (Exception e) {
          e.printStackTrace();
      private void readBytesFromFile( RspHandler handler ) throws IOException
        File file = new File( "Y:/output.txt") ;
        bufferByteA = getBytesFromFile( file ) ;
        readBuffer = ByteBuffer.allocate(bufferByteA.length ) ;
        readBuffer.put( bufferByteA , 0 , bufferByteA.length ) ;
        send(bufferByteA , handler);
        handler.waitForResponse();
      private static void readFully(ByteBuffer buf, SocketChannel socket) throws IOException
        System.out.println( "readFully  : " ) ;
        int len = buf.limit() - buf.position();
        int count = 0 ;
        while (len > 0)
          len -= socket.read(buf);
      private void writeFully(ByteBuffer buf , SocketChannel socketChannel) throws IOException
        System.out.println( "writeFully  : " ) ;
        int len = buf.limit() - buf.position() ;
        SocketChannel socket = socketChannel ;
        socket.open();
        while (len > 0)
          len -= socket.write(buf);
      private static byte[] getBytesFromFile(File file) throws IOException
        InputStream is = new FileInputStream(file);
        // Get the size of the file
        long length = file.length();
             * You cannot create an array using a long type. It needs to be an int
             * type. Before converting to an int type, check to ensure that file is
             * not loarger than Integer.MAX_VALUE;
        if (length > Integer.MAX_VALUE)
          System.out.println("File is too large to process");
          return null;
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ( (offset < bytes.length)
                ( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) )
                offset += numRead;
        // Ensure all the bytes have been read in
        if (offset < bytes.length)
          throw new IOException("Could not completely read file " + file.getName());
        is.close();
        return bytes;
      public static String printTimeWithMilliSec(long l )
        Date date = new Date( l ) ;
        SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss SSS");
        return f.format(date);
    }

    Data transfer rate for a single client is unlikely to be effected by using NIO or old blocking IO. The important factor is the maximum transfer rate you can get between the sender and receiver.
    You should be able to get 0.5-1.0 MB per second for each 10 Mbit per second of available bandwidth. Your timings suggest you are getting about a 10-20 Mbit/s link speed.

Maybe you are looking for

  • How do I transfer App data from iPod Touch to a new iPhone?

    When I restore from my iPod backup, the Apps that came with my iPhone are deleted. Where are the data files located so that a couple of games and other App data files can be moved over?

  • HADB session failover & realm problem

    I have a enterprise applicaiton server cluster configured for loadbalancing and session failover. I installed HADB. HADB works, I test with the webapp from the samples of the application server: I add some attribute in session, I see which node execu

  • Scheduling Reports for different Responsibilities

    We are using discoverer 10g with Oracle Apps 11i Can someone share some input on the following. If I schedule a report, can users from two different countries say US and Canada access the results and get their respective data. By this I mean if a use

  • AC 10.1 Empty screen on User Level analysis

    Hi all, We have migrated our 5.3 Access Control System to 10.1 and all the post-installation steps are applied. We loaded the user and roles from our ERP System, created rules and generated them for our system. Parameter 1027 – Enable offline risk an

  • Maxtor OneTouch II USB Drive

    Hey! I have a Maxtor USB External hard drive, which i would like to use with my mac. i plugged in the external power it requires, and plugged it into my mac. nothing happened, except the drive "whirred". I went to the maxtor (now seagate) website, an