Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7071885
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:44:30+00:00 2026-05-28T05:44:30+00:00

I have a utility method (= a static one) that I call a lot,

  • 0

I have a utility method (= a static one) that I call a lot, which uses a java.util.regex.Matcher. As the regex passed is reused a lot, I try not to compile it every time, so I keep it in a Map where the key is the regex, and the value is a List of Matcher objects (so that each thread gets it own Matcher instance).

How is it that the following code snippet manages to return the same Matcher twice… sometimes?

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyTest {

    private static final Map<String, Queue<Matcher>> matchers = new HashMap<String, Queue<Matcher>>();
    private static Set<Integer> duplicateHunter = new HashSet<Integer>();

    private static Matcher getMatcher(String regexp, String value) {
        Queue<Matcher> matcherQueue = matchers.get(regexp);

        if (matcherQueue == null) {
            synchronized (matchers) {
                matcherQueue = matchers.get(regexp);

                if (matcherQueue == null) {
                    // Create a new thread-safe Queue and a new Matcher
                    matcherQueue = new ConcurrentLinkedQueue<Matcher>();
                    matchers.put(regexp, matcherQueue);
                } // Else: another thread already did what needed to be done
            }
        }

        // Try to retrieve a Matcher
        Matcher matcher = matcherQueue.poll();

        if (matcher == null) {
            // No matchers available, create one
            // No lock needed, as it's not a drama to have a few more matchers in the queue
            Pattern pattern = Pattern.compile(regexp);
            matcher = pattern.matcher(value);
            matcherQueue.offer(matcher);
        } else {
            // reset the matcher
            matcher.reset(value);
        }

//        boolean notADuplicate = duplicateHunter.add(matcher.hashCode());
//        if(!notADuplicate) {
//            throw new RuntimeException("DUPLICATE!!!");
//        }

        return matcher;
    }

    private static void returnMatcher(String regex, Matcher matcher) {
        Queue<Matcher> matcherQueue = matchers.get(regex);
        //duplicateHunter.remove(matcher.hashCode());
        matcherQueue.offer(matcher);
    }

    public static void main(String[] args) {

        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(new Runnable() {

                public void run() {
                    for (int i = 0; i < 50000; i++) {
                        String regex = ".*";
                        Matcher matcher = null;
                        try {
                            matcher = getMatcher(regex, "toto" + i);
                            if (matcher.matches()) {
                                // matches
                            }
                        } finally {
                            if (matcher != null) {
                                returnMatcher(regex, matcher);
                            }
                        }
                    }


                }
            });

            thread.start();
        }

    }
}

You’ll get a “java.lang.StringIndexOutOfBoundsException: String index out of range”. Enable the duplicateHunter code and you’ll see that a Matcher is indeed returned twice sometimes.

(The static utility method isn’t shown, the main method was made to show you the problem)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T05:44:31+00:00Added an answer on May 28, 2026 at 5:44 am

    When there are no matchers for a regexp, you create a new matcher, but you also add it to the queue right away:

    if (matcher == null) {
        // No matchers available, create one
        // No lock needed, as it's not a drama to have a few more matchers in the queue
        Pattern pattern = Pattern.compile(regexp);
        matcher = pattern.matcher(value);
        matcherQueue.offer(matcher); // Don't add it to the queue here!
    }
    

    Thus it will be in the queue while you are using it, and another thread could easily get a hold of it before you are done.

    I don’t know if I agree with your idea of pooling matchers by the way. They are not very expensive to create in terms of CPU cycles. You probably want to profile it to see if it’s worth it. Precompiling the Pattern is a good idea, however.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a utility method that uses Display Templates to generate HTML: public static
We have a static method in a utility class that will download a file
I have a static utility class, FileUtils which has the following method: public static
I have a following static method in one of my utility class + (UIImage
I have a utility that I put together that uses the .NET Framework to
In my application I have written my own Logging utility using Java.Util.Logging import java.io.IOException;
I have a Junit4 test case which statically imports the org.junit.Assert.assertEquals method(s). import static
I have a utility class with some static methods which I use in some
I have a small utility extension method that performs some null checks on some
I have a set of methods that do some utility work over SQL connection,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.