Skip to content

Commit

Permalink
Add object lock to avoid race conditions between reads and resets
Browse files Browse the repository at this point in the history
  • Loading branch information
Bencodes committed Feb 6, 2022
1 parent 4c1c8ef commit 32557fd
Showing 1 changed file with 15 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@
import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.ShellQuotedParamsFilePreProcessor;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.time.Duration;
import java.util.Arrays;
Expand Down Expand Up @@ -140,6 +144,8 @@ void call(String[] args) throws Exception {

private static final Logger logger = Logger.getLogger(ResourceProcessorBusyBox.class.getName());
private static final Properties properties = loadSiteCustomizations();
// Static object locked used when reading/resetting the shared byte buffer
private static final Object LOCK = new Object();

/** Converter for the Tool enum. */
public static final class ToolConverter extends EnumConverter<Tool> {
Expand Down Expand Up @@ -220,11 +226,14 @@ private static int processRequest(List<String> args, PrintWriter pw, ByteArrayOu
e.printStackTrace(pw);
exitCode = 1;
} finally {
// Write the captured buffer to the work response
String captured = buf.toString().trim();
buf.reset();
if (!captured.isEmpty()) {
pw.print(captured);
// Write the captured buffer to the work response. We synchronize to avoid race conditions
// while reading from and calling reset on the shared ByteArrayOutputStream.
synchronized (LOCK) {
String captured = buf.toString().trim();
buf.reset();
if (!captured.isEmpty()) {
pw.print(captured);
}
}
}

Expand Down

0 comments on commit 32557fd

Please sign in to comment.