Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

FileLock doesn't work in UNIX (solaris)

807569Aug 21 2006 — edited Aug 21 2006
Hi all,
I have a piece of code which writes to xml file and before that locks the file to prevent two users writing in same file in same time.
This code works perfectly on my windows environment (Eclipse and windows 2000) but as soon as I put jar file in UNIX (SOLARIS) it doesn�t work and two clients can change at same time!
Anyone has an idea what is going on?

Note: I put sleep just to be able to make a delay so I can try to have access from second client session to test my lock

Following is my code:
  public synchronized void commitConfiguration() throws ConfigurationDataException
  {
      try {      
          // Get a file channel for the file
          File file = new File(uri);
          FileOutputStream outputStream = new FileOutputStream(file);
          FileChannel  channel = outputStream.getChannel();
          FileLock lock = fileLock(channel);

          if(lock != null) {
              try {
                  processCommit(outputStream);
                  Thread.sleep(8000);
              }finally {
                  Thread.sleep(8000);
                  lock.release();
                  channel.close();
              }
         }
          //reload the configuration
          refreshConfiguration();                             
    } catch (Exception e1) {        
        throw new ConfigurationDataException("Cannot commit file, because: " + e1.getMessage());
    }
  }
  
  private static FileLock fileLock( FileChannel  channel) throws IOException {
      // Use the file channel to create a lock on the file. This is a share lock not exclusive so
      // other users can still read but not set
      // This method blocks until it can retrieve the lock.
      //FileLock lock = channel.lock(0L, Long.MAX_VALUE, true);
      // Try acquiring the lock without blocking. This method returns
      // null or throws an exception if the file is already locked.
      FileLock lock =null;
      try {
          lock = channel.tryLock();
      } catch (OverlappingFileLockException e) {
          // File is already locked in this thread or virtual machine
      }
      if(lock == null) {
          lock = channel.lock();
      }
      return lock;      
  }
Thanks,
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 18 2006
Added on Aug 21 2006
4 comments
215 views