For the first time I have to play with Threads in java.
Basically, my code is a simple FIFO job queue. The main thread regularly puts jobs in the queue wich need to be executed.
The code below is a striped down version of what I am doing :
public class JobPerformer implements Runnable {
private final ArrayList<Job> jobList = new ArrayList<Job>();
private final AtomicBoolean threadStop = new AtomicBoolean(false);
private Thread thread;
public JobExecuter(){
thread = new Thread(this)
thread.start();
}
public void perform(Job job, bool async){
if(async){
jobList.add(job);
jobList.notifyAll();
}
else{
job.perform();
}
}
public void perform(Job job){
this.perform(job, false);
}
public void shutdown(){
threadStop.set(true);
if(thread.getState() == Thread.State.WAITING){
thread.interrupt();
}
}
public void run(){
while(! threadStop.get()){
if(jobList.isEmpty()){
try{
jobList.wait();
} catch (InterruptedException ex) {}
}
jobList.get(0).perform();
jobList.remove(0);
}
// Finish the jobs still in the queue
while(!jobList.isEmpty()){
jobList.get(0).perform();
jobList.remove(0);
}
}
}
I have two questions :
I use wait() and notifyAll() to avoid polling. But nowhere do I synchronize. Since it's a FIFO queue, threads are just adding jobs at the end or reading at the start. I don't see any conflict that would make me say "Hey, I have to make sure that during this op. only one thread can be working on this object", is there a possible conflict I am overseeing that would require me to synchronize anyway ?
I am using an "Atomic boolean" because of this question : Multithreading correctly done? What was wrong with using a normal boolean ?