Search code examples
javasynchronizationclassloader

Is java.lang.reflect.Field instance uniq in single class loader?


I have some java codes synchronized in a Field object. It looks like:

Field f = SomeClass.class.getDeclaredField("field1");
synchronized(f) {
  ....
}

Can java ensure that everytime I get a Field object by reflection, it's alway the same instance? So I can synchronize code block on it. I know it's ok for Class, but not sure about Field. Thanks


Solution

  • This simple example shows that it is not the same instance (it prints false). Why would you want to synchronized on a Field object anyway? I suppose you realise that it is not equivalent to locking on the underlying variable.

    You should explain why you want to do that, as there certainly is a better option.

    class Test {
    
        int i;
    
        public static void main(String[] args) throws Exception {
            Class c = Test.class;
            Field f1 = c.getDeclaredField("i");
            Field f2 = c.getDeclaredField("i");
            System.out.println(f1 == f2); //prints false
        }
    }