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, F.
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.