1

I have to add locks to my readFromFile() and writeToFile() methods for school. Please see the method code below and advise me where in the code I would place the locks? Would I use ReentrantLock or ReadWriteReentrantLock? We have to use locks.

Thank you.

Read method

public static void readFromFile(List<Person> people) { FileReader fr = new FileReader("names"); Scanner sc = new Scanner(fr); while (sc.hasNext()) { String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); people.add(new Person(name, age)); } sc.close(); } 

Write method

public static void writeToFile(List<Person> people) { File outputFile = new File (List<Person> people) PrintWriter pw = new PrintWriter(outputFile); for (Person p: people) { pw.println(p.name); } pw.close(); } 
1
  • 1
    probably easiest to synchronize on an Object Commented Oct 11, 2017 at 8:02

2 Answers 2

4

Just guard whole method body

 static ReadWriteLock rwl = new ReentrantReadWriteLock(); public static void readFromFile(List<Person> people) { rwl.readLock().lock(); try { ... //method body is not changed } finally { rwl.readLock().unlock(); } } public static void writeToFile(List<Person> people) { rwl.writeLock().lock(); try { ... //method body is not changed } finally { rwl.writeLock().unlock(); } } 
Sign up to request clarification or add additional context in comments.

Comments

2

The difference between ReentrantLock and ReentrantReadWriteLock is a more fine granular control on the throughput.

A ReentrantLock has the same power as the java monitor locking with synchronized. It is just technically different.

If you have many reads and less writes it is worth to use a ReadWrite lock, because it allowes reads in parallel as long as there is no write.

If you use ReentrantLocks, always follow the try-finally pattern to have the lock free in any case. That is not needed with synchronized.

here a suggestion for the read in your example with readWrite. The write method is the same just use the writeLock().

private static final ReentrantReadWriteLock readWriteLock = new readWriteLock; public static void readFromFile(List<Person> people) { readWriteLock.readLock().lock(); try { // method body } finally { readWriteLock.readLock().unlock(); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.