user452425
user452425

Reputation:

MethodHandle and thread safety

Is it safe to cache and re use the instances of java.lang.invoke.MethodHandle?

I check the JavaDoc and couldn't find anything about thread safety.

Upvotes: 2

Views: 372

Answers (2)

Rogério
Rogério

Reputation: 16380

Yes, it should be perfectly safe to share MethodHandle objects between threads.

Note the API documentation says the following about it:

Method handles are immutable and have no visible state. Of course, they can be bound to underlying methods or data which exhibit state. With respect to the Java Memory Model, any method handle will behave as if all of its (internal) fields are final variables. This means that any method handle made visible to the application will always be fully formed. This is true even if the method handle is published through a shared variable in a data race.

Upvotes: 1

Esko
Esko

Reputation: 29377

MethodHandle is an abstraction for code invocation, not the management of state behind the code. Thus the reasoning for thread safety is that it is reliant on the target method that is being actually executed, not the MethodHandle object itself.

Upvotes: 1

Related Questions