Perl5Matcher re-entrant?

R

Robert Mark Bram

Hi All,

I have the following code:

private static final Perl5Matcher MATCHER = new Perl5Matcher();

private static boolean validateRegex(
final String field,
final Pattern regex) {

boolean matches = false;
synchronized (MATCHER) {
matches = MATCHER.matches(field, regex);
}
return matches;
}

My question: I do have many threads accessing this code at about the
same time. Is it worthwhile synchronizing on the matches call? I can't
see anything in the docs to say either way, but I am a bit paranoid
since matches isn't a static call..

Rob
:)
 
T

Thomas Hawtin

Robert said:
private static final Perl5Matcher MATCHER = new Perl5Matcher();

private static boolean validateRegex(
final String field,
final Pattern regex) {

boolean matches = false;
synchronized (MATCHER) {
matches = MATCHER.matches(field, regex);
}
return matches;
}

My question: I do have many threads accessing this code at about the
same time. Is it worthwhile synchronizing on the matches call? I can't
see anything in the docs to say either way, but I am a bit paranoid
since matches isn't a static call..

Looks fine to me. I don't know what Pel5Matcher is.
java.util.regex.Matcher is not thread-safe, so requires the synchronized
block.

You can write the method body more simple as:

synchronized (MATCHER) {
return MATCHER.matches(field, regex);
}

If it is a frequently used method on a multiprocessor machine (even
desktops have multiple hardware threads these days), it may be worth
having a separate matcher for each thread:

private static final ThreadLocal<Perl5Matcher> MATCHER =
new ThreadLocal<Perl5Matcher>() {
@Override
protected Perl5Matcher initialValue() {
return new Perl5Matcher();
}
};

private static boolean validateRegex(
final String field, final Pattern regex
) {
return MATCHER.get().matches(field, regex);
}

(Usual warning that you wont get class unloading with this sort of use
of ThreadLocal: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6254531)

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top