File Locking using java.nio package

I am trying to lock a file using FileChannel's lock method on a CIFS file system. My application is on windows and the CIFS is accessed using UNC format ( \\1.2.3.4\blah.. ). I get the following error
     java.io.IOException: The network request is not supported
     at sun.nio.ch.FileChannelImpl.lock0(Native Method)
     at sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:750)
     at java.nio.channels.FileChannel.lock(FileChannel.java:865)
From the same machine using the same UNC formatm, when I lock the file using windows C API, I can successfull lock.
Anyone has any idea why JVM can not lock even using nio package. Shouldnt it use the same ( or similar ) API under the hood as its clear by the package name java.nio
The C program I am using is
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main( int argc, char **argv )
int fh,numread;
char buffer[40];
char filename[500];
/* Quit if can't open file or system doesn't
* support sharing.
if ( argc > 1 )
          strcpy(filename,argv[1]);
else
          strcpy(filename,"locking.c");
fh = sopen(filename , O_RDWR, SHDENYNO, //_SH_DENYRW,
SIREAD | SIWRITE );
if( fh == -1 )
exit( 1 );
/* Lock some bytes and read them. Then unlock. */
if( locking( fh, LKNBLCK, 30L ) != -1 )
printf( "No one can change these bytes while I'm reading them\n" );
numread = _read( fh, buffer, 30 );
printf( "%d bytes read: %.30s\n", numread, buffer );
lseek( fh, 0L, SEEK_SET );
     printf( "Press a key to unlock the file.....\n" );
     getchar();
     locking( fh, LKUNLCK, 30L );
printf( "Now I'm done. Do what you will with them\n" );
else
perror( "Locking failed\n" );
_close( fh );
}

