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.

Similar Messages

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

  • DPS 11.1.1.5.0 java.nio.channels.ClosedChannelException

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

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

  • Java.nio.channels.ClosedChannelException using https

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

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

  • Java.nio.channels.NonWritableChannelException

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

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

  • Java.nio.channels.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.

  • 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.util.Locale not thread-safe !

    In multithreading programming, we know that double-checking idiom is broken. But lots of code, even in sun java core libraries, are written using this idiom, like the class "java.util.Locale".
    I have submitted this bug report just now,
    but I wanted to have your opinion about this.
    Don't you think a complete review of the source code of the core libraries is necessary ?
    java.util.Locale seems not to be thread safe, as I look at the source code.
    The static method getDefault() is not synchronized.
    The code is as follows:
    public static Locale getDefault() {
    // do not synchronize this method - see 4071298
    // it's OK if more than one default locale happens to be created
    if (defaultLocale == null) {
    // ... do something ...
    defaultLocale = new Locale(language, country, variant);
    return defaultLocale;
    This method seems to have been synchronized in the past, but the bug report 4071298 removed the "synchronized" modifier.
    The problem is that for multiprocessor machines, each processor having its own cache, the data in these caches are never synchronized with the main memory.
    The lack of a memory barrier, that is provided normally by the "synchronized" modifier, can make a thread read an incompletely initialized Locale instance referenced by the static private variable "defaultlocale".
    This problem is well explained in http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html and other documents about multithreading.
    I think this method must just be synchronized again.

    Shankar, I understand that this is something books and articles about multithreading don't talk much about, because for marketing reasons, multithreading is supposed to be very simple.
    It absolutely not the case.
    Multithreading IS a most difficult topic.
    First, you must be aware that each processor has its own high-speed cache memory, much faster than the main memory.
    This cache is made of a mixture of registers and L1/L2/L3 caches.
    Suppose we have a program with a shared variable "public static int a = 0;".
    On a multiprocessor system, suppose that a thread TA running on processor P1 assign a value to this variable "a=33;".
    The write is done to the cache of P1, but not in the main memory.
    Now, a second thread TB running on processor P2 reads this variable with "System.out.prinln(a);".
    The value of "a" is retrieved from main memory, and is 0 !
    The value 33 is in the cache of P1, not in main memory where its value is still 0, because the cache of P1 has not been flushed.
    When you are using BufferedOutputStream, you use the "flush()" method to flush the buffer, and the "synch()" method to commit data to disk.
    With memory, it is the same thing.
    The java "synchronized" keyword is not only a streetlight to regulate traffic, it is also a "memory barrier".
    The opening brace "{" of a synchronized block writes the data of the processor cache into the main memory.
    Then, the cache is emptied, so that stale values of other data don't remain here.
    Inside the "synchronized" block, the thread must thus retrieve fresh values from main memory.
    At the closing brace "}", data in the processor cache is written to main memory.
    The word "synchronized" has the same meaning as the "sync()" method of FileDescriptor class, which writes data physically to disk.
    You see, it is really a cache communication problem, and the synchronized blocks allows us to devise a kind of data transfer protocol between main memory and the multiple processor local caches.
    The hardware does not do this memory reconciliation for you. You must do it yourself using "synchronized" block.
    Besides, inside a synchronized block, the processor ( or compiler ) feels free to write data in any order it feels most appropriate.
    It can thus reorder assignments and instruction.
    It is like the elevator algorithm used when you store data into a hard disk.
    Writes are reordered so that they can be retrieved more efficiently by one sweep or the magnetic head.
    This reordering, as well as the arbitrary moment the processor decides to reconciliate parts of its cache to main memory ( if you don't use synchronized ) are the source of the problem.
    A thread TB on processor P2 can retrieve a non-null pointer, and retrieve this object from main memory, where it is not yet initialized.
    It has been initialized in the cache of P1 by TA, though, but TB doen't see it.
    To summarize, use "synchronized" every time you access to shared variables.
    There is no other way to be safe.
    You get the problem, now ?
    ( Note that this problem has strictly nothing to do with the atomicity issue, but most people tend to mix the two topics...
    Besides, as each access to a shared variable must be done inside a synchronized block, the issue of atomicity is not important at all.
    Why would you care about atomicity if you can get a stale value ?
    The only case where atomicity is important is when multiple threads access a single shared variable not in synchronized block. In this case, the variable must be declared volatile, which in theory synchronizes main and cache memory, and make even long and double atomic, but as it is broken in lots of implementation, ... )

  • Java.lang.reflect.Constructor thread safe ?

    When you have a Constructor object in Java.
    Is calling the newInstance method on the same Constructor object from multiple threads safe.
    Or is this not thread safe leading to wrongly constructed objects?

    ejp wrote:
    And as Constructors are immutable, it's hard to see how it's going to get altered.Constructors are basically immutable, but they have at least one state which can make the difference between newInstance working or failing.
    As you can see in the following example, setAccessible() is not something you would want to set to different values in different threads.
    import java.lang.reflect.Constructor;
    public class Main {
        public static void main(String... args) throws Exception {
            Constructor cons = Private.class.getDeclaredConstructor();
            cons.setAccessible(false);
            try {
                System.out.println("cons.isAccessible()= " + cons.isAccessible());
                cons.newInstance();
                throw new AssertionError("IllegalAccessException expected");
            } catch (IllegalAccessException expected) {
                // ignored
            cons.setAccessible(true);
            System.out.println("cons.isAccessible()= " + cons.isAccessible());
            cons.newInstance();
    class Private {
        private Private() {
    }

  • Is java.xml.parsers.DocumentBuilder Thread Safe?

    Does anyone know if the DocumentBuilder is thread safe? Meaning,
    can I call the parse(...) methods from several threads simultanously, without getting errors?
    I would be happy if anyone can also point me to the documentation that says DocumentBuilder is or isn't thread safe.

    My Code Like Such:
    public class DigestUtil
    private static MessageDigest md_md5 = null;
    static
    try{
    md_md5 = MessageDigest.getInstance("MD5");
    }catch(Exception ex)
    public static byte[] DigestMD5(byte[] b)
    return b==null ? null : md_md5.digest(b);
    I Don't Wish to Every Digest, Every Create MessageDigest Instance.

  • 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

  • Java.nio, FileChannel, FileLock conundrum...

    Hey all--
    I want to have multiple java machines on multiple clients to access a singe file. I want the first java machine to access it to lock the file so only it can write to the file. Other machines may come in later and read it.
    Here's the trouble. If I simply access the file as, say, a RandomAccessFile in "rw" mode. All the clients may read and write to their hearts desire without throwing and exception.
    So I found that if I obtain a FileChannel from the RandomAccessFile, I can tryLock(0,Long.MAX_VALUE,true) to obtain a Shared Lock.
    Here's the trouble. A client can obtain the lock and prevent others from writing to it successfully while allowing them to read from it...great!. HOWEVER, even though that particular client has the lock, the client can't write to the file either!
    myRandomAccessFile.write() methods NOR myRandomAccessFile.getChannel().write(myByteBuffer);NOR
    FileLock myFileLock =myRandomAccessFile.getChannel().tryLock(0,Long.MAX_VALUE,true);
    FileChannel lockedChannel = myFileLock.channel();
    lockedChannel.write(myByteBuffer);all of these throw a java.io.IOException "The process cannot access the file because another process has locked a portion of the file"
    I'm only running one process and one virtual machine. I also checked to make sure myFileLock != null and that myFileLock.isValid()==true So does obtaining a filelock also prevent my OWN program from writing to the file?! If so what's the use of a filelock? Because in order to write to the channel upon whose lock I have, I'd have to release the lock which would allow any other clients the ability to write to it concurrently.
    Thanks for the help! The documentation seems a bit sparse on this...

    I know they say it's platform dependent. But what's weird is that I know native Windows and native Mac apps (the two systems this program will run on) both allow the type of lock I describe. Yet, at least on Java on Windows, this locking system doesn't work.
    "FileLock protects against other locks."
    So this would be great too! It would at least let me sense when another jvm from a different machine was accessing my file and I, as the programmer, could say if someone else has a lock, my app won't do any writing.
    The problem is that the only locks I appear to be able to get are 1) exclusive lock that boots everyone from coming within a Gigabyte of the file... or
    2) a shared lock that let's no one write including the locker of the file.
    Even if it doesn't let me have a "everybody read, only I write" lock, I wish it let me have a lock that just said, "someone's currently accessing the file besides you"...then I could fill in, "so don't do any writing."
    Which brings me to what you said that's kind of exciting "Also be aware that you can lock bytes beyond the end of the file:"
    So if I lock a RandomAccessFile only at the byte Long.MAX_VALUE-1, other's would be able to see that lock, even though that aspect of the file on others file systems didn't even exist? Because if so, you've answered my question. That would let me write and read the rest of the file but still have other apps detect whether there was a lock on the file or not.
    I suppose I could also just lock the first byte of the file and ask the same question. I'm going to play around with that and see if it works.

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

Maybe you are looking for