繁体   English   中英

从反射调用同步方法

[英]Call synchronized method from reflection

我需要通过Java的Reflection API调用一些同步方法。 假设我有:

public final synchronized void doSomething() {
    Thread.sleep(1000);
}

如果我直接从两个线程中调用此方法,则一个线程将进入该方法,而另一个线程将不得不等到第一个线程离开方法块(一秒钟后)。 然后,另一个线程可以进入该方法,任何其他线程都需要等待。

如果我不直接调用方法而是通过反射调用它,有什么区别吗? “阻塞”行为会是一样的吗?

阻塞行为将与调用该方法而不进行反射时完全相同。 基本上,下面的JVM将执行相同的逻辑。 您可以使用以下代码片段自行尝试:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SynchronizedReflectionTest {

public static void main(String[] args) {
    SynchronizedReflectionTest test = new SynchronizedReflectionTest();

    for(int i=0; i<5; i++) {
        final int finalI = i;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Method someThing = SynchronizedReflectionTest.class.getDeclaredMethod("someThing", new Class[]{int.class});
                    someThing.invoke(test, finalI);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

public synchronized void someThing(int nr)
{
    System.out.println("Executing someThing from "+nr);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Finished executing from nr "+nr);
}

}

从打印结果中,您可以看到方法调用已同步。 打印结果:

Executing someThing from 0
Finished executing from nr 0
Executing someThing from 4
Finished executing from nr 4
Executing someThing from 3
Finished executing from nr 3
Executing someThing from 2
Finished executing from nr 2
Executing someThing from 1
Finished executing from nr 1

JVM保证受锁保护的代码将在同步块中执行,并且如果依赖于方法的类型,则调用反射机制将完全不安全且无用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM