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

前端 未结 5 518
忘了有多久
忘了有多久 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 03:57

    i would provide instances to those objects through Factory methods and with that i have control over the creation of them, and i will feed the consumers with Proxies that does the logic of closing the object

    interface Service {
     T execute();
     void close();
    }
    
    class HeavyObject implements Service {
      SomeObject execute() {
      // .. some logic here
      }
      private HeavyObject() {}
    
      public static HeavyObject create() {
       return new HeavyObjectProxy(new HeavyObject());
      }
    
      public void close() {
       // .. the closing logic here
      }
    }
    
    class HeavyObjectProxy extends HeavyObject {
    
      public SomeObject execute() {
        SomeObject value = super.execute();
        super.close();
        return value;
      }
    }
    

提交回复
热议问题