maythesource.com maythesource.com - 1 month ago 16
Java Question

Compiling Pattern as Public Static Final in Multi-Threaded Environment

Is it ok to compile my regex

pattern
as
static final
if I am planning to use it in a
multi-threaded
environment such as a servlet?

Will any issues arise? My gut feeling is that it is more optimized/better to compile once, and than use a different
matcher
for each request.

Example:

private static final Pattern patternEmail = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+");


Then in the method called from
request-doGet()
, e.g.:

Matcher matcher = patternEmail.matcher(urlString);
String eMaill;
while (matcher.find()) {

Answer

Your gut feeling is right :)

Pattern

From the JavaDocs

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.

Matcher

From the JavaDocs

Instances of this class are not safe for use by multiple concurrent threads.