Search code examples
javastringreplaceall

String replaceall thread unsafe


I know that the Matcher class is thread unsafe.

But is my method also thread unsafe? I think not.. Or please could you explain to me if it is..

private static String doSomething(String rawValue) {
        return rawValue.replaceAll("&","&").replaceAll("#","#")
                       .replaceAll("<","&lt;").replaceAll(">","&gt;")
                       .replaceAll("\\(","&#40;").replaceAll("\\)","&#41;");
    }

Solution

  • Yes, this method is thread-safe; it doesn't modify any shared data.

    It's not safe to use the same Matcher instance in multiple threads, but it's fine to use different matchers in different threads at the same time. Even if the replaceAll method uses a Matcher internally, it'll be a different instance for each call, which means different instances even if it's called by different threads at the same time.