On Thu, 14 Apr 2022 18:06:10 GMT, Xue-Lei Andrew Fan <xue...@openjdk.org> wrote:
> This is an effort to fix a problem introduced in the fix for > [JDK-8284368](https://bugs.openjdk.java.net/browse/JDK-8284368), which > replaced the finalizers in jdk.crypto.cryptoki with Cleaners. However, there > is a problem with the code changes. The Runnables registered with Cleaner > refer to the object being registered ('this'). Meaning, the Cleaner mechanism > will keep the objects reachable, preventing them from being cleaned and > collected. src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java line 168: > 166: // Calls disconnect() to cleanup the native part of the wrapper. > 167: Cleaner.create().register(this, > 168: () -> PKCS11.disconnect(pNativeData)); If I'm not mistaken each new call to Cleaner.create() will create a new cleaner and a new deamon thread for it, so it's not recommended to create one cleaner per object. Also it might be worth double checking that the lambda created here doesn't capture `this`: IIRC there were some subtle cases where a lambda could unexpectedly capture `this`. Also probably the cleaner itself can't be GC'ed while its thread is running but you might be relying on undocumented behavior. It would be more prudent to stick it in a static variable to retain a strong reference. ------------- PR: https://git.openjdk.java.net/jdk/pull/8248