Search code examples
javaandroidmultithreadingfileblocking

Will a method be blocking if the return value depends on the result of a blocking operation?


I have written the following method in a class that inherits from the Thread class:

protected File createFile(String fileName){
        try {
            File file = new File(fileName);
            if(!file.exists())
                file.createNewFile();
            else{
                file.delete();
                file.createNewFile();
            }
            file.mkdirs();
            return file;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

It will be called from an Activity once the Thread has already started. If I do this from my Activity:

File logFile = mThread.createFile("/Logs/test.txt");
if(logFile!=null)
//do something
else
//do something else

Will it block until the file is created?


Solution

  • Yes it will block.

    What counts is not the class from which the method is called, it is the run() method of the thread from which it is called. There is a high probability that

    File logFile = mThread.createFile("/Logs/test.txt");
    if(logFile!=null)
    //do something
    else
    //do something else
    

    is called from your activity run method (handled by android), and calling directly a method from another thread class will not by magic make this thread run this method.

    To ensure that you are not blocking your activity with this createFile method you should use message passing mechanism so that createFile is called within the run() method of your non-activity thread.

    See examples like the ones in this post for how to pass messages between threads. To sum up your activity thread will set a variable from your other thread. This thread periodically check this variable and execute actions depending on it. That's the main idea but there is a lot to read on the web about this for thread safety and other problems that arise in these cases.