Search code examples
javamultithreadingsynchronizationreentrantlock

Running Threads on a File Method


Hi am try to run a thread on my "threadedSort", but i can not use the traditional void run method because it returns void. I also tried using the synchronised method but i don't think it made any difference...same with the reentrant method, i don't know what i'm doing wrong.

 private static String[] getDatathread(File file) throws IOException {

        ArrayList<String> data = new ArrayList<String>();
        BufferedReader in = new BufferedReader(new FileReader(file));
        // Read the data from the file until the end of file is reached
        while (true) {

            String line = in.readLine();
                if (line == null) {
                    // the end of file was reached

                    break;
                } else {
                    //synchronized(line){
                    lock.lock();
                    try{
                     data.add(line);   
                    }finally{
                      lock.unlock();
                    }

                    //}
                }

        }

        //Close the input stream and return the data
        in.close();
        return data.toArray(new String[0]);

    }
}


public static String[] threadedSort(File[] files) throws IOException, InterruptedException {
        String[] sortedData = new String[0];

        for (File file : files) {
            String[] data = getDatathread(file);
            Thread.sleep(100);
            data = MergeSort.mergeSort(data);
            sortedData = MergeSort.merge(sortedData, data);
        }

        return sortedData;
    }

Solution

  • I am not sure why you have use synchronized blocks or renentrant locks for that matter in your code. It seems that you have used the locks on blocks where no resource used in the block is shared in any way.
    If you want to run you method threadedSort in parallel and get the resulting data object you can simply specify the data to be returned as class variable and fetch the object later on.