Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'volatile' in method signature? [duplicate]

This one is weird. I have the following code:

class A
{   
    protected A clone() throws CloneNotSupportedException
    {
        return (A) super.clone();       
    }
}

when I de-compiled its bytecode through 'showmycode.com', it showed me the following code:

class A
{

    A()
    {
    }

    protected A clone()
    throws clonenotsupportedexception
    {
        return (A)super.clone();
    }

    protected volatile object clone()
    throws clonenotsupportedexception
    {
        return clone();
    }
}

What does it mean for a method return type to be volatile in the second 'clone' method? (This code was compiled through Eclipse's default JDK 1.6 compiler).

like image 395
shrini1000 Avatar asked Apr 29 '12 05:04

shrini1000


People also ask

Can methods be declared volatile?

The volatile keyword cannot be used with classes or methods. However, it is used with variables. It also guarantees visibility and ordering. It prevents the compiler from the reordering of code.

Is volatile synchronized?

Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables.

Is volatile variable in Java thread safe?

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem.

What determines the signature of a method?

The signature of a method consists of the name of the method and the description (i.e., type, number, and position) of its parameters. Example: toUpperCase()


1 Answers

This answer has already been covered in the question Why make a method volatile in java? But here's some more information.

When you overload methods (possibly only generic methods in the superclass), the method is marked as being a "bridge method". From java.lang.reflect.Modifier:

static final int BRIDGE    = 0x00000040;

Unfortunately, this is the same bit that is used to mark fields as being volatile:

public static final int VOLATILE         = 0x00000040;

If you print the modifiers on that method you will see something like:

public volatile

This is a limitation in the Modifiers.toString(int) method that doesn't know if it is a field or method.

public static String toString(int mod) {
    StringBuffer sb = new StringBuffer();
    ...
    if ((mod & VOLATILE) != 0)  sb.append("volatile ");
    // no mention of BRIDGE here
    ...
    return sb.toString().substring(0, len-1);
}
like image 81
Gray Avatar answered Sep 20 '22 22:09

Gray