It uses LockFile and LockFileEx. Please check in the MSDN documentation the peculiarities of such APIs.
JNIEXPORT jint JNICALL
Java_sun_nio_ch_FileChannelImpl_lock0(JNIEnv *env, jobject this, jobject fdo,
                                      jboolean block, jlong pos, jlong size,
                                      jboolean shared)
    jint fd = fdval(env, fdo);
    HANDLE h = (HANDLE)_get_osfhandle(fd);
    DWORD lowPos = (DWORD)pos;
    long highPos = (long)(pos >> 32);
    DWORD lowNumBytes = (DWORD)size;
    DWORD highNumBytes = (DWORD)(size >> 32);
    jint result = 0;
    if (onNT) {
        DWORD flags = 0;
        OVERLAPPED o;
        o.hEvent = 0;
        o.Offset = lowPos;
        o.OffsetHigh = highPos;
        if (block == JNI_FALSE) {
            flags |= LOCKFILE_FAIL_IMMEDIATELY;
        if (shared == JNI_FALSE) {
            flags |= LOCKFILE_EXCLUSIVE_LOCK;
        result = LockFileEx(h, flags, 0, lowNumBytes, highNumBytes, &o);
        if (result == 0) {
            int error = GetLastError();
            if (error != ERROR_LOCK_VIOLATION) {
                JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                return sun_nio_ch_FileChannelImpl_NO_LOCK;
            if (flags & LOCKFILE_FAIL_IMMEDIATELY) {
                return sun_nio_ch_FileChannelImpl_NO_LOCK;
            JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
            return sun_nio_ch_FileChannelImpl_NO_LOCK;
        return sun_nio_ch_FileChannelImpl_LOCKED;
    } else {
        for(;;) {
            if (size > 0x7fffffff) {
                size = 0x7fffffff;
            lowNumBytes = (DWORD)size;
            highNumBytes = 0;
            result = LockFile(h, lowPos, highPos, lowNumBytes, highNumBytes);
            if (result != 0) {
                if (shared == JNI_TRUE) {
                    return sun_nio_ch_FileChannelImpl_RET_EX_LOCK;
                } else {
                    return sun_nio_ch_FileChannelImpl_LOCKED;
            } else {
                int error = GetLastError();
                if (error != ERROR_LOCK_VIOLATION) {
                    JNU_ThrowIOExceptionWithLastError(env, "Lock failed");
                    return sun_nio_ch_FileChannelImpl_NO_LOCK;
                if (block == JNI_FALSE) {
                    return sun_nio_ch_FileChannelImpl_NO_LOCK;
            Sleep(100);
    return sun_nio_ch_FileChannelImpl_NO_LOCK;
}

Similar Messages

  • Java.nio package Runtime error java.lang.UnsupportedClassVersionError.

    Hi
    I am using nio package and create a java program for file locking (FileLocking.java).
    Here is the sample
    try {
    file = new File("C:/acc.txt");
    channel = new RandomAccessFile(file, "rw").getChannel();
         lock = channel.lock(0, Long.MAX_VALUE, true);
    try {
              lock = channel.tryLock(0, Long.MAX_VALUE, true);
    catch (OverlappingFileLockException e) {
    return true;
    using wsad 5.1 and jdk1.4 i compiled this program.
    While executing i got the following runtime error..
    java.lang.UnsupportedClassVersionError: FileLocking (Unsupported major.minor version 48.0)
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:703)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:133)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:319)
         at java.net.URLClassLoader.access$400(URLClassLoader.java:92)
         at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:677)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:238)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:516)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:441)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:448)
    Exception in thread "main"
    Even if i try to recompile it in command prompt and run, i got the same error.
    please suggest me how can i overcome this problem.

    UnsupportedClassVersionError means that you are trying to execute a class for a newer version of the JVM on an older version of the JVM.
    Version 48.0 is for Java 1.4, so you have compiled your class with JDK 1.4.
    The computer you are trying to run the class on, has an older version of Java than 1.4 - check it!
    Try recompiling your source files with the "-target" switch, for example if you're running on Java 1.3, try compiling with:
    javac -target 1.3 ... FileLocking.java

  • How to use Java NIO to implement disk cache for serialized java objects

    Hi,
    I have a cache (implemented as hahstable etc.) that contains java objects (mostly strings) and swaps objects from runtime memory to the disk and back based on some algorithms. Currently, the reading and writing from the disk is implemented using java.io.* package i.e. fileInputstream and FileOutputStream. Essentially, I serialize the java object and write to the disk and the deserialize and give it back to the Hashtable cache.
    The performance of swapping from disk to memory is kinda slow. I have read that memory mapping would improve the performance.
    My idea is to do the following:
    Have one big file mapped to memory. I write the serialized objects to different portions of the file and then read those portions when needed. I can use the MappedByteBuffer for that but then I have the following questions. I will not store objects in the hashtable anymore.
    1. How do I delete things from the cache in the above design i.e. how do I delete portions of a mapped file?
    2. How do I serialize objects using ByteBuffers and then deserialize them? I guess this shouldn't be hard but just want to confirm.
    Do you think this is the right design or should I change? Right now using the old io package, I have a separate file for each object. When using the NIO package, I want to store all objects in a single file in different portions of the file, is that the right way to go?
    As you can see, I am beginner in memory mapped io and need help.

    Have one big file mapped to memory. I write the serialized objects to different portions of the file and then read those portions when needed. I can use the MappedByteBufferThis is a good idea, one that I have worked on. It involves quite a bit of manipulation with temporary buffers and a deep working knowledge of object serialization.
    1. How do I delete things from the cache in the above design i.e. how do I delete portions of a mapped file?The best way to handle this is do a two-step process, cutting the file into two pieces and gluing it back together where the original one is...
    2. How do I serialize objects using ByteBuffers and then deserialize them? I guess this shouldn't be hard but just want to confirm.It is hard. Wrapping the streams and making the IO work properly is not the challenge however. The hard part comes in hacking the object streams. The object input/output streams use a ClassDescriptor object which only gets written once/ read once. This shouldn't be a problem if you will read/write the entire file at once, but will bring you grief if you want random access to your objects. You will also need an indexing mechanism to support random access.
    Do you think this is the right design or should I change? Right now using the old io package, I have a separate file for each object. When using the NIO package, I want to store all objects in a single file in different portions of the file, is that the right way to go?I guess it depends on your needs. Do you require random access to objects? NIO provides some performance gains, but mostly for very large amounts of data (>10M in my experience).
    You can always write all your objects into the same file using normal io techniques and you can still generate an index and acheive random access. It might be easier...
    Good luck

  • Using Java.io Package in JSP

    Hi all,
    I want to use java.io package in a JSP and read one htm file. the program is giving me exception that the file say index.htm does not exists.
    I don't know how to solve this error. If any one can help me then it would be great. I don't want to use <%@ include %> or <jsp:include> tags.

    How are you accessing the file index.html?
    You might need to use the method new File(ServletContext.getRealPath("/index.html"))
    which will convert your web reference into a real filepath on your system.
    Cheers,
    evnafets

  • Package java.nio package does not exists

    I am trying to move some steps in java environment.
    I am using a Windows98 O.S.
    I downloaded jdk1.3 for Windows from sun site and installed it in c:\jdk1.3.1_02
    I have set path variable as .....;c:\jdk1.3.1_02\bin
    I am trying to compile a java source including java.nio package.
    What I do is:
    javac example.java
    What I get is:
    package java.nio does not exists
    I saw a lot of documentation about how to use java.nio but not how to link it.
    Any help I appreciate.

    Package java.nio is introduced with the version 1.4

  • Folder Locking using java

    Hi All,
    I want to implement the folder locking using java.But i can't find any method to implement my requirement. I find one method to lock a file using FileChannelObject.tryLock() or FileChannelObject.lock() methods of FileLock class. But the main problem is that FileChannel object is coming through only by calling getChannel() method on a RandomAccessFile object or FileInputStream object only.
    If i want to lock a folder i am not able to create the lock on it. So please provide me any example to create a lock on  a directory.
    Thanks in advance.

    JNI isn't magic. It can only call the operating system. The question is, is there really an operating system API that would let you do it.?

  • 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

  • Getting a file name using java.io.file

    Dear List,
    I am having problems using java.io package. I am reading a string on a linux tomcat server. I am
    trying to parse a windows type filepath (passed by a web-browser-client) and get only the filename. ie. sample.jpg.
    fileName = "c:\\temp\\sample.jpg"
    java.io.File file = new File(fileName);
    onlyFileName = file.getName();
    remember this on linux, and on my server onlyFileName contains "c:\\temp\\sample.jpg" and not sample.jpg as I would expect.
    can any one tell me what I (yet again) dont understand.? Strangely enough when the server is on windows and I am passing a linux string with the fileseperator as a forward-slash, the code manages to derive the correct filename.
    regards
    Ben

    Post this to the beginners forum - has nothing to do
    with native methods.Apologies I thought Java.io would be "native".
    sorry,
    BB

  • Help needed  while exporting crystal reports to HTML file format using java

    Help needed  while exporting crystal reports to HTML file format using java api(not using crystalviewer).i want to download the
    html file of the report
    thanks

    the ReportExportFormat class does not have HTML format, it has got to be XML. Export to HTML is available from CR Designer only.
    Edited by: Aasavari Bhave on Jan 24, 2012 11:37 AM

  • PDF created using Java iText package - Text not editable and not displaying font properties on Acrobat

    Hi,
    I have an issue in editing the text and viewing the font properties of a text region on a PDF created using Java iText package.
    I use Adobe Acrobat 9 Pro Extended and the option Tools -> Advanced Editing -> TouchUp Text Tool.
    The strange behaviour is that, I have 2 PDFs created out of the same base PDF and text added via Java iText package with the same Text, Font and other properties.
    One of the PDF has the text region editable on Acrobat but the other one has the text region which is not editable.
    But both the PDFs are editable via Adobe Illustrator.
    I have attached both the PDFs for your reference
    PDF_Editable.pdf - Editable on Acrobat
    PDF_Not Editable.pdf - Not Editable on Acrobat
    Any help or insight to find out the difference/issue with the PDF which is not editable via Acrobat would be appreciated.
    Thanks in advance.
    Regards,
    Madhusoodhan Henryraman

    You don't have direct control of the leading of a multiline text field. A common approach is to control the background color of the field with JavaScript since the lines are not really needed when the field is used in Reader/Acrobat. They may be useful when using the form by hand. For more information, see the posts by Max in this topic: http://acrobatusers.com/forum/forms-acrobat/how-do-i-use-multi-lined-text-fields-over-prin ted-line-area-existing-form

  • Change file mode using java?

    Hi
    Can I change file mode using java method other than
    Runtime.exec()
    thx
    Jacinle

    Hi
    Thank you Roopasri. But what I want is not using Runtime.exec
    I am using Unix and I want to change some image file access mode
    so not a RandomAccess File.
    So is there anything like chmod command on Unix?
    something like maybe java.io.File.chmod("755");
    I read that's a feature requested early on 1.2
    Will it be included in 1.4?
    Jacinle

  • Does JMQ 3.5 SP1 Enterprise Edition use Java NIO anywhere?

    Hi,
    I was wondering, does anyone know whether JMQ 3.5 SP1 Enterprise Edition uses Java NIO anywhere?
    Cheers, Andrew

    Yes ...
    java.nio is not used on the client (because it needs to support older
    jdk's), however we do use nio on the broker.
    java.nio is used:
    - in the "channels" support in the shared thread pool to allow
    non-blocking reads
    - we use the various Buffer classes for reading,writing and
    persisting some of our data

  • 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

  • How to read pdf files using java.io package classes

    Dear All,
    I have a certain requirement that i should read and write PDF files at runtime. With normal java file IO reading is not working. Can any one suggest me how to proceed probably with sample code block
    Thanks in advance.

    hi I also have the pbm. to read pdf file using JAVA
    can any body help meWhy is it so difficult to read the thread you posted in? They say: java.io is pointless, use iText. So why don't you?
    or also I want to read a binary encoded data into
    ascii,
    can anybody give me a hint how to do it.Depends on what you mean with "binary encoding". ASCII's binary encoding, too, basically.

  • How to deploy EAR on CE server using Java Support Package Manager

    Hello,
    I am using CE server where I want to deploy EAR file by using JSPM. I run this program in Drive:\usr\sap\CE1\J00\j2ee\JSPM\go.bat
    I have also put the EAR file into the inbox folder Drive:\usr\sap\CE1\SYS\EPS\in but still It does not show me any file to proceed further for deployment.
    Does any one has idea?
    Regards,
    NK

    Hi,
    The Java Support Package Manager is not able to deploy a single .ear file.
    If the *.EAR file is placed inside an SCA (Software Component Archive) then JSPM is able to deploy it.
    You have to create a .SCA from an .EAR file
    SAP note 1223957 contains an attachment (nwpacktool.zip) which can be used to create a .SCA file from the .EAR file.
    Gerd

Maybe you are looking for

  • Schedule lines for schedule agreement

    Hi, I need get all schedule lines for schedule agreement (all schedule lines = all visible in tab analysis u2013 all lines for all forecast dlv. sched). I check table VBEP and VBEH and I canu2019t find all items. Could you help? Thanks in advance, E

  • ADF FACES: jdeveloper hangs on opening a .jspx file

    I may not have had this file open since updating to EA13, but I'm not positive. Upon trying to open the file (code below), jdeveloper hangs. It sucks down roughly 50% of the CPU and the memory footprint slowly grows (about 3 MB per minute). As of now

  • Inbound Invoice thru XML Gateway

    Hi to all, Thru XML Gateway i am trying to process an inbound invoice based on 171_process_invoice_002.dtd Invoice is matching with Receipt in our system and i dont know how to fill RECEIPT_NUMBER in invoice line (INVLINE) Thanks in advance Edited by

  • Doubt about Deploy Application

    Hello Guys, I need deploy application XX.msi,size 17Mb on 300 desktop's by SCCM 2012. But I want know if is possible configure my limit bandwidth because my deploy can't cause slowness in my environment. Is it possible? Is there some configuration I

  • MBP automatic restart/reboot everyday.

    I left my MBP on every night to download movies and applications . Sometimes it can last through the night without restarting/rebooting , sometimes when i wake up to see it is at the startup login screen , which means my MBP has restarted/logged out.