C
Chris Uppal
Any thoughts on this ?
I've just noticed that code like:
=====================
public class Test
{
public Class aMethod()
{
return Test2.class;
}
}
class Test2
{
}
=====================
is re-written by the compiler as if it had been:
=====================
public class Test
{
static class$Test2;
static Class class$(String name)
{
try
{
return Class.forName(name);
}
catch (ClassNotFoundException e)
{
throw new NoClassDefFoundError(e.getMessage());
}
}
public Class aMethod()
{
if (class$Test2 == null)
class$Test2 = class$("Test2");
return class$Test2;
}
}
class Test2
{
}
=====================
However the generated implementation of aMethod() is not threadsafe. The
compiler should either generate a "synchronized" block around the test-and-set,
or "declare" the synthetic static variable class$Test to be volatile.
The first option looks tricky since the code would have to be synchronized on
the class object for class Test -- which would cause the same problem ;-) or
possibly it code use a second static synthetic variable which would just be a
lock, and which was initialized as class initialisation. But then if it did
that, then why not just assign class$Test in the class's <cinit> ? Perhaps the
easiest thing to do would be to generate a static synchronized accessor method
for class$Test, rather than accessing the field directly from the instance
method.
Am I missing something or is this a bug ?
I'm using the compiler from J2DSK 1.4.2.
-- chris
I've just noticed that code like:
=====================
public class Test
{
public Class aMethod()
{
return Test2.class;
}
}
class Test2
{
}
=====================
is re-written by the compiler as if it had been:
=====================
public class Test
{
static class$Test2;
static Class class$(String name)
{
try
{
return Class.forName(name);
}
catch (ClassNotFoundException e)
{
throw new NoClassDefFoundError(e.getMessage());
}
}
public Class aMethod()
{
if (class$Test2 == null)
class$Test2 = class$("Test2");
return class$Test2;
}
}
class Test2
{
}
=====================
However the generated implementation of aMethod() is not threadsafe. The
compiler should either generate a "synchronized" block around the test-and-set,
or "declare" the synthetic static variable class$Test to be volatile.
The first option looks tricky since the code would have to be synchronized on
the class object for class Test -- which would cause the same problem ;-) or
possibly it code use a second static synthetic variable which would just be a
lock, and which was initialized as class initialisation. But then if it did
that, then why not just assign class$Test in the class's <cinit> ? Perhaps the
easiest thing to do would be to generate a static synchronized accessor method
for class$Test, rather than accessing the field directly from the instance
method.
Am I missing something or is this a bug ?
I'm using the compiler from J2DSK 1.4.2.
-- chris