同时调用时的 JVM 方法调用内部

JVM method invocation internals when simultaneous invocation

这个标题很难拟定,所以如果有人能把它写得更简洁一些,我将不胜感激。

我知道 Java 中的方法调用是如何工作的。基本上,JVM 进行查找 table 以查找特定方法然后调用它。

假设我们有一个 MyClass 类型的实例列表,我们通过调用 i.E. toString() 在每个实例上。将有多个线程同时调用 toString() 。都指向方法栈中的同一个toString()。

所以我的问题是:JVM 内部是否有一些内部同步来处理这个问题?还是每个 object 都有自己的内联方法?

我找不到这方面的任何详细信息。 Oracle Docs 的级别太高了。不胜感激。

谢谢

同步的是数据,不是代码(方法)。

每个线程都有自己的 stack,其中存储了局部变量和调用方法链的 return 地址。当程序遇到方法调用时,将return点(方法调用完成时执行的指令)的地址存储在线程栈中,程序流程跳转到新方法(执行该方法的指令) ).

可以有许多线程执行相同的代码(位于内存中某处的同一组指令),但每个线程都有自己的堆栈。

I know how method invocation works in Java. Basically the JVM holds a lookup table where to find a specific method and then invokes it.

正确。

Assume we have for example a list of instances from type MyClass and we process these with a parallel stream by calling i.E. toString() on every instance. There will be multiple threads calling toString() at the very same moment. All point to the same toString() in the method stack.

正确。

So my question is: Is there some internal synchronization going on inside the JVM to handle this?

没有。为什么?该代码是只读的:它不需要顺序访问。

Or does every object have its own method inlined?

没有。为什么需要它?

越来越技术化但是..

Basically the JVM holds a lookup table where to find a specific method and then invokes it.

确实如此,但它可以内联一个方法的多个实现,而无需使用此类查找 table。

There will be multiple threads calling toString() at the very same moment. All point to the same toString() in the method stack.

虽然代码名义上是只读的,但实际上它是分阶段编译和重新编译的,也可能反编译。每次发生这种情况时,代码实际上都已更改。它做同样的事情,但方式不同。所做的是在 运行 时交换对代码的引用,这可能意味着不同的线程可能 运行 同一方法的不同版本一段时间。

So my question is: Is there some internal synchronization going on inside the JVM to handle this?

它没有使用 JVM 可见锁,我怀疑它根本没有使用互斥锁,而是使用线程安全操作来交换应该调用的方法。

Or does every object have its own method inlined?

对象有数据,没有方法。对象有一个对 class 的引用,它有对方法的引用。这些引用可以在应用程序的生命周期内发生变化。