Skip to content
This repository was archived by the owner on May 8, 2026. It is now read-only.

Commit f9a7686

Browse files
committed
fix: Fix race in emulator controller
1 parent 2933ef6 commit f9a7686

1 file changed

Lines changed: 24 additions & 3 deletions

File tree

google-cloud-bigtable-emulator-core/src/main/java/com/google/cloud/bigtable/emulator/core/EmulatorController.java

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,12 @@ public class EmulatorController {
4444

4545
private final Path executable;
4646
private Process process;
47+
private Thread stdoutThread;
48+
private Thread stderrThread;
4749
private boolean isStopped = true;
4850
private Thread shutdownHook;
4951

52+
5053
private int port;
5154

5255
public static EmulatorController createFromPath(Path path) {
@@ -127,8 +130,8 @@ public synchronized void start(int port)
127130
throw e;
128131
}
129132
}
130-
pipeStreamToLog(process.getInputStream(), Level.INFO);
131-
pipeStreamToLog(process.getErrorStream(), Level.WARNING);
133+
Thread stdoutThread = pipeStreamToLog(process.getInputStream(), Level.INFO);
134+
Thread stderrThread = pipeStreamToLog(process.getErrorStream(), Level.WARNING);
132135
isStopped = false;
133136

134137
shutdownHook =
@@ -164,6 +167,23 @@ public synchronized void stop() {
164167
} finally {
165168
isStopped = true;
166169
process.destroy();
170+
171+
try {
172+
process.waitFor();
173+
if (stdoutThread != null) {
174+
stdoutThread.join();
175+
}
176+
if (stderrThread != null) {
177+
stderrThread.join();
178+
}
179+
} catch (InterruptedException e) {
180+
Thread.currentThread().interrupt();
181+
LOGGER.log(Level.WARNING, "Interrupted while waiting for emulator to stop", e);
182+
} finally {
183+
stdoutThread = null;
184+
stderrThread = null;
185+
process = null;
186+
}
167187
}
168188
}
169189

@@ -239,7 +259,7 @@ private static void waitForPort(int port) throws InterruptedException, TimeoutEx
239259
}
240260

241261
/** Creates a thread that will pipe an {@link InputStream} to this class' Logger. */
242-
private static void pipeStreamToLog(final InputStream stream, final Level level) {
262+
private static Thread pipeStreamToLog(final InputStream stream, final Level level) {
243263
final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
244264

245265
Thread thread =
@@ -258,6 +278,7 @@ private static void pipeStreamToLog(final InputStream stream, final Level level)
258278
});
259279
thread.setDaemon(true);
260280
thread.start();
281+
return thread;
261282
}
262283
// </editor-fold>
263284
}

0 commit comments

Comments
 (0)