How do I make the thread wait until the file is created?

I need a thread to wait until the file is created or created. So far, I have the following code:

while(!receivedDataFile.isFileExists("receiveddata.txt"))
{
    try {
        Thead.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        return null;
    }
}

      

When I run it, the following exception appears and the end of the stream:

java.lang.InterruptedException: sleep interrupted

      

+1


source to share


5 answers


A thread is interrupted when it blocks (call to sleep) and another thread calls its method interrupt

. The call interrupt

must be explicitly specified for this.

It seems that re-checking the file would be a logical task if the thread was interrupted, but without knowing the reason for the interruption, which is difficult to tell.



As usual when it comes to streaming, Brian Goetz has something to say about the question InterruptedException

:

http://www-128.ibm.com/developerworks/java/library/j-jtp05236.html

+4


source


I have to agree with Bombes' comment: threads don't interrupt on their own. Contrary to Jokis' comment - they are not interrupted when a thread is swapped (in fact, if a thread sleeps, it will pass a quantum to any thread that should be running, but I'm digressing).

Also, I would suggest alternative means of communication besides polling for files. You cannot be sure, for example, that after you noticed a file, it was completely written without additional work from the file author (for example, renaming it when ready or creating a "finished" file).



Consider using something more "push data" like RMI, HTTP-POST, JMS queues, etc.

+3


source


You have to figure out which thread is interrupting this thread. Themes don't do it themselves.

+2


source


If all you need is a notification when the file is created, and you can (and wish to) switch to native (JNI). And you only want win32 support, you can use the code here .

0


source


Ok, if you don't know what InterruptedException is and / or don't want to do anything, obviously you should at least do something other than returning and exiting the loop. Pull it back out and then you will wait.

But I would clarify why you are interrupting. Something is trying to cancel your thread.

0


source







All Articles