Home arrow static arrow Java Programming [Archive] - java.nio.FileChannel tryLock() method does not lock!!!
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - java.nio.FileChannel tryLock() method does not lock!!!
This topic has 5 replies on 1 page.

Posts:9
Registered: 10/20/02
java.nio.FileChannel tryLock() method does not lock!!!  
Jul 1, 2004 6:29 PM



 
Hello,

I have the following:
           ...           RandomAccessFile raf = new RandomAccessFile(file, "rw");           try {                 lock = raf.getChannel().tryLock();          } catch (OverlappingFileLockException e) {                  System.out.println("File is locked"); // this never gets printed          }            if (lock != null) {                   // successfully acquired a lock                  System.out.println("acquired lock!!!"); // this gets printed alright                  // check if lock is valid                  System.out.println("is this lock valid?  "+lock.isValid()); // it always is when I run my app                                   // do stuff with the file                  ...          }          ....

Note that I do NOT close the channel, which would make the lock invalid.

Well, as far as I know, the code above tries to acquire an EXCLUSIVE lock (no read or write) on a file. It means that no other java application should be able to access that file, right?
My problem is that I can still open that file with a second instance of my app, regardless of the lock.

What am I missing?

PS: don't know if it's relevant, but I do this right AFTER acquiring the lock:

     InputStream stream = Channels.newInputStream(raf.getChannel());     XMLDecoder d = new XMLDecoder(new BufferedInputStream(stream));                        
 

Posts:9
Registered: 10/20/02
Re: java.nio.FileChannel tryLock() method does not lock!!!  
Jul 12, 2004 3:56 PM (reply 1 of 5)



 
Hi folks,

I have to insist on this one.

I've extract the following lines from the API docs:

"This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.

Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity."

Reading the above lead me to the following conclusions:

1. a lock should be visible to all processes in the machine that can access the file;
2. if a process can or not access a locked file is both system and aplication dependant;

In order to test file locking I created a lock on a simple text file (kept my app running through the whole process) and then tried to access it using different programs, Word for instance. They all could access it without problem.

So I ask: does Windows XP use merely advisory file locking? Word can't open the same document twice. Is it implemented in it, or is it an indication that WinXP's file locking mechanism is not merely advisory?

Thanks.

PS: I'm using SDK 1.4.2_05 on XP SP1.

 

Posts:9,091
Registered: 8/15/01
Re: java.nio.FileChannel tryLock() method does not lock!!!  
Jul 12, 2004 4:14 PM (reply 2 of 5)



 
I think Windows locking is just advisory. But I am no expert on windows file locking. So hopefully someone with more knollage will speak up, or the [url http://search.microsoft.com/search/results.aspx?qu=file+locking&View=msdn&st=b&c=0&s=1&swc=0]MSDN[/url] will tell ye.

Word gets round this by creating a second hidden file called ~[name of word doc].doc.
(I know this as it does not always delete said file. Grrrr
 

Posts:9
Registered: 10/20/02
Re: java.nio.FileChannel tryLock() method does not lock!!!  
Jul 13, 2004 5:11 AM (reply 3 of 5)



 
Thanks for the answer, mlk.

Well, I went through MSDN to find no answer. Anyway, now I noticed tryLock() blocks, and it shouldn't. I ran two instances of my app and the second one keeps waiting till I release the lock created on the first one!!! Here's some code:

...            try            {                lock = channel.tryLock();                System.out.println("File not locked");            }            catch (OverlappingFileLockException e)            {                // File is already locked in this thread or virtual machine                System.out.println("File locked");            }              try            {                BufferedReader in = new BufferedReader(new InputStreamReader(                        System.in));                String str = "";                while (str != null)                {                    System.out.print("> prompt ");                    str = in.readLine();                    if (str.equalsIgnoreCase("status")) {                        System.out.println("lock = "+lock);                    } else if (str.equalsIgnoreCase("exit")) break;                }            }...


As stated in the API docs, tryLock() should return immediately. Therefore, the 'lock = channel.tryLock();' should either return cleanly or throw an exception. Then, no matter what, 'prompt >' should appear in the console. Except it doesn't for the second instance. Exiting the first instance makes the second one print out 'prompt'. I believe this shows tryLock() was blocking the execution. Am I missing something?

Not being able to use file lock functionality has been annoying me for quite some time now. Urgh!!!!
Has someone used it on Windows with success? Is there another way of doing it (I know one could use native code, but I could not find example) ?

Thanks
 

Posts:9
Registered: 10/20/02
Re: java.nio.FileChannel tryLock() method does not lock!!!  
Jul 16, 2004 4:43 AM (reply 4 of 5)



 
PLEASE!!! ANYONE JUST TELL IF THEY HAD SUCCESS USING NIO's FILE LOCKING IN WIN XP.
 

Posts:1,044
Registered: 4/16/04
Re: java.nio.FileChannel tryLock() method does not lock!!!  
Jul 16, 2004 5:02 AM (reply 5 of 5)



 
From part of my application. This locks perfectly on Win2000
private FileLock lock;   public MainFrame(String title) {      super(title);      File lockFile = new File("lock.lf");           lockFile.deleteOnExit(); 		     try {          if(!lockFile.exists())               lockFile.createNewFile();	   			           lock = new FileOutputStream( lockFile ).getChannel().tryLock();            if(lock == null) {                 JOptionPane.showMessageDialog(null, "An Instance Of The Current Application Is Running.\n"                    + "This New Instance Will Be Terminated.", "Program Error", JOptionPane.ERROR_MESSAGE);                System.exit(0);             }      } catch(IOException ioe) {}   }

ICE
 
This topic has 5 replies on 1 page.