Is Java Regex Thread Safe

Is Java Regex Thread Safe?

Yes, from the Java API documentation for the Pattern class

Instances of this (Pattern) class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.

If you are looking at performance centric code, attempt to reset the Matcher instance using the reset() method, instead of creating new instances. This would reset the state of the Matcher instance, making it usable for the next regex operation. In fact, it is the state maintained in the Matcher instance that is responsible for it to be unsafe for concurrent access.

Is Pattern::asPredicate thread safe

Matcher is not thread safe but Pattern is.

About asPredicate() you can consider it thread safe as the Pattern javadoc class itself is defined as safe for use by multiple concurrent threads :

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.

As underlined by Holger, the Predicate returned by Pattern.asPredicate() is not documented as thread safe (nor the reverse) but the implementation of it proves that it is :

public Predicate<String> asPredicate() {
return s -> matcher(s).find();
}

Pattern.asPredicate() is just another way to do a match between a String against a pattern similarly to Pattern.matcher(CharSequence).find().

This :

boolean isFound = pattern.matcher(myString).find(); 

can be done in this way :

boolean isFound = pattern.asPredicate().test(myString); 

So here the new thing is that you can pass the predicate in a stream or any method that accepts a predicate. Which makes the intention really clearer : not need to manipulate a Pattern but a Predicate.

Pattern pattern = ...;
...stream().filter(o-> pattern.matcher(o).find());

can be replaced by :

Predicate<String> predicate = pattern.asPredicate();
List<String> strings = ...;
strings.stream().filter(predicate).(...);
//or
strings.stream().filter(pattern.asPredicate()).(...);

Kotlin Regex thread-safety

The documentation for Regex points you to java.util.regex.Pattern for the JVM.  So it will inherit Pattern's concurrency behaviour.

(Note that checking the current implementation isn't enough; JetBrains can and do change their implementations.  But if it's specified in the docs, then it's part of the public API and should be fairly reliable.)

The corresponding docs for JavaScript point here, which doesn't mention anything about thread-safety.  And that for Native doesn't even have a link.  So it's probably not safe to assume anything about them.

Is scalas pattern matching regex thread safe?

There are more than one class. It breaks down to:

  • scala.util.matching.Regex
    depends on java.util.regex.Pattern, so, according to JavaDoc, thread-safe.
  • scala.util.matching.Regex.Match
    depends on java.util.regex.Match, so, according to JavaDoc, not thread-safe.
  • scala.util.matching.Regex.MatchIterator
    is mutable, and contains java.util.regex.Match, so not thread-safe.
  • scala.util.matching.Regex.MatchData
    is technically thread-safe, but it only appears as part of the two classes above, so you won't find thread-safe instances of MatchData.

Is System.RegularExpressions.TRegEx thread-safe?

The PCRE library on which Delphi's regex class is built is threadsafe. See PCRE pcre_exec thread safe?

However, the Delphi wrapper TRegex is not threadsafe. Consider the calls made to pcre_exec in TPerlRegEx.Match:

OffsetCount := pcre_exec(FPattern, FHints, @FSubject[0], FStop, 0, Opts, @Offsets[0],
High(Offsets));

Here FSubject and Offsets are members of TPerlRegEx and so will be shared between different threads using this instance of TPerlRegEx, which in turn is owned by the instance of TRegEx.

For TRegEx to be threadsafe in the sense that you desire (multiple threads performing matches on a shared compiled regex) these variables would need to be private to each invocation of a match function.

Is JAVA StringJoiner Thread-Safe?

Unlike StringBuffer methods (like append()) which are synchronized, methods of StringJoiner (like add()) are not synchronized. Thus it is not thread-safe.

Source code from OpenJDK:

  • StringJoiner
  • StringBuffer

Is java regex matcher stateful?

  1. Yes Matcher is stateful.

  2. If anything1 calls find or match while you are (still) looking at the groups (etc) from the previous call, then you will lose the state from the previous call. The same applies for reset and reset(CharSequence), and some other methods. This behavior is inherent in the API design, and clearly documented.

  3. Matcher is not thread-safe. The javadoc states this explicitly:

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

  4. However, using it like your code does should work ... provided that the Matcher was only visible to / used by the current thread, and not used further up (or down) the call stack.

See also:

  • Java Pattern Matcher: create new or reset? ... though the accepted answer is missing the "recursion" caveat.

By contrast, Pattern is both thread-safe and immutable / stateless.


1 - That could be another thread, or the current thread that is using the same Matcher at different points in the call stack; i.e. via recursion or something like that.

Is this code correct example of thread safe Singleton design pattern?

This is guaranteed to be safe by the JLS. See the holder pattern: "since the class initialization phase is guaranteed by the JLS to be sequential, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization."

The holder pattern is more complex than what you want, but the important part is that static final Something INSTANCE = new Something() is safe no matter which class it is declared in. The benefit of the holder pattern compared to what you have is that the singleton won't be initialized until the first time it is used. This is helpful if you want to access other static members in your Singleton class when the cost of initializing the Singleton instance is expensive.

As Lewis_McReu and user6690200 pointed out, you should declare the INSTANCE field final in order to ensure that you don't accidentally assign a different Singleton instance to the variable. You should also declare a private no-argument Singleton() constructor to prevent other instances from being created. To make it even more bulletproof, you should declare the Singleton class final so that you can't subclass it with a public constructor.



Related Topics



Leave a reply



Submit