Java file-locking issues on Linux (Ubuntu Dapper)?

By | August 7, 2006

I was playing with a test server for something I was working on, and one of the data files got corrupted. From the look of it, half way through one write process, another started, erased the file, wrote the new content, finished. Then the first one wrote the remainder of the data. This confused me a fair bit, as I knew I’d implemented file locking to prevent that very thing happening.

So I wrote a test case.

The test case I wrote seems to work on Windows, but throws an assertion failure on Linux. I’d be interested to know what’s going on here. File locking seems a little bit black-magic-like.

The test case can be download from here, but the bulk of it (in ugly wordpress non-formatting) is:

File testFile = new File("_testfile.txt");
FileOutputStream fout = new FileOutputStream(testFile);
fout.write(new byte[] {1,2,3,4,5,6,7,8,9});
fout.close();
fout = new FileOutputStream(testFile);
FileLock lock = null;
try {
	lock = fout.getChannel().lock(0, Long.MAX_VALUE, false);
	assertNotNull(lock);
	Thread thr = new Thread() {
		public void run() {
			File testFile = new File("_testfile.txt");
			FileLock lock = null;
			try {
				FileOutputStream fout = 
					new FileOutputStream(testFile);
				lock = fout.getChannel().
					lock(0, Long.MAX_VALUE, false);
				if (!isInterrupted()) {
					fail("Lock broken :(");
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			} finally {
				if (lock != null && lock.isValid())
					try {
						lock.release();
					} catch (IOException e) {
						throw new 
							RuntimeException(e);
					}
			}
		}
	};
	thr.start();
	Thread.sleep(1000);
	thr.interrupt();

3 thoughts on “Java file-locking issues on Linux (Ubuntu Dapper)?

  1. tikitu

    Glad to say I’ve got no clue whatsoever. What’s kinda fun, though, is that in Dutch “fout” means “wrong”.

  2. robin Post author

    …I somehow don’t think that’s the problem, but maybe I should write up a test case with it just in case 🙂 ‘course, it makes “fout.write()” into some bad spella, bilingual pun…

  3. tikitu

    Owwwww, I didn’t notice that one. I honestly read it, though, the way might construct a test case myself:


    FileOutputStream right = ...;
    FileOutputStream wrong = ...;

    And recently I caught myself using a literally-translated Dutch expression to an English speaker (“make it up” instead of “finish it”). Downsides to partial bilinguality…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.