Java.nio.channels.NonWritableChannelException

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

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

Similar Messages

  • DPS 11.1.1.5.0 java.nio.channels.ClosedChannelException

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

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

  • Java.nio.channels.ClosedChannelException using https

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

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

  • Java.nio.channels.IllegalBlockingModeException

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

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

  • Java.nio.channels.FileChannel jar file

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

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

  • Java.nio.channels.Pipe?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • 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

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

  • Any java.nio guru out there ?

    Hi help,
    I'm studying new java.io classes. I've compiled and learnt
    a basic server like this...
    import java.io.*;
    import java.net.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.util.*;
    public class Server {
       private static int port = 9999;
       public static void main(String args[])
         throws Exception {
         Selector selector = Selector.open();
         ServerSocketChannel channel =
           ServerSocketChannel.open();
         channel.configureBlocking(false);
         InetSocketAddress isa = new InetSocketAddress(port);
         channel.socket().bind(isa);
         // Register interest in when connection
         channel.register(selector, SelectionKey.OP_ACCEPT);
         // Wait for something of interest to happen
         while (selector.select() > 0) {
           // Get set of ready objects
           Set readyKeys = selector.selectedKeys();
           Iterator readyItor = readyKeys.iterator();
           // Walk through set
           while (readyItor.hasNext()) {
             // Get key from set
             SelectionKey key =
               (SelectionKey)readyItor.next();
             // Remove current entry
             readyItor.remove();
             if (key.isAcceptable()) {
               // Get channel
               ServerSocketChannel keyChannel =
                 (ServerSocketChannel)key.channel();
               // Get server socket
               ServerSocket serverSocket = keyChannel.socket();
               // Accept request
               Socket socket = serverSocket.accept();
               // Return canned message
               PrintWriter out = new PrintWriter
                 (socket.getOutputStream(), true);
               out.println("Hello, NIO");
               out.close();
             } else {
               System.err.println("Ooops");
         // Never ends
    } now I'd like to write a Proxy Server. In other
    words the Server must
    1. listen for a request
    2. forward the request to another server
    3. listen its reply
    4. forward it back to the original caller.
    I've tried to modify the basic class but with no success....
    unfortunately I'm not that smart with these new Apis.
    anybody can give me some guidelines about how should I
    struct it ?
    Thanks a lot
    Francesco

    Not a guru but I'll offer some suggestions. Are these persistent connections to the proxy, or is a connection made per request? You'll probably do things a little bit differently in the two different cases.
    In general though, you can have one thread running a request dispatcher which accepts incoming connections and puts read ready channels on a queue. Another thread(or threads) can take requests off the queue and process them. Also, when you accept new connections, I think its better to do it through channels, rather than work directly with the socket. Something like this:
    SocketChannel clientChannel = serverChannel.accept();
    clientChannel.configureBlocking(false);
    SelectionKey newReadKey = clientChannel.register(selector, SelectionKey.OP_READ);
    Where are you getting into problems?

Maybe you are looking for

  • Imac wont boot from cd, Can anyone help me Please

    Hello, I just bought my first mac from a co-worker. it didnt have a hard drive so i threw a spare one i had in. I tried holding c when booting, and all i get is the little smile face and the ? on a folder. At first when i booted the computer it didnt

  • Hooking up a wireless router.

    I am hooking up a wireless n router. The setup wizard is asking me what type of internet connection the verizon router uses (cable modem, fixed-ip, PPPoE, PPTP, or L2TP). Thanks for your help.

  • Re: Error when configuring Data Masking with workload masking in 12c

    Hello, Even I am facing a similar issue - error message displayed when trying for data-masking along with R.A.T. capabilities Can anybody help resolve this. Objective - Use Real Application Testing in combination with Test Data Masking Pack Current S

  • Smart Collection "Capture Date is in the last n hours" not working?

    In Smart Collection, the rule "Capture Date is in the last n hours" doesn't work for me. It seems to behave similarly to "Capture Date is today".  (See the screenshot below).  Has anyone else noticed this, or can you replicate this?  If so, I'll file

  • IChat script to get open IMs

    A few days ago, I was on the road with my old PowerBook G4 which only runs Mac OS X 10.4.11. I got bored and wrote a script to set my iChat status to a list of people who I have IMs open and am conversing with. That script took advantage of the fact