Zame
Zame

Reputation: 320

Synchronisation JAVA - File lock

I have the following code , it is a part of a multi thread server code :

 File ff=new File("../key.txt");
       if(ff.exists())
         {
            try(
              BufferedReader br = new BufferedReader(new FileReader("..\key.txt"))) {



                for(String line2; (line2 = br.readLine()) != null; ) {


                    System.out.println("WE ARE READING 'KEY' ");
                    String a[]=line2.split("-");
                    k[i2]=a[0];
                    od[i2]=a[1];
                    ed[i2]=a[2];
                    System.out.println("key: "+k[i2]+" OD: "+od[i2]+" ED: "+ed[i2]);
                                                                      }
                                                                                }
         }

i've read about "synchronisation" in java but i didn't guess how to integrate it in my code, i want to lock the file "key" whenever a user is using it so another user at the same time cannot access it if someone else is already using it (for security reasons), any ideas ?

Upvotes: 0

Views: 188

Answers (1)

aalku
aalku

Reputation: 2878

If the file is not used in other place but this code you may just synchronize the block:

synchronized {
   File ff=new File("../key.txt");
   if(ff.exists()) {
        BufferedReader br = new BufferedReader(new FileReader(ff))) {
        try(
           // YOUR STUFF WITH br HERE
        } finally {
           br.close();
        }

     }
 }

If the file is shared between several parts of the code you may want to use a constant monitor to synchronize against it (synchronized (MY_MONITOR_OBJECT) {...}) or use a lock (doc here).

Upvotes: 1

Related Questions