It's my first time working with threads in Java, and I was wondering if I'm synchronizing correctly. I did some quick research on locks, synchronized and volatile, but I'm still not sure where/how to use them. Basically I have a thread that executes some process, and I can cancel it from an outside thread (calling cancelProcess()
). Between each step I check if the process should be canceled.
public final class ExecuteProcess {
private volatile boolean processShouldCancel;
private volatile boolean processKilled;
private final Object processLock = new Object();
private Process process;
public boolean run() {
initialize();
if (processShouldCancel) {
showCanceledMsg();
return false;
}
synchronized (processLock) {
process = new Process();
process.Start();
}
if (processShouldCancel) {
if (!processKilled)
cancelProcess();
showCanceledMsg();
return false;
}
process.waitForResponse();
if (processKilled) {
showCanceledMsg();
return null;
}
if (process.finished()) {
process.getResult();
return true;
}
return false;
}
private void cancelProcess() {
processShouldCancel = true;
synchronized (processLock) {
if (process != null && !processKilled) {
boolean killed = process.kill();
if (killed)
processKilled = true;
}
}
}
}
return null
after waiting for the process which won't compile. This should bereturn false
instead. – David Harkness yesterday