Java NIO with ByteBuffer

Hi guys,
I search the forum and the web too, there are many pros and cons in relation to NIO, and on my free time I was trying to research about it, but there
are time when some things don't make any sense at all.
Without NIO:
    FileInputStream foin = new FileInputStream("/home/metitus/Desktop/test");
    FileOutputStream fout = new FileOutputStream("/home/metitus/Desktop/test1");
    int character = 0;
    while((character = foin.read()) != -1)
        fout.write(character);
    }with NIO:
FileInputStream foin = new FileInputStream("/home/metitus/Desktop/test");
    FileOutputStream fout = new FileOutputStream("/home/metitus/Desktop/test1");
    FileChannel fci = foin.getChannel();
    FileChannel fco = fout.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(1);
    while(fci.read(buffer) != -1)
        buffer.flip();
        fout.write(buffer.array());
        buffer.clear();
    }So guys where is the gain here? Why do I need a ByteBuffer always; it might be useful in some cases but definitely not in all.
MeTitus

Well there should be more than one position. You're doing it the slowest way possible. There should be 8192, or 16384, or some large number. And when you raise the size you have to use compact(): buffer.clear() is valid if and only if the buffer size is 1; buffer.compact() is valid for all buffer sizes.
In fact the loop should look like this to take care of the last write:
while ((count = in.read(buffer)) >= 0 || buffer.position() > 0)
  buffer.flip();
  out.write(buffer);
  buffer.compact();
}

