I was checking the java 8 documentation and I found that class Pattern has the method asPredicate.
I was looking through StackOverflow but I've not found anything related with thread safety.
I know that the Pattern class is thread safe as the docs says
Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.
But, what happens with the Predicate generated by asPredicate method?
Matcher
is not thread safe but Pattern
is.
About asPredicate()
you can consider it thread safe as the Pattern
javadoc class itself is defined as safe for use by multiple concurrent threads :
Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.
As underlined by Holger, the Predicate
returned by Pattern.asPredicate()
is not documented as thread safe (nor the reverse) but the implementation of it proves that it is :
public Predicate<String> asPredicate() {
return s -> matcher(s).find();
}
Pattern.asPredicate()
is just another way to do a match between a String
against a pattern similarly to Pattern.matcher(CharSequence).find()
.
This :
boolean isFound = pattern.matcher(myString).find();
can be done in this way :
boolean isFound = pattern.asPredicate().test(myString);
So here the new thing is that you can pass the predicate in a stream or any method that accepts a predicate. Which makes the intention really clearer : not need to manipulate a Pattern
but a Predicate
.
Pattern pattern = ...;
...stream().filter(o-> pattern.matcher(o).find());
can be replaced by :
Predicate<String> predicate = pattern.asPredicate();
List<String> strings = ...;
strings.stream().filter(predicate).(...);
//or
strings.stream().filter(pattern.asPredicate()).(...);