I have a list of TxnTypes with different complexities (process durations).
I want to find matched TxnType
from the list.
I tried to implement it by mixing parallel processing and short-circuit filter features of the stream.
but I noticed there is not a mixture of them.
I wrote the below sample. But noticed a mix of parallel and short-circuit not work properly.
Every run shows parallel processing working but not terminate when found as soon as found item!!!
class TxnType {
public String id;
public TxnType(String id) {this.id = id;}
public boolean match(String entry) {
Date s = new Date();
// simulate long processing match time TxnType
if (id.equals("1")) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Date f = new Date();
System.out.println("check id = " + id+ " duration = "+(f.getTime()- s.getTime()));
return id.equalsIgnoreCase(entry);
}
}
private void test4() {
// build list of available TxnTypes
ArrayList<TxnType> lst = new ArrayList<>();
lst.add(new TxnType("0"));
lst.add(new TxnType("1")); // long match processing time type
lst.add(new TxnType("2"));
lst.add(new TxnType("3"));
lst.add(new TxnType("4"));
String searchFor = "3";
System.out.println("searchFor = " + searchFor);
Date st, fi;
st = new Date();
Optional<TxnType> found2 =lst.stream().parallel().filter(txnType->txnType.match(searchFor)).findFirst();
System.out.println("found.stream().count() = " + found2.stream().count());
fi= new Date();
System.out.println("dur="+ (fi.getTime()- st.getTime()));
}
By running multiple times, I found that the processing was not terminated as soon as possible and wait to process all of them!!!!
searchFor = 3
check id = 4 duration = 0
check id = 2 duration = 0
check id = 3 duration = 0
check id = 0 duration = 0
check id = 1 duration = 4005
found.stream().count() = 1
dur=4050
Is there something like FilterFindFirst()
?