Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have a thread which read and insert new lines in same file. I must synchronized that file so that no other thread is not accessing the file at the same time. Here is how i will synchronize a file record because while other threads write. Which approach to use in this case?

ReentrantLock

Or

producer-consumer pattern

My example code

public class ThreadManager extends Thread {

    public void run() {
        try {
            BufferedReader br = null;
            String line;
            String fileNme = "threadLog.txt";
            ArrayList<String> fileLines = new ArrayList<String>();
            int numLine = 0;

            File outFile = new File("$$$$$$$$.tmp");

            // input
            FileInputStream fis = null;
            PrintWriter out = null;

   //From here is a critical section

                fis = new FileInputStream(fileNme);


            // output
                FileOutputStream fos = new FileOutputStream(outFile);
                out = new PrintWriter(fos);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));

            try {
                while ((line = in.readLine()) != null) {
                    fileLines.add(line);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            if (!fileLines.isEmpty()) {
                int middleLine = (int) Math.round(fileLines.size() / 2);
                fileLines.add(middleLine, Thread.currentThread().getName());

                for (int i = 0; i < fileLines.size(); i++) {
                    out.println(fileLines.get(i));
                }

                out.flush();
                out.close();
                try {
                    in.close();
                    new File(fileNme).delete();
                    outFile.renameTo(new File(fileNme));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

//end critical section
      }
share|improve this question
3  
I suggest you read about synchronization and perhaps thread synchronization questions on StackOverflow –  msw Feb 28 at 15:59
1  
Are you familiar with classes such as SynchronousQueue? –  Snowman Feb 28 at 16:12
    
In most file systems, this should already be taken care of for you. If you open the file exclusively, the OS will block any attempts by another thread or process to open it. –  Robert Harvey Feb 28 at 16:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.