Is it normal that any Amazon AWS Lambda Java function takes an unreasonable long time to finish when an uncaught exception is thrown? Please note this is a general question regarding Amazon Lambdas in Java, since I am testing this in a very generic way, with a very simple bare bones function.
For example, consider the function below, that validates a PIN. If the PIN is valid, it returns the text: PIN is OK: "A"
. Otherwise, it throws an IOException
:
public class Hello implements RequestStreamHandler {
private static final int BUFFER_SIZE = 65_536;
private static final int MAX_SIZE = 262_144;
private static final String CHARSET_UTF8 = "UTF-8";
private static final byte[] buffer = new byte[BUFFER_SIZE];
private static final ByteArrayOutputStream baos = new ByteArrayOutputStream();
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
String input = readInputStreamToString(inputStream);
// PIN is valid.
if (input.equals("\"A\""))
writeStringToOutputStream(outputStream, "PIN is OK: " + input);
// PIN is not valid.
else
throw new IOException("PIN is wrong: " + input);
}
private String readInputStreamToString(InputStream inputStream) throws IOException {
baos.reset();
int length, total = 0;
while ((length = inputStream.read(buffer)) != -1) {
total += length;
if (total > MAX_SIZE) throw new IllegalStateException("InputStream bigger than " + MAX_SIZE + ".");
baos.write(buffer, 0, length);
}
return baos.toString(CHARSET_UTF8);
}
private void writeStringToOutputStream(OutputStream outputStream, String info) throws IOException {
byte[] chars = info.getBytes(CHARSET_UTF8);
outputStream.write(chars, 0, chars.length);
}
}
To test the above code:
For a valid PIN, use
"A"
as the test data.For an invalid PIN, use any other input, for example:
"B"
.
Memory size is 128 MB, and max memory used is 48 MB. When the PIN is valid, the function is very fast, and exits in less than 1 ms. However, when the PIN was not valid, the function was timing out in 3 secs, and I was getting this:
{
"errorMessage": "2017-10-15T21:35:58.744Z *** Task timed out after 3.00 seconds",
"errorType": "java.lang.RuntimeException"
}
I then increased the timeout to 10 secs, and now it actually finishes around 7.5 secs and gives me a stacktrace:
{
"errorMessage": "PIN is wrong: \"B\"",
"errorType": "java.io.IOException",
"stackTrace": [ "example.Hello.handleRequest(Hello.java:83)" ]
}
My questions:
1) Is it normal that exceptions in lambda functions should take that much time for Amazon to process? Why? If not, why am I having this problem?
2) What is the recommended way of dealing with exceptions? Should I never let a function finish with an exception?