theAnonymous
theAnonymous

Reputation: 1804

Java - dispose pattern

I want to make sure that my Objects (Class <? extends Object>) are properly disposed of, because other instances may hold data that are used by them. Example, a DEK/KEK pair for secret data.

Since Overriding finalize() is generally frowned upon, how do I make the IDE warn and force the developer to call dispose() iff the Object reference is set to null, or would be automatically set to null (example exiting a method)?

Assuming source code is under my direct control, and the IDE is Netbeans.

Upvotes: 4

Views: 1894

Answers (1)

skapral
skapral

Reputation: 1217

First of all, worth to mention that finalizers were deprecated in Java 9 in favour of the Cleaner. Probably this would be the better option then the one I will describe below. Didn't tried it yet though.

Speaking about the question itself: I'd try doing it that way:

  1. Assuming there is an object of type A, which implements Closeable.
  2. Make a class S with the only method: void execute(Consumer<A> consumer).
  3. In the method execute: instantiate object of type A, pass it to consumer (accept) then close it.
  4. In the client code - always use S, passing a lambda to it as a consumer. In lambda - you will get the instance of A and S will guarantee disposal of it.
  5. Make all constructors' visibility of class A limited to only the service S (like, make them package-private and place A in the same package with S). That will prevent A to be instantiated outside of S and left unmanaged.

Upvotes: 4

Related Questions