<classname>.class constuction not threadsafe ?

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
 
C

Chris Uppal

I said:
Any thoughts on this ?

*Immediately* after hitting the <send> button, I realised that the assignment
is idempotent, and that Class.forName() is (or bloody well should be)
threadsafe itself, so there's really no issue here.

Sigh...

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top