If there is a problem, how can I fix it? The classes SomeResource and ResourceManager are given by condition, tested and accepted to work correctly. You only need to use them correctly ...

// resourceManager is created and initialized correctly ... //Acquire a limited resource SomeResource r = resourceManager.acquire(); r.use(); //Now release the resource to be available for other users resourceManager.release(r); 
  • there may be a problem of resource release when an exception occurs ... then it is better to wrap everything in try catch finally - ermak0ff
  • Thanks a lot for the answer - Alexander Dermenzhi

1 answer 1

If the use() method is insecure with respect to exceptions, then this code may cause the resource not to be freed.

 SomeResource r = resourceManager.acquire(); try { r.use(); } catch (Exception e) { ... } finally { //Now release the resource to be available for other users resourceManager.release(r); } 
  • You can use the "try-catch with resources" construct: try(FileInputStream input = new FileInputStream("file.txt")) { int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } try(FileInputStream input = new FileInputStream("file.txt")) { int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } try(FileInputStream input = new FileInputStream("file.txt")) { int data = input.read(); while(data != -1){ System.out.print((char) data); data = input.read(); } } hasysdev.blogspot.ru/2012/06/try-java-7.html - DimXenon
  • one
    For this, the class must implement the AutoClosable interface, since nothing is known about SomeResource , this approach is incorrect. - Pavel Parshin