Similar Messages

  • 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));
    }

  • Converting from CP1252 (Windows) to ISO 8859-1 doesn't work with java.nio?

    Hi
    I'm trying to write some code that checks whether an InputStream contains only characters with a given encoding. I'm using java.nio for that. For tests, I downloaded some character set examples from http://www.columbia.edu/kermit/csettables.html
    When creating the CharsetDecoder, I want to get all errors:
        Charset charset = Charset.forName( encoding );
        CharsetDecoder decoder = charset.newDecoder();
        decoder.onMalformedInput( CodingErrorAction.REPORT );
        decoder.onUnmappableCharacter( CodingErrorAction.REPORT );I then read an InputStream and try to convert it. If that fails, it can't contain the desired encoding:
        boolean isWellEncoded = true;
        ByteBuffer inBuffer = ByteBuffer.allocate( 1024 );
        ReadableByteChannel channel = Channels.newChannel( inputStream );
        while ( channel.read( inBuffer ) != -1 )
          CharBuffer decoded = null;
          try
            inBuffer.flip();
            decoded = decoder.decode( inBuffer );
          catch ( MalformedInputException ex )
            isWellEncoded = false;
          catch ( UnmappableCharacterException ex )
            isWellEncoded = false;
          catch ( CharacterCodingException ex )
            isWellEncoded = false;
          if ( decoded != null )
            LOG.debug( decoded.toString() );
          if ( !isWellEncoded )
            break;
          inBuffer.compact();
        channel.close();
        return isWellEncoded;Now I want to check whether a file containing Windows 1252 characters is ISO-8859-1. From my point of view, the code above should fail when it gets to the Euro symbol (decimal 128), since that's not defined in ISO-8859-1.
    But all I get is a ? character instead:
    (})  125  07/13  175  7D                 RIGHT CURLY BRACKET, RIGHT BRACE
    (~)  126  07/14  176  7E                 TILDE
    [?]  128  08/00  200  80  EURO SYMBOL
    [?]  130  08/02  202  82  LOW 9 SINGLE QUOTEI also tried to replace the faulty character, using
        decoder.onUnmappableCharacter( CodingErrorAction.REPLACE );
        decoder.replaceWith("!");but I still get the question marks.
    I'm probably doing something fundamentally wrong, but I dont get it :-)
    Any help is greatly appreciated!
    Eric

    As a suggestion....create a complete example demonstrating the problem. It shouldn't have channel in it since that wouldn't appear to be the problem (decoding is.) You should create the byte array in the example code - populate it with the byte sequence that you think should work. And your code should then demonstrate that it doesn't. Then post that.

  • Cannot access class java.nio.ByteBuffer

    Hi All -
    I'm trying to compile a java sample code.
    I keep getting the error described in the subject line
    cannot access class java.nio.ByteBuffer; file java\nio\ByteBuffer.class not found
    I have un-ziped the java sdk 1.4.1 src.zip to a directory under c:\ and added the java\nio directory to the project setting and compile with jdk runtime 1.4.1 and yet get the same error....
    I've tried by redirecting to src.zip and didn't work either....
    I would appreciate your feedbacks and sorry for the lame question, consider it as a newcomer to Java world.
    thanks in advance

    You test it by running the following line....
    java java.nio.ByteBuffer
    If it says "main not found" then your problem has nothing to do with the java install nor the classpath. The code you are trying to compile is wrong.
    If it says class not found then you use this line next....
    java -version
    If this returns nothing then you are not using the Sun VM (you are using the MS one.) If it returns a version below 1.4 then your PATH statement is wrong (and you should uninstall all sun versions then reinstall.) You can fix the MS VM problem by altering the path so the java path is first.
    If it does say 1.4 then you need to uninstall and reinstall because something is messed up.

  • Using ByteBuffer from java.nio package

    Hi,
    I have a java.nio.ByteBuffer object that is returned from the C++ code, created using NewDirectByteBuffer. I would like to use this ByteBuffer object in my java code to create a WritableRaster object. I would like to avoid an array copy here as the data may be huge.
    Could someone please let me know if there is a solution to this?
    Thanks in advance for any help.

    Warning: I know almost nothing about the java.awt.image package - so please take what Im going to suggest as the throw away, off the top of my head random rambling that it is......
    Could you implement a custom DataBuffer which sits on top of a NIO ByteBuffer? Already, custom DataBuffers provide access for certain data types (e.g. theres a DataBufferByte, DataBufferDouble which wrap arrays) - so I guess you could write a NIODataBufferByte - or what ever - which sits on top of a ByteBuffer.
    Im not sure how this would tie in with the SampleModel though (again, I dont know anything about this area).
    Hopefully someone who knows this stuff will come across this thread and actually give you some decent advice :o)
    ~D

  • Need help with java.nio.socket program.

    Can someone please help me here? I am trying to create a class that listens on a socket for an incoming connection, but I am getting the following error on compile:
    SocketIn.java:48: incompatible types
    found : java.nio.channels.SocketChannel
    required: java.net.Socket
    Socket requestSocket = requestChannel.accept();
    Here is my code:
    package NETC;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.channels.spi.*;
    public class SocketIn{
         // Buffer for any incoming data.
         private static ByteBuffer inBuffer = ByteBuffer.allocateDirect(1024);
         CharBuffer charBuffer = null;
         public SocketIn(int intPort)throws Exception{
              // Create a non-blocking server socket.
              ServerSocketChannel serverChannel = ServerSocketChannel.open();
              serverChannel.configureBlocking(false);
              // Use the host and port to bind the server socket.
              InetAddress inetAddress = InetAddress.getLocalHost();
              InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, intPort);
              serverChannel.socket().bind(socketAddress);
              // The selector for incoming requests.
              Selector requestSelector = SelectorProvider.provider().openSelector();
              // Put the server socket on the selectors 'ready list'.
              serverChannel.register(requestSelector, SelectionKey.OP_ACCEPT);
              while(requestSelector.select() > 0){
                   System.out.println("Connection Accepted...");
                   // A request has been made and is ready for IO.
                   Set requestKeys = requestSelector.selectedKeys();
                   Iterator iterator = requestKeys.iterator();
                   while(iterator.hasNext()){
                        SelectionKey requestKey = (SelectionKey)iterator.next();
                        // Get the socket that's ready for IO.
                        ServerSocketChannel requestChannel = (ServerSocketChannel)requestKey.channel();
                        // This shouldn't block.
                        Socket requestSocket = requestChannel.accept();
                        inBuffer.clear();
                        requestSocket.read(inBuffer);                    
                        inBuffer.flip();
                        Charset charset = Charset.forName("ISO-8859-1");
                        CharsetDecoder decoder = charset.newDecoder();
                        charBuffer = decoder.decode(inBuffer);
                        iterator.remove();                    
    }

    Well its been about a month and a half so I guess you have your answer. In case you don't...
    // This shouldn't block.
    Socket requestSocket = requestChannel.accept();
    The problem is quite simple. The ServerSocketChannel.accept() returns a SocketChannel. (Channel -> Channel).
    You can get access to the socket using the SocketChannel.
    SocketChannel requestSocketChannel = requestChannel.accept();
    Socket requestSocket = requestSocketChannel.socket();
    But you don't need the socket to read and write.

  • 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.

  • Java NIO client

    I need to make the server is able to hold about 500 connections and operates on a single thread. The server itself should make all the connections. Where can I find examples of finished implementations?

    I have an example, but it does not work
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
         // The host:port combination to connect to
         private InetAddress hostAddress;
         private String host;
         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(8192);
         // A list of PendingChange instances
         private List pendingChanges = new LinkedList();
         // Maps a SocketChannel to a list of ByteBuffer instances
         private Map pendingData = new HashMap();
         // Maps a SocketChannel to a RspHandler
         private Map rspHandlers = Collections.synchronizedMap(new HashMap());
         public NioClient() {
              try {this.selector = this.initSelector();} catch(IOException e){}
         public void connect(String host, int port, RspHandler handler) throws IOException {
              this.hostAddress = hostAddress;
              this.host = host;
              this.port = port;
              this.send("$Hello |".getBytes(), handler);
         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();
              handler.waitForResponse();
         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()) {
                             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 {
              SocketChannel socketChannel = (SocketChannel) key.channel();
              // Clear out our read buffer so it's ready for new data
              this.readBuffer.clear();
              // Attempt to read off the channel
              int numRead;
              try {
                   numRead = socketChannel.read(this.readBuffer);
              } catch (IOException e) {
                   // The remote forcibly closed the connection, cancel
                   // the selection key and close the channel.
                   key.cancel();
                   socketChannel.close();
                   return;
              System.out.println("READ");
              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(), numRead);
         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];
              System.arraycopy(data, 0, rspData, 0, 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();
              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) {
                             // ... 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.host, this.port));
              // 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 class RspHandler {
         private byte[] rsp = null;
         public synchronized boolean handleResponse(byte[] rsp) {
              this.rsp = rsp;
              this.notify();
              return true;
         public synchronized void waitForResponse() {
              while(this.rsp == null) {
                   try {
                        this.wait();
                   } catch (InterruptedException e) {
              System.out.println(new String(this.rsp));
    }          NioClient NioClient = new NioClient();
              Thread t = new Thread(NioClient);
              t.setDaemon(true);
              t.start();
              RspHandler handler = new RspHandler();          
              NioClient.connect("69.28.156.250", 27040, handler);
              NioClient.connect("72.165.61.188", 27040, handler);
              NioClient.connect("208.111.133.84", 27011, handler);
              NioClient.connect("72.165.61.136", 27012, handler);
    Edited by: 915967 on 01.08.2012 7:07

  • Java NIO - UDP packets

    I'm curious as to the rationale behind having a DatagramPacket class and just using ByteBuffers for TCP connections. I can see the logic, but I'm trying to write a Java framework wrapping NIO with TCP and UDP connections. In my C++ version I have one packet class that I use for both types of connections. I'm stuck with what to implement for Java as I'm going to need two classes, NIO's DatagramPacket and a new TCPPacket. Ideally I would like both to implement an interface or derive from a parent class so I can pass them to all class methods that deal with packets, be they UDP or TCP based. But this won't work. I could wrap DatagramPacket into a new class, and have it and the TCPPacket class implement a Packet interface. But when I'm sending UDP packets I'll be creating two objects for the price of one.
    Any suggestions?
    Thanks

    Remember that in UDP case you can easily lose packets and never know. In TCP you would receive an exception, but UDP can silently discard your packages while in transit.
    My point is, you probably should use a different package class for UDP anyway, maybe adding some stuff like a package ID that would enable re-sending and additional processing in order to ensure a successful communication.
    If you already have this information and some procedures for retrying in your package, then I agree with the previous poster in that you can use bytebuffer for both.

  • Java.nio select() method return 0 in my client application

    Hello,
    I'm developing a simple chat application who echo messages
    But my client application loop because the select() method return 0
    This is my code
    // SERVER
    package test;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class Server {
         private int port = 5001;
         public void work() {               
              try {
                   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                   serverSocketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(port);               
                   serverSocketChannel.socket().bind(isa);
                   Selector selector = Selector.open();
                   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Listing on "+port);
                   while(selector.select()>0) {
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isAcceptable()) {
                                  ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();                              
                                  SocketChannel channel = keyChannel.accept();
                                  channel.configureBlocking(false);                              
                                  channel.register(selector, SelectionKey.OP_READ );
                             } else if (key.isReadable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel );
                                  Help.write(m.toUpperCase(), keyChannel );
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         public static void main(String[] args) {
              Server s = new Server();
              s.work();
    // CLIENT
    package test;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {               
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);               
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
                   while(true) {
                        selector.select();
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  if (keyChannel.isConnectionPending()) {
                                       System.out.println("Connected "+keyChannel.finishConnect());                                                                           
                             } else if (key.isReadable()) {                                                                                                                                                           
                                  SocketChannel keyChannel = (SocketChannel) key.channel();                                             
                                  String m = Help.read(keyChannel);
                                  display(m);                                                                                                                                                                                                                   
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {               
                   public void run() {                                                                                
                        try {                         
                             Help.write(m, socketChannel);
                        } catch (IOException e) {               
                             e.printStackTrace();
              t.start();                    
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);     
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();
    // HELPER CLASS
    package test;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    public class Help {
         private static Charset charset = Charset.forName("us-ascii");
         private static CharsetEncoder enc = charset.newEncoder();
         private static CharsetDecoder dec = charset.newDecoder();
         private static void log(String m) {
              System.out.println(m);
         public static String read(SocketChannel channel) throws IOException {
              log("*** start READ");                              
              int n;
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              while((n = channel.read(buffer)) > 0) {
                   System.out.println("     adding "+n+" bytes");
              log("  BUFFER REMPLI : "+buffer);
              buffer.flip();               
              CharBuffer cb = dec.decode(buffer);          
              log("  CHARBUFFER : "+cb);
              String m = cb.toString();
              log("  MESSAGE : "+m);          
              log("*** end READ");
              //buffer.clear();
              return m;                    
         public static void write(String m, SocketChannel channel) throws IOException {          
              log("xxx start WRITE");          
              CharBuffer cb = CharBuffer.wrap(m);
              log("  CHARBUFFER : "+cb);          
              ByteBuffer  buffer = enc.encode(cb);
              log("  BUFFER ALLOUE REMPLI : "+buffer);
              int n;
              while(buffer.hasRemaining()) {
                   n = channel.write(buffer);                         
              System.out.println("  REMAINING : "+buffer.hasRemaining());
              log("xxx end WRITE");

    Here's the fix for that old problem. Change the work method to do the following
    - don't register interest in things that can't happen
    - when you connect register based on whether the connection is complete or pending.
    - add the OP_READ interest once the connection is complete.
    This doesn't fix all the other problems this code will have,
    eg.
    - what happens if a write is incomplete?
    - why does my code loop if I add OP_WRITE interest?
    - why does my interestOps or register method block?
    For code that answers all those questions see my obese post Taming the NIO Circus
    Here's the fixed up Client code
    // CLIENT
    package test
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   int interest = 0;
                   if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
                   else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
                   socketChannel.register(selector, interest);
                   while(true)
                        int nn = selector.select();
                        System.out.println("nn="+nn);
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();)
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  System.out.println("Connected "+keyChannel.finishConnect());
                                  key.interestOps(SelectionKey.OP_READ);
                             if (key.isReadable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel);
                                  display(m);
              } catch (IOException e) {
                   e.printStackTrace();
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {
                   public void run() {
                        try {
                             Help.write(m, socketChannel);
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();

  • Problematic frame: # J java.nio.MappedByteBuffer.load()

    Helo all...
    I'm getting an error when generating a PDF using BIRT Framework in Eclipse. Nothing fancy, just compiling a simple report to pdf.
    The problem is, the JVM crashes with the following error:
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_IN_PAGE_ERROR (0xc0000006) at pc=0x0190f0be, pid=5848, tid=2392
    # JRE version: 7.0_09-b05
    # Java VM: Java HotSpot(TM) Client VM (23.5-b02 mixed mode, sharing windows-x86 )
    **# Problematic frame:
    # J java.nio.MappedByteBuffer.load()Ljava/nio/MappedByteBuffer;**
    # Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
    # An error report file with more information is saved as:
    # C:\Users\luis\Desktop\teste\birt\hs_err_pid5848.log
    # If you would like to submit a bug report, please visit:
    # http://bugreport.sun.com/bugreport/crash.jsp
    I already tried:
    1. Run the program in another computers - it worked
    2. Reinstall Java on the computer - It did nothing
    3. I check the integrity of the disk C: - Nothing
    I already spent two days trying to fix this and I don't have any progress. I can't find a solution on the web either.
    Thanks in advance

    Thanks for the help.
    But it can not be related to BIRT because it works in every other computer that I tried so far. There is only one computer that not works properly.
    If it were BIRT's fault, it wouldn't work in any computer.
    Thanks again

  • Java NIO locking and NTFS network resources

    Hi all - just ran into a really nasty situation and I was wondering if anyone else has hit it and might have some suggestions.
    Platform: JRE 1.4_02 on a Win XP machine
    The following test code locks a file, then copies it to another location using NIO.
    When I run it with source path on my local drives (C), it works fine. If I run it with source path on a network shared resource, it fails with an IOException with description 'Error performing inpage operation'.
    If I disable the lock immediately before the copy operation, it works fine.
    My conclusion is that there is something about the NIO locking implementation that prevents it from working properly with NTFS volumes on other hosts. Can this be right? I've found the following bug report:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4774175
    but this seems like a huge problem that would prevent folks from using NIO in many, many applications. Maybe I'm wrong on something here...
    Anyway, here's the test code:
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.channels.FileChannel;
    import java.nio.channels.FileLock;
    * Created on May 28, 2004
    * (c) 2004 Trumpet, Inc.
    * @author kevin
    public class test {
         private void createFile(File f) throws IOException{
              FileOutputStream os = new FileOutputStream(f);
              for(int i = 0; i < 10; i++){
                   os.write(i);
              os.close();
         public test() {
              boolean testWithReleasingLockPriorToCopy = false;
              final File f1= new File("w:/temp/test2.lok");
              final File f2 = new File("w:/temp/test.lok");
              f1.delete();
              f2.delete();
              try {
                   createFile(f1);
                   RandomAccessFile raf1 = new RandomAccessFile(f1, "rw");
                   RandomAccessFile raf2 = new RandomAccessFile(f1, "rw");
                   FileChannel ch1 = raf1.getChannel();
                   FileChannel ch2 = raf2.getChannel();
                   FileLock flock1 = ch1.lock();
                  if (!f2.getParentFile().exists() && !f2.getParentFile().mkdirs())
                       throw new IOException("Unable to create directories for destination file '" + f2 + "'");
                  if (testWithReleasingLockPriorToCopy)
                       flock1.release();
                   ch1.transferTo(0, raf1.length(), ch2);
                   raf1.close();
                   raf2.close();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public static void main(String[] args) {
              test t = new test();
    }Does anyone have any pointers here? I need to be able to exclusively lock a file on a network drive (preventing any other applications from opening it), then make a copy of it. I can't use regular stream operations, because the lock prevents them from working properly (it appears that, once you grab a file lock using NIO, the only way your application can use the file is via the NIO operations - using stream operations fails...).
    Thanks in advance for any help!
    - Kevin

    i've run into the same problem recently, channels working fine for local file locking, but when you turn to the network, they fail to accurately handle locks.
    i ended up writing a jni utility to ship with my java application that locks files using native windows calls.
    my .c file ends up looking something like this:
    JNIEXPORT jint JNICALL Java_Mapper_NativeUtils_LockFile
    (JNIEnv *env, jobject obj, jstring filename)
    const char* ntvFilename = (*env)->GetStringUTFChars(env, filename, 0);
    int retVal = (int)CreateFile
    ntvFilename
    , GENERIC_WRITE
    , FILE_SHARE_READ
    , 0
    , OPEN_EXISTING
    , FILE_FLAG_SEQUENTIAL_SCAN
    , 0
    //add code to throw java exceptions based on retVal
    if (retVal == (int)INVALID_HANDLE_VALUE)
    return retVal;
    (*env)->ReleaseStringUTFChars(env, filename, ntvFilename);
    return retVal;
    JNIEXPORT jboolean JNICALL Java_Mapper_NativeUtils_UnlockFile
    (JNIEnv *env, jobject obj, jint handle)
         CloseHandle((void *)handle);
    return 1;
    it's a little shy on the error checking side, but it provides support for network file locking that java seems to lack.

  • J2ME and java.nio

    I'm not sure which forum this should go in so applogies if I got it wrong.
    I would like to use the java.nio package from JDK1.4 with the J2ME. Is this possible in any way?
    cheers
    Andrew

    I'm not sure which forum this should go in so
    applogies if I got it wrong.
    I would like to use the java.nio package from JDK1.4
    with the J2ME. Is this possible in any way?this topic should be post at
    CLDC and MIDP
    http://forum.java.sun.com/forum.jsp?forum=76
    or
    K Virtual Machine (KVM)
    http://forum.java.sun.com/forum.jsp?forum=50
    CLDC 1.0 and MIDP 1.0 doesn't include java.nio
    please go to
    http://java.sun.com/j2me/docs/
    two documents will be useful
    CLDC Specification, V1.0
    MIDP 1.0 Specification, Final (JSR 37)

  • Socket seems too slow...maybe java.nio?

    Hello
    In our system I have to receive Multicast Packets repeats very quick(1-5 ms). I have to link them one after an other in the order they sent. And if I miss a packet, something will go wrong...
    I have to listen to different IPs and I use different threads for different IPs. If I use only one thread (and listens to only one IP) everything seems ok.
    But if I starts listening to an other ip too, I miss 2 packets in a row, or only one if I turn off parsing the message (XML).
    Here is the code I use in the Threads:
    try{
                   socket = new MulticastSocket(port);
                   socket.setSoTimeout(1000);
                   inetAddress = InetAddress.getByName(ip);
                   NetworkInterface nInterface=
    NetworkInterface.getByName(networkInterface);
                   if(nInterface!=null)socket.setNetworkInterface(nInterface);
                   socket.joinGroup(inetAddress);
              catch(IOException ioe){
                   logger.error(ioe.getMessage(), ioe);
    return;
              try{
                   while (!interrupted()) {
                        try{
                             byte[] buffer = new byte[1480];
                             packet = new DatagramPacket(buffer, buffer.length);
                             socket.receive(packet);
    parse(buffer);
                        }catch(SocketTimeoutException stoe){
                             //     DO NOTHING
                        }catch(IOException ioe){
                             logger.error(ioe.getMessage(), ioe);
              }finally{
                   try {
                        if(socket!=null){
                             socket.leaveGroup(inetAddress);
                   } catch (IOException ioe) {}
    Every Thread has its own parsing object.
    Any tips, what is wrong?
    Maybe java.nio could solve the problem somehow. There is a sample server in [Java Home]/sample/nio/server and it suggest that there are quicker methods to receive messages from different IPs (maybe Blocking/Pooled-Thread Server). But I can't understand the API and the Sample while I was reading it (20-30 minutes).
    Could it be quicker? Does it worth toying with the idea?
    Thanks:
    Bence

    In our system I have to receive Multicast Packets
    repeats very quick(1-5 ms). I have to link them one
    after an other in the order they sent. And if I miss
    a packet, something will go wrong...There is no guarantee anywhere in the system that you won't miss a datagram. UDP doesn't make such guarantees. If you need all the packets you will have to build ACK or NACK into your protocol.
    You can alleviate the problem by running a very large socket receive buffer. But you can't eliminate it. Rethink this.
    NIO is not significantly quicker for applications like this, it is more scalable.

  • Java NIO, ByteBuffers and Linksys router

    I have a client server app/game that uses NIO for communication sending ByteBuffers. On a LAN with 5-8 users it runs great. On the internet, through a Linksys router, with one user, it has a blip. I get all my data transmissions except for one buffer. Whenever I chat the buffer contains a size, an int typeID and the encoded string for chat. This particular buffer never makes it to the client on the outside of the router. I have a port forwarded and regular tcp/ip java io sockets stuff works fine. As does al lof the other NIO buffer traffic for locational data, login in and out, etc... ANy thoughts??

    But not sure what would be the performance of those clients?? when compared to Java NIO performance....Telnet isn't a high-performance protocol anyway. Don't worry about it. Use existing code. Get it working. Measure. If you have a performance issue, then worry, while at least you have something you can deploy. It won't be a problem. The router is there to route, not to talk high-speed telnet.

Maybe you are looking for