Skip to main content

Locking a file in Java

Locking a file in Java is platform dependent. Write once run anywhere? Thumbs down. Some platforms will not allow a file access without a lock while others will.


This is very useful especially when writing your own database (I know some people will argue but this is still happening in corporations handling very sensitive data). It starts with a simple file access.



try {
final File file = new File("Tables.dat");
final FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();

// this method will block until a lock is acquired
final FileLock lock =fileChannel.lock();

// this method will not block, it will return null or throw an exception
lock = fileChannel.tryLock();

// TODO: do something with the file

// release the lock
lock.release();

// cleanup / close file
fileChannel.close();
} catch (Exception e) {
// TODO: handle exception
}

Caution: You really need to verify how the target platform handles files. This will not apply on a distributed database as well as networked file systems, if that’s the case you need to write at least a protocol for handling concurrency.

Comments

Popular posts from this blog

Android Studio:Unknown Host Error

After installing Android Studio, I got the following error: Unknown host 'services.gradle.org'. Please ensure the host name is correct. If you are behind an HTTP proxy, please configure the proxy settings either in Android Studio or Gradle. Consult IDE log for more details (Help | Show Log) Solution File --> Settings --> HTTP Proxy --> Auto-detect proxy settings

Architecture Complexity

Here are the items to consider: Coding to an interface Service Oriented Architecture Automated Testing Domain Driven Design Custom Data Access Layer Layered architecture Complexity is relatively equal the number of lines of code. Note that complexity is not bad. It must be justified.

Access VirtualBox Shared Folder in Ubuntu Guest

I have been doing this for quite some time now but I failed to document it. First, install the VirtualBox Guest Additions on your host. Then you create a mount point (assuming it is /media/shared). $ sudo mkdir /media/shared You may change the path if you want. Mount the shared folder using the command below. $ sudo mount -t vboxsf <folder> /media/shared Replace the <folder> above with the correct shared folder name. Enjoy.