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

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();