Java OCA OCP Practice Question 2860

Question

What statements about the following class definition are true? (Choose all that apply.)

public class Main { 
   private Main() { super(); } 
   private static Main instance; 
   public static synchronized Main getInstance() { // k1 
      if (instance == null) instance = new Main(); // k2 
      return instance; 
   } /*ww w. ja  v  a  2  s . c o m*/

   private int tickets; 
   public int getTicketCount() { return tickets; } 
   public void makeTicketsAvailable(int value) { tickets += value; } // k3 
   public void sellTickets(int value) { 
      synchronized (this) { // k4 
         tickets -= value; 
      } 
   } 
} 
  • A. It compiles without issue.
  • B. The code will not compile because of line k2.
  • C. The code will not compile because of line k3.
  • D. The lock locks acquired on k1 and k4 are on the same object.
  • E. The class correctly prevents concurrency issues for the value of tickets when accessed by multiple threads.
  • F. At most one instance of Main will be created in the application.


A, F.

Note

The class compiles without issue so A is correct, and B and C are incorrect.

The synchronized object on line k1 is Main.

class, while the synchronized object on line k4 is the instance of Main.

The class is not thread-safe because the makeTicketsAvailable() method is not synchronized, and E is incorrect.

One thread could call sellTickets() while another thread has unblocked accessed to makeTicketsAvailable(), causing an invalid number of tickets to be reached as part of a race condition.

Finally, F is correct because the class synchronizes using a static getInstance() method, preventing more than one instance from being created.




PreviousNext

Related