Java OCA OCP Practice Question 2521

Question

Examine the following code and select the correct answer options.

public class Main {
    Lock myLock = new ReentrantLock();            //1
    static List<String> students = new ArrayList<>();
    public void add(String newStudent) {
        myLock.lock();                            //2
        try {/*w w  w.j a va  2s  .  c  om*/
            students.add(newStudent);
        }
        finally {
            myLock.unlock();                      //3
        }
    }
}
a  At line 1, if a reference variable lock is assigned an object of  
   ReentrantReadWriteLock, it won't make a difference.

b  The code at line 2 tries to acquire a lock on object myLock. 
   If the lock isn't available, it waits until the lock can be acquired.

c  The code at line 2 tries to acquire a lock on object myLock. 
   If the lock isn't available, it returns immediately.
   /*  w ww. java 2s  .  co m*/
d  If the code at line 3 is removed, the code will fail to compile.


b

Note

Option (a) is incorrect because, on assigning an object of ReentrantReadWriteLock to reference variable myLock, the code won't compile.

Class ReentrantReadWriteLock and the Lock interface are unrelated.

ReentrantReadWriteLock doesn't implement Lock, directly or indirectly.

Option (d) is incorrect because you should unlock an object when you no longer require a lock on it.

If you don't, your code will compile anyway.




PreviousNext

Related