tags:

views:

95

answers:

2

Is there a way to cancel a long running file open operation? Long delays due anti-virus scans, mapped network drives etc.

new FileInputStream("a_file_that_the_antivirus_" + 
    "will_process_for_minutes_before_returning.jar")
// process the contents...

In the above example, the first line can block, but I don't know any way to asynchronously cancel that operation (if we got the new inputstream object, cancellation is as easy as in.close(), but this question is not about that case).

Is it possible interrupt the open process - perhaps with NIO - or is there already a mechanism such as a simple Thread.interrupt() to cancel the open?

OS: mostly Windows XP+, Java 6+, the blocking is typically due some larger and deeper jar files - for example, Eclipse's plugins or my own complex apps.

A: 

fileinputstream is blocking. You might want to take a look at Asynchronous File I/O in Java or java nio

Niko
Ah, the Mina framework again. I guess I have to take a more closer look at it :) However, it states Linux only and suffers the same file-open trouble - that is not asynchronous at all. I'll double check the NIO for the file/channel open. Thanks.
kd304
+1  A: 

Suppose that there were no solution (I can't find one, and I suspect that we're stuck in OS-level calls) how bad would it be to actually do the open attempt in a worker thread, and eventually timeout waiting for that Thread. You main processing could then continue, while in the backgrounbd that worker thread would eventually complet its open, but immediately close the file again - no one is waiting for it any more.

Yes, it's going to tie up FD resources, but presumably not large numbers - and anyway you could throttle the number of worker threads to control the impact.

djna
Basically the entire file processing is done in a SwingWorker already, so that's not a problem. The problem is that when the user wants to cancel the operation, I cannot reliably cancel the open - It will keep the thread blocked and the JVM cannot exit gracefully for example.
kd304
I think the idea is to do the open in another thread and use wait/notify to detect when it's done. The wait can easily be canceled. The actual open call keeps running in the other thread and then is thrown away when it eventually completes.
Dave Ray
Thats true, but 'eventually' is too late usually.
kd304