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

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.

Repair Windows 7 System Files

8 out of 10 average PC users have their box’s system files altered by malwares, viruses, etc. We usually reinstall the OS if the antivirus and anti malware software did not perform their job well. Here’s one way to fix the corrupted system files without the need of restarting your Windows 7 box. 1. Run the Command Prompt as Administrator 2. Type the following command C:\Windows\system32\> sfc /scannow 3. After the verification phase, you will receive a message about your system files’ integrity Windows Resource Protection did not find any integrity violations.