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 Pattern
s and threads during configuration.
Do I need to put a synchronize
on this function if it uses regex? Is regex in java thread safe?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With