java - Try-with transfer ownership -
in java 7, there try-with syntax ensures objects inputstream closed in code paths, regardless of exceptions. however, variable declared in try-with block ("is") final.
try (inputstream = new fileinputstream("1.txt")) { // stuff "is" is.read(); // give "is" owner someobject.setstream(is); // release "is" ownership: doesn't work because final = null; }
is there concise syntax express in java? consider exception-unsafe method. adding relevant try/catch/finally blocks make method more verbose.
inputstream opentwofiles(string first, string second) { inputstream is1 = new fileinputstream("1.txt"); // is1 leaked on exception inputstream is2 = new fileinputstream("2.txt"); // can't use try-with because close is1 , is2 inputstream dual = new dualinputstream(is1, is2); return dual; }
obviously, can have caller open both files, placing them both in try-with block. 1 example of case want perform operation on resource before transferring ownership of object.
the try-with intended used in situation identified resource must never persist outside scope of try block.
if want use try-with construction, must change design follows:
- delete
opentwofiles()
method. value free. - create constructor
dualinputstream
class takes 2 file names , creates 2inputstreams
. declare constructor throwsioexception
, allow throwioexceptions
. - use new constructor in try-with construct.
Comments
Post a Comment