Hi,
I'm interested in understanding how a Java VM (or any VM for that
matter) deals with situations that could cause a segfault or similar
error in C/C++ multithreaded code. Specifically, I'm wondering if, in
order to avoid segfaults caused by race conditions, a VM must grab
thread locks or somehow synchorize code, even if that code lacks the
java 'synchronized' keyword. Here is some contrived example code:
class Example {
private int [] ia;
...
int getLastElement() {
return ia[ia.length - 1];
}
void resize(int sz) {
ia = new int[sz];
}
}
Now, assuming we don't synchronize the methods, we have a race
condition.
1. Thread A enters getLastElement, and reads ia.length.
2. Thread B enters resize and sets ia to a smaller array.
3. Thread A completes getLastElement, accessing the new ia and getting
an ArrayIndexOutOfBounds exception.
The VM must, somewhere "under" the Java, have access to raw memory and
objects. How can it execute bytecode for getLastElement without
risking a low-level error like a segfault? (Instead, we get our
beautfied java exception, with traceback, etc.)
Rob
Chris Uppal - 28 Feb 2006 10:56 GMT
> The VM must, somewhere "under" the Java, have access to raw memory and
> objects. How can it execute bytecode for getLastElement without
> risking a low-level error like a segfault? (Instead, we get our
> beautfied java exception, with traceback, etc.)
If the JVM (JITer) can't prove to itself that the scenario you descibe is
impossible, then it must range-check each access to the array. Since there are
no operations that change the size of an array, it can ensure that it has a
thread-safe reference to the array by copyng the reference from the field "ia"
into a local variable.
So your example might be executed as if the source had read:
int
getLastElement()
{
int x1 = ia.length - 1;
int[] x2 = ia;
int x3 = la.length;
if (x1 > x3)
throw new ArrayIndexException();
return x2[x1];
}
-- chris
rob.nikander@gmail.com - 28 Feb 2006 12:50 GMT
Ah, that makes sense.
thanks,
Rob
Mike Amling - 28 Feb 2006 20:49 GMT
>>The VM must, somewhere "under" the Java, have access to raw memory and
>>objects. How can it execute bytecode for getLastElement without
[quoted text clipped - 15 lines]
> int[] x2 = ia;
> int x3 = la.length;
int x3=x2.length;
> if (x1 > x3)
if (x1 >= x3 or x1 < 0)
> throw new ArrayIndexException();
> return x2[x1];
> }
--Mike Amling
Chris Uppal - 28 Feb 2006 21:03 GMT
[me:]
> > int[] x2 = ia;
> > int x3 = la.length;
>
> int x3=x2.length;
Yes indeed, thanks for the correction.
-- chris