Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java Regex Thread Safe?

I have a function that uses Pattern#compile and a Matcher to search a list of strings for a pattern.

This function is used in multiple threads. Each thread will have a unique pattern passed to the Pattern#compile when the thread is created. The number of threads and patterns are dynamic, meaning that I can add more Patterns and threads during configuration.

Do I need to put a synchronize on this function if it uses regex? Is regex in java thread safe?

like image 940
jmq Avatar asked Sep 01 '09 01:09

jmq


People also ask

Is Regex thread-safe Java?

SUMMARY: The Java regular expression API has been designed to allow a single compiled pattern to be shared across multiple match operations. You can safely call Pattern. matcher() on the same pattern from different threads and safely use the matchers concurrently.

Is Regex match thread-safe?

The Regex class itself is thread safe and immutable (read-only). That is, Regex objects can be created on any thread and shared between threads; matching methods can be called from any thread and never alter any global state.

Are Java variables thread-safe?

Using Final keywordFinal Variables are also thread-safe in java because once assigned some reference of an object It cannot point to reference of another object.

Why ++ is not thread-safe in Java?

Example of Non-Thread-Safe Code in Java The above example is not thread-safe because ++ (the increment operator) is not an atomic operation and can be broken down into reading, update, and write operations.


1 Answers

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.

like image 199
Vineet Reynolds Avatar answered Nov 09 '22 16:11

Vineet Reynolds