diff --git a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java index 1161822cd1..d980c90f78 100644 --- a/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java +++ b/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java @@ -112,9 +112,9 @@ private enum State { * Listeners that will be called when the {@link AsyncResultSetImpl} has finished fetching all * rows and any underlying transaction or session can be closed. */ - private Collection listeners = new LinkedList<>(); + private final Collection listeners = new LinkedList<>(); - private State state = State.INITIALIZED; + private volatile State state = State.INITIALIZED; /** This variable indicates that produce rows thread is initiated */ private volatile boolean produceRowsInitiated; @@ -498,10 +498,12 @@ public ApiFuture setCallback(Executor exec, ReadyCallback cb) { } private void initiateProduceRows() { - if (this.state == State.STREAMING_INITIALIZED) { - this.state = State.RUNNING; + synchronized (monitor) { + if (this.state == State.STREAMING_INITIALIZED) { + this.state = State.RUNNING; + } + produceRowsInitiated = true; } - produceRowsInitiated = true; this.service.execute(new ProduceRowsRunnable()); }