Skip to content

Commit

Permalink
refactor: extract method from a complex thread call method
Browse files Browse the repository at this point in the history
  • Loading branch information
matheusbus committed Nov 27, 2024
1 parent b8e5141 commit be8bac0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
1 change: 0 additions & 1 deletion .idea/.name

This file was deleted.

38 changes: 19 additions & 19 deletions cli/src/main/java/hudson/cli/FlightRecorderInputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,29 @@ public DiagnosedStreamCorruptionException analyzeCrash(Exception problem, String
final ByteArrayOutputStream readAhead = new ByteArrayOutputStream();
final IOException[] error = new IOException[1];

Thread diagnosisThread = new Thread(diagnosisName + " stream corruption diagnosis thread") {
Thread diagnosisThread = createDiagnosisThread(diagnosisName, readAhead, error);

diagnosisThread.start();
try {
diagnosisThread.join(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}

if (diagnosisThread.isAlive()) {
diagnosisThread.interrupt();
}

IOException diagnosisProblem = error[0];
return new DiagnosedStreamCorruptionException(problem, diagnosisProblem, getRecord(), readAhead.toByteArray());
}

private Thread createDiagnosisThread(String diagnosisName, ByteArrayOutputStream readAhead, IOException[] error) {
return new Thread(diagnosisName + " stream corruption diagnosis thread") {
@Override
public void run() {
int b;
try {
// not all InputStream will look for the thread interrupt flag, so check that explicitly to be defensive
while (!Thread.interrupted() && (b = source.read()) != -1) {
readAhead.write(b);
}
Expand All @@ -66,23 +83,6 @@ public void run() {
}
}
};

// wait up to 1 sec to grab as much data as possible
diagnosisThread.start();
try {
diagnosisThread.join(1000);
} catch (InterruptedException ignored) {
// we are only waiting for a fixed amount of time, so we'll pretend like we were in a busy loop
Thread.currentThread().interrupt();
// fall through
}

IOException diagnosisProblem = error[0]; // capture the error, if any, before we kill the thread
if (diagnosisThread.isAlive())
diagnosisThread.interrupt(); // if it's not dead, kill

return new DiagnosedStreamCorruptionException(problem, diagnosisProblem, getRecord(), readAhead.toByteArray());

}

@Override
Expand Down

0 comments on commit be8bac0

Please sign in to comment.