I am 100% sure that Thread.sleep(3000);
should throw InterruptedException
either if the thread's interrupted status was set to true
before or during the sleep call. See Calling Thread.sleep() with interrupted status set?
But I never get an exception when I interrupted the thread beforehand, only during the 3 seconds of sleep. How can this be?
Here is the concept of my code:
public class MyView extends CustomComponent implements View {
private Thread importThread;
private Collection<File> allUploadFiles = new HashSet<>();
public MyView(){
allUploadFiles.add(new File("/foo/bar.xlsx"));
allUploadFiles.add(new File("/foo/bar.xlsx"));
allUploadFiles.add(new File("/foo/bar.xlsx"));
allUploadFiles.add(new File("/foo/bar.xlsx"));
createMainLayout();
}
private void createMainLayout(){
// Builds the layout here, including the upload button:
MultiFileUpload upload = new MultiFileUpload(uploadFinishedHandler, uploadStateWindow, true);
upload.setAllUploadFinishedHandler(this::allUploadFinishedHandler);
}
private void allUploadFinishedHandler(){
final UI ui = UI.getCurrent();
final VaadinSession session = VaadinSession.getCurrent();
importThread = new Thread(() -> {
UI.setCurrent(ui);
VaadinSession.setCurrent(session);
for (File uploadFile : allUploadFiles){
try {
// system output to see when the thread sleeps
System.out.print("start sleep");
Thread.sleep(3000);
System.out.print("end sleep");
MyImporter.import(uploadFile); // takes about a minute
} catch (InterruptedException e){
Thread.currentThread.interrupt(); // keep the interrupted status
System.out.print("InterruptedException thrown!");
break;
}
}
allUploadFiles.clear();
});
importThread.start();
}
/**
* this is the clickListener of the interruptImport Btn which I left out in this codesample
*/
public void interruptImport(){
importThread.interrupt();
}
}
Whenever I interrupt the importThread
between the system-output of "start sleep" and "end sleep", an InterruptedException
is thrown and everything works fine.
But when I interrupt it anytime else, nothing happens, the thread keeps importing file after file. The Thread.sleep(3000);
lets it wait for 3 seconds but there is no exception being thrown.
I don't know what I'm doing wrong and could really need some help!
Edit: I replaced the import method with a keep-me-busy method as suggested by k5_, The problem remained.
I then added this codeblock just within the uploadFile-forloop and it worked (Edit 2: not consistently. I can't yet see why)
if(Thread.interrupted()){
Thread.currentThread().interrupt();
System.out.print("interrupted status detected manually");
break;
}
but if I use Thread.currentThread().isInterrupted() in the if-condition it doesn't work.
Why does Thread.interrupted() work but not Thread.currentThread().isInterrupted() or even Thread.sleep(3000)