Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! :)

like image 246
Alexandros Avatar asked Jul 29 '16 10:07

Alexandros


People also ask

Can we use try with resources without catch?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.

What is the advantage of using try with resources statement give an example?

The try-with-resources statement ensures that each resource is closed at the end of the statement execution. If we don't close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it. You can pass any object as a resource that implements java.

Can we use finally with try with resources?

You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement.

Which of the following is a correct statement about try with resources statement in Java 9?

The try-with-resources statement is a try statement with one or more resources duly declared. Here resource is an object which should be closed once it is no more required. The try-with-resources statement ensures that each resource is closed after the requirement finishes.


Video Answer


2 Answers

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.

like image 145
Mureinik Avatar answered Nov 02 '22 22:11

Mureinik


Under the covers, most resources (e.g. File Descriptors) are effectively allocated from a pool by the Operating System, and then returned to the pool when closed.

Using try-with-resources in this way is perfectly valid.

N.B. your code example has significant threading issues though, but I assume the necessary thread safety has been removed for clarity in the question. I mention it only because people should NOT copy your code and use it in an implementation.

like image 35
Harry Harrison Avatar answered Nov 02 '22 22:11

Harry Harrison