albertfc / csv

MIT License
0 stars 0 forks source link

Thread interrupted vs exception #2

Open pditommaso opened 1 month ago

pditommaso commented 1 month ago

I'm a bit confused by the use of Thread.currentThread().interrupt() followed by an exception throw in the following snippet:

https://github.com/albertfc/csv/blob/dc4f4908744341622c0cb2e4b4272b4589801d63/src/main/java/com/seqera/ParallelDataProcessor.java#L112-L113

Is that really necessary?

albertfc commented 1 month ago

Here I'm restoring the interrupt flag in case the caller is interested on this information. As the Interrupted exception is just rethrown as a SequeraException the fact that the thread was interrupted would be lost.

pditommaso commented 1 month ago

Understand, however, by doing so you will have two exception thrown, the SeqeraException and an InterruptedException in the thread awaiting for the parallel data processor run to complete.

A cleaner implementation could be just break in the while loop and report a log message. See also https://stackoverflow.com/a/52623479/395921

albertfc commented 1 month ago

you will have two exception thrown, the SeqeraException and an InterruptedException

i don't think so, from the [interrupt()](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Thread.html#interrupt()) reference doc:

If this thread is blocked in an invocation of the [wait()](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#wait()), wait(long), or wait(long, int) methods of the Object class, or of the [join()](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Thread.html#join()), join(long), join(long, int), sleep(long), or sleep(long, int) methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException. [...] If none of the previous conditions hold then this thread's interrupt status will be set.

The InterruptedException is only thrown if the first criteria is meet (which is not our case), otherwise calling interrupt()just restores the interrupted status.

A cleaner implementation could be just break in the while loop and report a log message

I agree