Given: public class NamedCounter { private final String name; private int count; public NamedCounter(String name) { this.name = name; } public String getName() { return name; } public void increment() { count++; } public int getCount() { return count; } public void reset() { count = 0; } } Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.)

  1. declare reset() using the synchronized keyword

  2. declare getName() using the synchronized keyword

  3. declare getCount() using the synchronized keyword

  4. declare the constructor using the synchronized keyword

  5. declare increment() using the synchronized keyword


Correct Option: A,C,E

AI Explanation

To adapt the NamedCounter class to be used safely by multiple threads, we need to ensure that the class's methods are synchronized to avoid potential race conditions.

Let's go through each option to understand why it is correct or incorrect:

Option A) Declare reset() using the synchronized keyword - This option is correct because synchronizing the reset() method ensures that only one thread can call it at a time, preventing any inconsistencies or conflicts when resetting the count.

Option B) Declare getName() using the synchronized keyword - This option is incorrect. Synchronizing the getName() method is not necessary because it only returns the name field, which is a final field and cannot be modified.

Option C) Declare getCount() using the synchronized keyword - This option is correct because synchronizing the getCount() method ensures that only one thread can access and return the count at a time, preventing any inconsistencies or conflicts.

Option D) Declare the constructor using the synchronized keyword - This option is incorrect. Synchronizing the constructor is not necessary because each thread will have its own instance of the NamedCounter object, and the constructor does not modify any shared data.

Option E) Declare increment() using the synchronized keyword - This option is correct because synchronizing the increment() method ensures that only one thread can increment the count at a time, preventing any inconsistencies or conflicts.

Therefore, the correct answers are A, C, and E. These options ensure that the necessary methods are synchronized to make the NamedCounter class safe for concurrent access by multiple threads.

Find more quizzes: