Given:
<code>
public class MyGrades {
private final List<Integer> myGrades = new ArrayList<Integer>();
private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
public void addGrade(Integer grade) {
/*
lock and modify
*/
}
public void averageGrades() {
// acquire _______ lock Line **
double sum = 0;
int i = 0;
for (i = 0; i < myGrades.size(); i++) {
sum += myGrades.get(i);
}
// release __________ lock Line ***
System.out.println(“The average is: ” + sum/(i+1));
}
}
</code>
Which pairs statements should you insert at line ** and line *** (respectively) to acquire and release the most appropriate lock?
A.
rwlock.readLock().acquire();
rwlock.readLock().release();
B.
rwlock.readLock().lock();
rwlock.readLock().unlock();
C.
rwlock.getLock().acquire();
rwlock.getLock().release();
D.
rwlock.getLock().lock();
rwlock.getLock().Unlock();
E.
rwlock.WriteLock().acquire();
rwlock.writeLock().release();
F.
rwlock.writeLock().lock();
rwlock.WriteLock().unlock();
Explanation:
We need a read lock, not a write lock, we are just reading data, not writing/updating data.
To aquire and release the lock the method lock() and unlock are used.
Reference: Class ReentrantReadWriteLock