The Best-practice threading policy in Java is now to use the ExecutorService implementations found in the java.util.concurrent
package.
Before we go there, though, your current code should be improved. The method:
public static void stringAnalysis(ArrayList<String> strData) {
Thread t;
t = new Thread(new SentimentAnalysis(strData));
t.start();
}
creates and starts a thread. The thread that is started is a regular thread, as opposed to a daemon thread. The JVM will exit when all threads complete, or all the remaining threads are Daemon (background) threads: see Thread.setDaemon(boolean)
.
You should typically use Daemon threads (and I believe that Java has a bug in that Daemon threads should be the default).
Additionally, there is no reason to 'Declare' the t
Thread variable before assigning to it.
Finally, for many reasons, it is nice to give threads names.
I would have the code:
public static void stringAnalysis(ArrayList<String> strData) {
Thread toRun = new Thread(new SentimentAnalysis(strData), "Sentiment Analysis thread");
toRun.setDaemon(true);
toRun.start();
}
But, in reality, I would use an Executor service....
Executors.
Executor services work best with Daemon threads too. Here's a method that creates a Daemon thread for an Executor service:
private static final AtomicInteger sentimentThreadID = new AtomicInteger();
public static Thread createSentimentThread(Runnable toRun) {
String name = "Sentiment Thread " + sentimentThreadID.incrementAndGet();
Thread myThread = new Thread(toRun, name);
myThread.setDaemon(true);
return myThread();
}
Executors have their own Runnable that they use to create the thread. When you have your runnable, you pass it to the Executor, and the Executor runs it on one of the Executor's threads.
So, you can create an ExecutorService with something like (using Java 8):
ExecutorService sentimentService = Executors.newCachedThreadPool(
runnable -> createSentimentThread(runnable)
);
Java 7 would be slightly longer with:
ThreadFactory factory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return createSentimentThread(r);
}
};
ExecutorService sentimentService = Executors.newCachedThreadPool(factory);
Once you have the sentimentService
, you can run your analysis Runnables with:
sentimentService.submit(new SentimentAnalysis(strData));