0

I have written a simple program to find the factorial of the numbers. I am using the join() method of Thread class for better thread coordination ( and to avoid the race condition). I am adding the code below.

public static void main(String[] args) throws InterruptedException {

    List<Long> listOfNumbers = new ArrayList<>(Arrays.asList(100031489L, 4309L, 0L, 199L, 333L, 23L));
    List<FactorialCalculations> threadList = new ArrayList<>();

    for (Long number : listOfNumbers) {
        threadList.add(new FactorialCalculations(number));
    }


    for (Thread thread : threadList) {
        thread.start();
    }

    for (Thread thread : threadList) {
        thread.join(3000);
    }

    // Thread.sleep(1000);
    for (int i = 0; i < listOfNumbers.size(); i++) {
        FactorialCalculations factorialCalculationsThread = threadList.get(i);
        if (factorialCalculationsThread.isStatus()) {
            System.out.println("Factorial of number " + listOfNumbers.get(i) + " : " + factorialCalculationsThread.getResult());
        } else {
            System.out.println("still processing for " + listOfNumbers.get(i));
        }
    }

}

Whenever I am inputting a big value (100031489L), the main thread is printing the outputs of the numbers except for this one, and the program isn't getting terminated. I have used two approaches - Daemon threads thread.setDaemon(true) and thread.interrupt() with Thread.currentThread().isInterrupted() (if true print the results) to terminate the program. Both approaches have worked but I would like to know which is a more appropriate approach to use in my scenario.

Thanks in advance!

Simran Singh
  • 52
  • 1
  • 9

1 Answers1

0

The usual way to terminate a thread is Thread.interrupt(). It may be more complicated, but forces you to understand better the workflow and let's you know what actions are going to be performed.

One reason why it could be better even if it may not be important in your scenario is that if you or someone else is going to reuse your code in a program that exits later and you use Thread.setDaemon(), the threads won't terminate untill the program exits, or may terminate later than you want, while Thread.interrupt() gives you more control. You may find better information on daemon threads and when or why they should be avoided or used in this question.

I don't know much about daemon threads and I am not saying they are bad, but probaby you should know when to you use them and what could be some associated problems and I hope the other question will help you with that.