Given:
public class MyGrades {
private final List<Integer> myGrades = new ArrayList<Integer>();
private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
public void addGrade(Integer grade) {
// acquire _______ lock
myGrades.add(grade);
// release __________ lock
}
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));
}
Which pair’s statements should you insert at lines ** and lines *** (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.
relock.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