Gandalf
Gandalf

Reputation: 9855

Java retry after IOException

If I have stream that I expect at times may throw an IOException, and want to catch the exception and retry where will the stream be (i.e. will the mark still be after the last successfully read block/byte)? Ca I simply catch the exception and execute the same read(byte[]) and have any expectation I will not be missing data? Thanks.

Upvotes: 2

Views: 3274

Answers (2)

ddyer
ddyer

Reputation: 1786

Some IOExceptions are fatal where you can't expect to continue. Make sure successive retries may succeed. (Ie. check whether the exception at hand is recoverable.)

Upvotes: 0

yegor256
yegor256

Reputation: 105153

You can try use mark()/reset() methods, AOP, and Java annotations from jcabi-aspects (I'm a developer). The function that reads will look like this (pseudo code):

@RetryOnFailure(attempts = 5)
private byte[] read(InputStream stream, int length) {
  stream.reset();
  byte[] bytes = new byte[length];
  stream.read(bytes, 0, length);
  stream.mark(length);
  return bytes;
}

If an IOException is thrown at stream.read(bytes, 0, length) call to mark() won't happend and the next call to reset() will set the pointer to the previous position.

Upvotes: 1

Related Questions