DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Mastering Thread-Local Variables in Java: Explanation and Issues
  • Unlocking Performance: Exploring Java 21 Virtual Threads [Video]
  • Visualizing Thread-Safe Singletons in Java
  • Double-Checked Locking Design Pattern in Java

Trending

  • Spring Security JWT Validation Best Practices
  • Three Measured Outcomes of Manually Scaling Fleet in Prod
  • Prompt Caching for LLMs, Part 2: Semantic Caching in Production
  • The "Just Read the Code" Myth Is Killing Your AI Workflow

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Locking Files in Java

Locking Files in Java

Time to get to know your locks! Whether you need blocking or non-blocking locks or want to know more about how they work, this quick example will set you straight.

By 
Arun Pandey
DZone Core CORE ·
May. 19, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
89.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In most I/O-based applications, we deal with concurrency, where several processes do reads/writes to a file. While reading/writing to a file, we need to ensure that it is not being used by other processes to ensure data integrity. The Java NIO API provides file locking at the operating system level (hence it is visible to other processes) so that other processes cannot access the file. The NIO API  allows the obtaining of shared or exclusive locks on either whole file or part of the file.

In Java, a file lock can be obtained using FileChannel, which provides two methods — lock() and tryLock() — for this purpose.

The lock()  method acquires an exclusive lock on entire file, whereas the lock(long position, long size, boolean shared) method can be used to acquire a lock on the given region of a ile. These two methods will block until the lock is obtained. Meanwhile, the methods tryLock() and tryLock(long position, long size, boolean shared) do the same, but they don't block and they return immediately.

These methods return a FileLock object, which can be used further to control the lock and, at the end, to release a lock. In the case of the  tryLock() method, if it fails to acquire a lock due to overlapping (lock already held by other process), then it returns null; if it fails due to some other reason, then an appropriate exception is thrown.

Now let us look at an example:

package com.test.nio.filelock;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileLockTest {

    private static final Log LOG = LogFactory.getLog(FileLockTest.class);
    private static FileChannel fc;
    private static RandomAccessFile randomAccessFile;

    public FileLockTest(String fileName) throws FileNotFoundException {
        randomAccessFile = new RandomAccessFile(fileName, "rw");
    }

    public void writeToFileWithLock(String data) {

        fc = randomAccessFile.getChannel();
        ByteBuffer buffer = null;

        try (fc; randomAccessFile; FileLock fileLock = fc.tryLock()) {
            if (null != fileLock) {

                buffer = ByteBuffer.wrap(data.getBytes());
                buffer.put(data.toString().getBytes());
                buffer.flip();
                while (buffer.hasRemaining())
                    fc.write(buffer);
            }
        } catch (OverlappingFileLockException | IOException ex) {
            LOG.error("Exception occured while trying to get a lock on File... " + ex.getMessage());
        }
    }
}


Don't forget to lock the file when your application has several processes that can read/write. Happy learning!

Java (programming language) Threading

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Thread-Local Variables in Java: Explanation and Issues
  • Unlocking Performance: Exploring Java 21 Virtual Threads [Video]
  • Visualizing Thread-Safe Singletons in Java
  • Double-Checked Locking Design Pattern in Java

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook