Используется ли ReadWriteLock для предотвращения исключения?Который из? - PullRequest
0 голосов
/ 18 мая 2018

Я одновременно читаю / записываю в один файл из нескольких потоков без синхронизации Reader и Writer .И все же никаких исключений не выдается.

Используется ли ReadWriteLock для предотвращения исключений?

public class Main {
    public static void main(String[] args) {
        int nmbOfThreads = 10;
        int nmbOfReadWritePerThread = 100;
        int maxWaitTimeBetweenReadWrite = 3; // seconds
        try {
            File f = new File("C:\\tmp\\foo.txt");
            Writer wrtr = new FileWriter(f);
            Reader rdr = new FileReader(f);

            Set<Thread> threads = new HashSet();        
            for(int i = 0; i < nmbOfThreads; i++) {                
                Thread t = new Thread(new Worker(rdr, wrtr, nmbOfRdWrtPerThread, maxWaitTimeBetweenReadWrite));                
                threads.add(t);
            }

            for(Thread t : threads) { t.start(); }     
            for(Thread t : threads) { t.join(); }        
            wrtr.close();    
            rdr.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static void rndmPause(int range) throws Exception {
        long milliSec = (long) new Random(System.currentTimeMillis()).nextLong();
        milliSec = (long) (Math.abs(milliSec) % (range * 1000));
        Thread.sleep((long) milliSec);
    }


         static class Worker implements Runnable {
             Reader rdr; Writer wrtr;
             int nmbRdWrt, maxWaitTime;

             public Worker(Reader rdr, Writer wrtr, int nmbRdWrt, int maxWaitTime) {
                 this.rdr = rdr;
                 this.wrtr = wrtr;
                 this.nmbRdWrt = nmbRdWrt;
                 this.maxWaitTime = maxWaitTime;
             }

             public void run() {
                 try {
                     for(int i = 0; i < nmbRdWrt; i++) {
                         rndmPause(maxWaitTime);
                         wrtr.write("foo" + System.getProperty("line.separator"));
                         wrtr.flush();

                         rndmPause(maxWaitTime);
                         char[] cbuf = new char[100];
                         rdr.read(cbuf);
                     }
                 } catch(Exception e) {
                     e.printStackTrace();
                 }      
             }                  
         }
     }
}

Или ReadWriteLock используется только длязапретить многим потокам давить друг на друга и писать искаженный текст?

1 Ответ

0 голосов
/ 18 мая 2018

ReadWriteLock используется не только для предотвращения исключений, но и для того, чтобы writer не получил доступ к записи, в то время как другие writer или reader уже существуют.Как вы справляетесь с такими ситуациями?

Посмотрите

class Main {
    private static volatile int numFileWriter = 0;
    public static void main(String[] args) {
        int nmbOfThreads = 100;
        int nmbOfReadWritePerThread = 100;
        int maxWaitTimeBetweenReadWrite = 1; // seconds
        try {
            File f = new File("/home/mwalko/test");
            Writer wrtr = new FileWriter(f);
            Reader rdr = new FileReader(f);

            Set<Thread> threads = new HashSet();
            for(int i = 0; i < nmbOfThreads; i++) {
                Thread t = new Thread(new Worker(rdr, wrtr, nmbOfReadWritePerThread, maxWaitTimeBetweenReadWrite, i));
                threads.add(t);
            }

            for(Thread t : threads) { t.start(); }
            for(Thread t : threads) { t.join(); }
            wrtr.close();
            rdr.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static void rndmPause(int range) throws Exception {
        long milliSec = (long) new Random(System.currentTimeMillis()).nextLong();
        milliSec = (long) (Math.abs(milliSec) % (range * 1000));
        Thread.sleep((long) milliSec);
    }


    static class Worker implements Runnable {
        Reader rdr; Writer wrtr;
        int nmbRdWrt, maxWaitTime, threadNumber;

        public Worker(Reader rdr, Writer wrtr, int nmbRdWrt, int maxWaitTime, int threadNumber) {
            this.rdr = rdr;
            this.wrtr = wrtr;
            this.nmbRdWrt = nmbRdWrt;
            this.maxWaitTime = maxWaitTime;
            this.threadNumber = threadNumber;
        }

        public void run() {
            try {
                for(int i = 0; i < nmbRdWrt; i++) {
                    rndmPause(maxWaitTime);
                    wrtr.write("foo thread: " + threadNumber + " num: " + numFileWriter + System.getProperty("line.separator"));
                    wrtr.flush();
                    numFileWriter++;
                    rndmPause(maxWaitTime);
                    char[] cbuf = new char[100];
                    rdr.read(cbuf);
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

результат в файле:

foo thread: 33 num: 0
foo thread: 99 num: 0
foo thread: 29 num: 0
foo thread: 39 num: 0
foo thread: 7 num: 0
foo thread: 98 num: 0
foo thread: 95 num: 0
foo thread: 20 num: 0
foo thread: 75 num: 0
foo thread: 58 num: 0
foo thread: 47 num: 0
foo thread: 67 num: 0
foo thread: 40 num: 0
foo thread: 37 num: 0
foo thread: 21 num: 0
foo thread: 74 num: 0
foo thread: 16 num: 0
foo thread: 0 num: 0
foo thread: 70 num: 0
foo thread: 73 num: 19
foo thread: 63 num: 19
foo thread: 38 num: 20

и когда вы синхронизируете его или используете ReadWriteLock или используетеBufferedWriter (который является потокобезопасным), результат может быть правильным.Под правильным я имею в виду numFileWriter в хорошем состоянии

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...