Java Iterator supported by network connection

With some frequency, I find myself writing APIs that offer Iterator<Foo> , which is supported by a network connection. The implementation opens a network connection, reads information from the stream, and deserializes this information in Foo to pass to the caller. Unfortunately, there is always the possibility of an IOException , as well as the need to correctly close the network connection (which can be done automatically when the caller reads the last Foo , but what if this does not happen?).

There are already a couple of questions ( here and here ) on how to deal with checked exceptions that will be implemented in the Iterator implementation, and the accepted advice is "to wrap them in an unverified RuntimeException s". Meanwhile, to allow the closure of the network connection, we can implement Closeable . So, we got something like this for a good user checking exception checking:

 Iterator<Foo> iter = null; try { iter = getFooIterator(); while(iter.hasNext()) { Foo foo = iter.next(); // do something with foo } } catch(RuntimeException e) { if(e.getCause() instanceof IOException) { // do something with the IOException } else throw e; } finally { if(iter instanceof Closeable) try { ((Closeable)iter).close(); } catch(IOException e) {} } 

And it seemed like such a good idea to implement Iterator . Is there a better way?

+4
source share
1 answer

The IMO's first step would be to wrap it in an implementation or application-specific exception, eliminating the need to catch a generic RuntimeException or check the root cause.

I would consider a specific implementation to avoid a closing check and wrap an IOException .

 NetworkIterator<Foo> iter = null; try { iter = getFooIterator(); while (iter.hasNext()) { Foo foo = iter.next(); // do something with foo } } catch (NetworkIteratorExceptiom e) { // do something with the IOException } finally { iter.close(); } 

I probably would not have allowed this method to make a template plan, but I would have been tempted; about:

 NetworkIterator<Foo> iter = new IteratorThang<Foo>() { @Override public void each(Foo foo) { // Do something with foo } }; 
+1
source

Source: https://habr.com/ru/post/1392791/


All Articles