Robert

7%
Flag icon
To improve the performance, explicitly compile the regular expression into a Pattern instance (which is immutable) as part of class initialization, cache it, and reuse the same instance for every invocation of the isRomanNumeral method:
Robert
Beware the other edge of this sword: thread-safety (a likely factor when we're talking about "performance critical situations" that call for caching instances). A frequent example of this in practice is DateFormat, where (similar to this example) you want might instantiate an instance with a format pattern once, and re-use it (call `.format()`) many times. However, DateFormat uses internal state (that is, private instance fields whose values change) while formatting. This means that concurrent calls to `.format()` can mess each other up. In this case, you have a number of options: just take the cost of instantiating new objects each use; keep a thread-local copy; synchronize usage of the object, introduce a pool of instances that can be "checked out" for use... See another related note just below on "When an object is immutable, it is obvious it can be reused safely."
Julie
· Flag
Julie
https://www.joda.org/joda-time/apidoc... claims to be thread-safe and immutable
Robert
· Flag
Robert
That's a nice example that recognizes that the two things are independent ☺.
Effective Java
Rate this book
Clear rating
Open Preview