Jdk7 AutoCloseableを使ってtry-with-resourcesでリソースを開放

1.リソースを開放サンプル
public class ResCheck {
public static void main(String[] args) {
try(Resource res = new Resource()) {
res.doSome();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}

class Resource implements AutoCloseable {
void doSome() {
System.out.println(“do something");
}
@Override
public void close() throws Exception {
System.out.println(“resource is closed");
}
}7
2.同時に多数のリソースを開放する
public class ResStartnews24 {
public static void main(String[] args) {
try(ResourceSome some = new ResourceSome();
ResourceOther other = new ResourceOther()) {
some.doSome();
other.doOther();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}

class ResourceSome implements AutoCloseable {
void doSome() {
System.out.println(“do something");
}
@Override
public void close() throws Exception {
System.out.println(“some resource is closed");
}
}

class ResourceOther implements AutoCloseable {
void doOther() {
System.out.println(“do other things");
}
@Override
public void close() throws Exception {
System.out.println(“other resource is closed");
}
}

Java

Posted by arkgame