Search code examples
javatry-with-resources

Is using try-with-resources without a new object instance bad form?


Generally I've always seen try-with-resources used to allocate a new object instance whose close() method is invoked as it goes out-of-scope.

As far as I can tell, creating a new object is not a requirement and the try-with-resources syntax simply needs a local variable to call close() on when that goes out-of-scope. Therefore you can use it to control "paired operations" such as allocating something from a pool and making sure it is returned.

For example, MyHandle below shows how to release a pooled instance when you no longer need it:

// init
class MyHandle implements AutoCloseable {
    boolean inUse = false; 
    public MyHandle allocate() {
        inUse = true;
        return this;
    }

    public void close() {
       inUse = false;
    }
}

MyHandle[] pool = new MyHandle[POOL_SIZE];
for (int i = 0; i < pool.length; i++) {
    pool[i] = new MyHandle(i);
}

// allocate
MyHandle allocateFromPool() {
    for (int i = 0; i < pool.length; i++) {
        if (!pool[i].inUse)
            return pool[i].allocate();
    }
    throw new Exception("pool depleted");
}

// using resources from the pool

try (MyHandle handle = allocateFromPool()) {
   // do something
}
// at this point, inUse==false for that handle...

Is this considered bad form?

EDIT: I guess I'm asking if there's better alternatives to building this sort of logic, or if there's some major drawback when going with the approach above. I find that using this in a library makes for a clean API.

EDIT 2: Please disregard problems in the code example, I wrote it inline in the SO text box to make my question clear with some sort of example. Obviously it's not real code! :)


Solution

  • The try-with-resource syntax is intended as a syntactic sugaring to allow you to make sure you dispose an object, whatever the disposal logic would be. In your case, it's returning the object to the pool. There's absolutely nothing wrong with using try-with-resource like this. It may not be the most common usecase for it, but it's definitely a valid one.