Skip to content

Commit

Permalink
Don't create Machine while holding this' monitor. (#85)
Browse files Browse the repository at this point in the history
This change attempts to reduce monitor contention.
  • Loading branch information
sjamesr authored Feb 22, 2019
1 parent 3bbd13b commit fc83bf7
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions java/com/google/re2j/RE2.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -112,7 +114,8 @@ class RE2 {

// Cache of machines for running regexp.
// Accesses must be serialized using |this| monitor.
private final List<Machine> machine = new ArrayList<Machine>();
// @GuardedBy("this")
private final Queue<Machine> machine = new ArrayDeque<Machine>();

// This is visible for testing.
RE2(String expr) {
Expand Down Expand Up @@ -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);
}
Expand Down

0 comments on commit fc83bf7

Please sign in to comment.