简体   繁体   中英

file thread synchronization

How to perform read and write operation by using thread synchronization.

Condition: If one file exists where writers may write information to, only one writer may write at a time. Confusion may arise if a reader is trying read at the same as a writer is writing. Since readers only look at the data, but do not modify the data, we can allow more than one reader to read at the same time.

//reader thread
    class Read extends Thread {
        static File Reader fr1 = null;
        static Buffered Reader br1 = null;

        static synchronized void reader() throws IO Exception {

            String path ="C:/Users/teja/Documents/file1.txt";

            fr1 = new File Reader(path);
            br1 = new Buffered Reader(fr);
            int i;
            while ((i = br. read()) != -1)
                System .out. print((char) i);
            System .out. print ln();
        }

        public void run() {
            try {
                reader();
            } catch (IO Exception e) {
                e. print Stack Trace();
            }
        }
    }
    //writer code
    class Writer extends Thread {
        static Buffered Writer bw1 = null;
        static File Writer fw1 = null;

        static synchronized void writer() throws IO Exception {
            Scanner scanner = new Scanner(System.in);
            System .out .print ln("enter data to be added:");
            String data = scanner. nextLine();

            String path = "C:/Users/vt/Documents/file1.txt";
            fw1 = new File Writer(path, true);

            bw1 = new Buffered Writer(fw1);
            bw1.newLine();
            bw1.write(data);
            bw1.flush();

            scanner. close();
            System. out . println("data added");
        }

        public void run() {
            try {
                writer();
            } catch (IO Exception e) {
                e. print Stack Trace();
            }
        }
    }
    //main method
    public class File Read Write {

        public static void main(String[] args) {
           Read rd1 =new Read();
           Read rd2=new Read();
           Writer wt1=new Writer();

           rd1.run();
           rd2.run();
           wt1.run();
           rd1. run();
            }           
    }

I am new to files and threading in java. I know this is not correct approach. Guide me.

If one file exists where writers may write information to, only one writer may write at a time. Confusion may arise if a reader is trying read at the same as a writer is writing. Since readers only look at the data, but do not modify the data, we can allow more than one reader to read at the same time.

There are two approaches to this.

(1) Either lock the resource and have the readers wait until the writer has completed the writing operation (or likewise, have a writer waits until all readers are done). This approach guarantees consistency, but can be slow if a lot of writers/readers are working on the resource at the same time (see Lock in java.util.concurrent.locks package).

(2) Keep an in-memory-version of the contents of the file that is served to readers only. When a change is made, this in-memory version is updated. Here, you'll have more speed, but you lose consistency and you'll need more memory.

The condition you want to avoid is generally referred as race condition and what you want to avoid it is a synchronization method between threads. There are more choices available but the most suitable for your case are mutex and read-write lock .

A mutex basically just lock the resource before any operation on the shared resource is performed, independently from the type of operation and free it after the operation is terminated. So a read will block the resource and any other operation, read or write will be blocked. A write will block the resource too so again no other read or write operation can be performed before the action is terminated and mutex unlocked. So basically a mutex has 2 states: locked and unlocked.

read-write lock gives you more freedom based on the fact that read only operations do not result in inconsistencies. A read-write lock has 3 states: unlocked, read lock, write lock. A write lock works as a regular mutex blocking any other operation. A read lock on the contrary blocks only write operations.

I am not a Java expert but from this answer mutex in Java can be used as the following:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

private final Lock lock = new ReentrantLock(true);
lock.lock()
/*open file and do stuff*/
try {
  // do something
} catch (Exception e) {
  // handle the exception
} finally {
  lock.unlock();
}

Instead here you can find a description of a read-write lock class.

From the implementation point of view you can create an instance of one of the two synchronization method and have your read/write thread instances keeping a reference to it, as an instance variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM