0

Question : When invokeAny() is called with some tasks, On successful returning of one of the tasks, will the other task execution be "STOPPED" or Is the thread interruption is just called and the task execution continues to happen unless we manually check for the thread ?? According to the documentation :

Upon normal or exceptional return, tasks that have not completed are cancelled.

Background : I have an implementation where I need to run few tasks parallely and wait for the acknowledgement of one success task completion but let the other tasks run and complete their job. For the POC, I found InvokeAny() could help me and just wrote the following code to test it out :


public class PasswordHacker implements Callable {
    private static final Logger logger = LoggerFactory.getLogger(PasswordHacker.class);
    int password ;
    int digits;

    PasswordHacker(int password, int digits){
        this.password = password;
        this.digits = digits;
    }
    @Override
    public Object call() throws Exception {
        String hackerName = Thread.currentThread().getName();
        logger.info( hackerName +  " is starting to hack ");
        try{
            while(true){
                Integer guess = new Random().nextInt((int) Math.pow(10, digits));
                if(guess.equals(password)) {
                    logger.info(hackerName + " completed the hack ");
                    return hackerName + " Successfully ";
                }
            }
        }catch (Exception e){
            throw new InterruptedException();
        }
//        return hackerName + " Failed ";
    }
}

and then added them as callableTasks

        List<Callable<String>> callableHackerTasks = new ArrayList<>();
        for( int i = 1 ; i<= hackers; i++){
            callableHackerTasks.add(new PasswordHacker(password, digits));
        }

        try {
            String result = executorService.invokeAny(callableHackerTasks, 2, TimeUnit.MINUTES);
            logger.info( "Hacker "  +  result + " completed the hack");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

And the result is as follows, when I run 3 threads :

pool-1-thread-2 is starting to hack 
pool-1-thread-3 is starting to hack 
pool-1-thread-1 is starting to hack 
pool-1-thread-1 completed the hack 
Hacker pool-1-thread-1 Successfully  completed the hack
pool-1-thread-2 completed the hack 
pool-1-thread-3 completed the hack 

Thought this approach seems to satisfy my need, I want to know what exactly is the documentation referring to. Clearly, even though the documentation says that other threads are cancelled, they continue to run. According to the answer here ; We need to manually check in the while condition if the threat is interrupted and then stop the logic. But in real case scenarios what actually happens ?? Should we manually check for that or some Exception be thrown (Bcz in above code, the catch block isn't catching Interuption Exc ). Would appreciate a bit more clarity on this part or suggest any other useful methods to achieve the same.

Suhas
  • 55
  • 9
  • 1
    As an aside, it looks like `PasswordHacker` should implement `Callable`, not the raw type `Callable`. [Don't use raw types](https://stackoverflow.com/q/2770321/6395627). – Slaw Jan 29 '23 at 08:48

0 Answers0