Ale*_*ros 12 java try-with-resources
一般来说,我总是看到try-with-resources用于分配一个新的对象实例,close()当其超出范围时,该方法的方法被调用.
据我所知,创建一个新对象不是必需的,try-with-resources语法只需要一个局部变量来调用close(),当它超出范围时.因此,您可以使用它来控制"配对操作",例如从池中分配内容并确保返回它.
例如,下面的MyHandle显示了当您不再需要它时如何释放池化实例:
// 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...
Run Code Online (Sandbox Code Playgroud)
这被认为是不好的形式吗?
编辑:我想我问是否有更好的替代方案来构建这种逻辑,或者如果采用上述方法存在一些主要缺点.我发现在库中使用它可以实现一个干净的API.
编辑2:请忽略代码示例中的问题,我在SO文本框中内联编写,以某种方式使我的问题清楚.显然这不是真正的代码!:)
Mur*_*nik 10
try-with-resource语法旨在作为一种语法糖,以允许您确保处置对象,无论处置逻辑是什么.在您的情况下,它将对象返回到池中.使用像这样的try-with-resource绝对没有错.它可能不是最常见的用例,但它绝对是有效的.