In Java, how to check that AutoCloseable.close() has been called?

前端 未结 5 517
忘了有多久
忘了有多久 2021-02-01 03:38

I am authoring a java library. Some of the classes that are meant to be used by library users, hold native system resources (over JNI). I\'d like to ensure that the user \"dispo

5条回答
  •  长发绾君心
    2021-02-01 04:15

    If I were you, I'd do the following:

    • Write a static wrapper around your calls that returns "heavy" objects
    • Create a collection of PhantomReferences to hold all your heavy objects, for cleanup purposes
    • Create a collection of WeakReferences to hold all your heavy objects, to check whether they are GC'd or not (have any reference from the caller or not)
    • At teardown I would check the wrapper to see what resources have been GC'd (have reference in the Phantom, but not in the Weak), and I'd check whether they have been closed or nor properly.
    • If you add some debug/caller/stacktrace information while serving the resource, it will be easier to trace back the leaking test case.

    It also depends whether you want to use this mechanism in production or not - maybe it is worth to add this feature to your lib, because resource management will be a problem in production environment, too. In this case you don't need a wrapper, but you can extend your current classes with this feature. Instead of a teardown, you can use a background thread for regular checks.

    Regarding reference types, I recommend this link. PhantomReferences are recommended to use for resource cleanups.

提交回复
热议问题