Many time-consuming threads (500-900ms.) are created in the application.
They are to be executed in the order they have been created – one after another – not simultaneously. The execution should be processed in thread, that is not synchronized with main application thread.
I can’t make small threads executed in an order, so I found a ThreadPoolExecutor, but think it’s too heavy for my task. So I wrote my Executor class.
It works fine. You add a thread to the threadList and it start the Executor thread to execute small tasks, that can be added while execution.
Can you tell me it’s drawbacks and maybe another better way to solve my problem.
import java.util.LinkedList;
import java.util.List;
public class SfourExecutor extends Thread implements Runnable {
private static List <Thread> threadList = new LinkedList<Thread>();
private static final SfourExecutor INSTANCE = new SfourExecutor();
public static List<Thread> getThreadList() {
return threadList;
}
public static void setThreadList(List<Thread> threadList) {
SfourExecutor.threadList = threadList;
}
public void addToThreadList(Thread thread) {
getThreadList().add(thread);
if (!this.isAlive()) {
this.start();
}
}
public static SfourExecutor getInstance() {
return SfourExecutor.INSTANCE;
}
private static class SfourHolder {
private static final SfourExecutor INSTANCE = new SfourExecutor();
}
SfourExecutor () {
}
@Override
public void run() {
LinkedList <Thread> tL = (LinkedList<Thread>) getThreadList();
while (!tL.isEmpty()) {
Thread t = tL.poll();
if (t!=null) {
t.start();
try {
t.join();
} catch (InterruptedException ex) {
}
}
}
}
}
Won’t an
Executorcreated via Executors.newSingleThreadExecutor() meet your requirements exactly? “Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.”Don’t create new
Threadinstances when you don’t need to execute jobs concurrently. Even if you are working with legacy code that has implemented some logic in aThreadclass, you should be able to execute them asRunnableinstances to the executor.If you insist on using your own executor, you should know that your current implementation is not thread-safe.
LinkedListis not a concurrent data structure, and since any code in the process can add new jobs at any time, you have no way to ensure that all jobs are added to the list before your executor thread is started. Thus, changes to the list are not guaranteed to be visible to all of the threads that are working with it.