Does Pattern.compile cache?

I don't believe the results are cached and there's no evidence of such behaviour in the code or the documentation. It would (of course) be relatively trivial to implement such a cache yourself, but I would be interested in a use case in which such caching is beneficial.

Re. the comment below and String.split(), there's a different approach in that the code takes a distinct path for trivial 1 or 2 char patterns vs more complex regexps. But it still doesn't appear to cache.


As far as I know from looking at the code (JDK 6) it doesn't do caching but once constructed, Pattern object could be cached on application side and shared among multiple threads. Standard pattern seems to be to assign it to final static variable:

private static final Pattern p = Pattern.compile(",");

Tags:

Java

Regex