From fc83bf793e8dfb6af091ffb1a1632ad59e09bd44 Mon Sep 17 00:00:00 2001 From: James Ring Date: Fri, 22 Feb 2019 10:08:51 -0800 Subject: [PATCH] Don't create Machine while holding this' monitor. (#85) This change attempts to reduce monitor contention. --- java/com/google/re2j/RE2.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/java/com/google/re2j/RE2.java b/java/com/google/re2j/RE2.java index a5367bae..a20bd4d2 100644 --- a/java/com/google/re2j/RE2.java +++ b/java/com/google/re2j/RE2.java @@ -19,9 +19,11 @@ package com.google.re2j; import java.io.UnsupportedEncodingException; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Queue; /** * An RE2 class instance is a compiled representation of an RE2 regular expression, independent of @@ -112,7 +114,8 @@ class RE2 { // Cache of machines for running regexp. // Accesses must be serialized using |this| monitor. - private final List machine = new ArrayList(); + // @GuardedBy("this") + private final Queue machine = new ArrayDeque(); // This is visible for testing. RE2(String expr) { @@ -204,10 +207,11 @@ int numberOfCapturingGroups() { // get() returns a machine to use for matching |this|. It uses |this|'s // machine cache if possible, to avoid unnecessary allocation. - synchronized Machine get() { - int n = machine.size(); - if (n > 0) { - return machine.remove(n - 1); + Machine get() { + synchronized (this) { + if (!machine.isEmpty()) { + return machine.remove(); + } } return new Machine(this); }