package org.eclipse.core.internal.jobs;
import org.eclipse.core.internal.runtime.RuntimeLog;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.util.NLS;
public class Worker extends Thread {
private static int nextWorkerNumber = 0;
private volatile InternalJob currentJob;
private final WorkerPool pool;
private final String generalName;
public Worker(WorkerPool pool) {
super("Worker-" + nextWorkerNumber++);
this.generalName = getName();
this.pool = pool;
setContextClassLoader(pool.defaultContextLoader);
}
public Job currentJob() {
return (Job) currentJob;
}
private IStatus handleException(InternalJob job, Throwable t) {
String message = NLS.bind(JobMessages.jobs_internalError, job.getName());
return new Status(IStatus.ERROR, JobManager.PI_JOBS, JobManager.PLUGIN_ERROR, message, t);
}
@Override
public void run() {
setPriority(Thread.NORM_PRIORITY);
try {
while ((currentJob = pool.startJob(this)) != null) {
IStatus result = Status.OK_STATUS;
IProgressMonitor monitor = currentJob.getProgressMonitor();
try {
setName(getJobName());
result = currentJob.run(monitor);
} catch (OperationCanceledException e) {
result = Status.CANCEL_STATUS;
} catch (ThreadDeath e) {
result = handleException(currentJob, e);
throw e;
} catch (Exception | Error e) {
result = handleException(currentJob, e);
} finally {
if (result != Job.ASYNC_FINISH && monitor != null) {
monitor.done();
}
Thread.interrupted();
if (result == null) {
String message = NLS.bind(JobMessages.jobs_returnNoStatus, currentJob.getClass().getName());
result = handleException(currentJob, new NullPointerException(message));
}
pool.endJob(currentJob, result);
currentJob = null;
setName(generalName);
setPriority(Thread.NORM_PRIORITY);
}
}
} catch (Throwable t) {
RuntimeLog.log(new Status(IStatus.ERROR, JobManager.PI_JOBS, JobManager.PLUGIN_ERROR, "Unhandled error", t));
} finally {
currentJob = null;
pool.endWorker(this);
}
}
private String getJobName() {
String name = currentJob.getName();
if (name == null || name.trim().isEmpty()) {
name = "<unnamed job: " + currentJob.getClass().getName() + ">";
}
return generalName + ": " + name;
}
}