Friday, September 14, 2007

How portable is Java code?

In my last blog entry, I mentioned the differences in file locking behaviour I found between Sun's Windows JDK and Mac JDK. Well, I recently acquired a Dell server, and am running SLES 10.1 64-bit edition on it. The default Java 5 SDK that comes with SLES 10.1 is IBM's JDK 5 SR3. SimpleDBM fails to pass all its test cases under this JVM. All tests pass successfully when I run using Sun's Java 6 SE Update 2 64-bit JVM.

I haven't tried any other JDK's yet, but it would be interesting to see the results.

The point is that when I code in Java, I expect my code to run correctly on all JDKs. I do not want to have to worry about portability issues. But reality is that the JDK and its libraries are so large, that it must be very hard to make independently developed JVM's to be completely compatible.

Update: One of the test cases started failing because the HashMap.values().toArray() on IBM's JVM returns values in reverse order of the Sun JVM. This changed the results of the test to be different from what was expected, and therefore the test failed.

Java on Mac

Recently bought an iMac - with 24inch screen, and this is now my development platform for simpledbm. I am using JDK 5 and Eclipse 3.3.

So far one test case has failed. Upon investigation, found that the behaviour of FileChannel locking is different on the Mac. It seems that Mac JVM allows multiple threads within the same JVM to acquire exclusive locks on a file concurrently - whereas on Windows, we get an OverlappingFileLockException exception. It also seems that within the same thread, it is okay to acquire a lock more than once on the same file on Mac but not on Windows.

I was relying on the locking behaviour I saw on Windows, to allow simpledbm to detect multiple instances of simpledbm running concurrently against the same database.

Interestingly, the specification of locking behaviour seems contradictory:
File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
But on the other hand:
The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock.
Which is right?