I am trying to create a function that will receive a stream of strings and it will return a sorted list of strings that meet all of the following criteria:
- They must contain the pattern
- The strings length must be equal to or greater than the min length number
- The strings length must be an even or odd number
Although I am able to compile the code I still get an error when testing it. “java.util.concurrent.TimeoutException”
Below is my function.
….
public static List<String> findWinners(String pattern, int minLength, boolean even, Stream<String> stream) { return stream.filter(x -> x.matches(pattern) && x.length() >= minLength).filter(x -> x.length() % 2 == (even ? 0 : 1)) .sorted(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }).collect(Collectors.toList()); }
…….
Below is the full stacktrace:
java.util.concurrent.TimeoutException at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:204) at homeworkTests.StreamsHomeWorkTest.findWinners(StreamsHomeWorkTest.java:227) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298) at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.lang.Thread.run(Thread.java:829)`enter code here`
Advertisement
Answer
Based on the stack trace you’ve shared, the TimeoutException
has been thrown from the invocation of the blocking method get
of a FutureTask
.
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:204)
Specifically, the get
method you’ve invoked is the overloaded form with a timeout in input, as the no parameters form does not throw a TimeoutException
.
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html#get()
The problem does not lie within your stream, but with the timeout passed, either because the value is too small or the computation takes too long.
In case an upper time limit is not guaranteed, you’d better use the get
form with no parameters as it will block the execution until this has completed or interrupted by raising the corresponding exception.