Exam 1z0-819 All QuestionsBrowse all questions from this exam
Question 38

Given the code fragment:

You must make the count variable thread safe.

Which two modifications meet your requirement? (Choose two.)

    Correct Answer: C, D

    To ensure the count variable is thread-safe, two suitable modifications can be made. First, replacing line 1 with private AtomicInteger count = new AtomicInteger(0); and replacing line 3 with test.count.incrementAndGet(); uses AtomicInteger, which provides atomic operations for its value, ensuring thread safety. Second, replacing line 3 with synchronized(test) { test.count++; } ensures that only one thread can execute the block at a time, preventing race conditions when incrementing the count. This combination effectively handles the thread-safety requirement.

Discussion
d7bb0b2Options: CD

D => 0nly one observarion, Notice atomic.incrementAndGet is ++testcont atomicinteget.getAndIncrement is testcount ++

d7bb0b2

on the conext is not important because not used after that, but is only a observation

StavokOptions: CD

Option C replaces line 3 with a synchronized block that synchronizes on the test object. This ensures that only one thread can execute the code within the synchronized block at a time, preventing race conditions when multiple threads try to increment the count variable simultaneously. Option D replaces line 1 with an AtomicInteger variable, which provides atomic operations for updating its value. The incrementAndGet method is then used on line 3 to atomically increment the value of the count variable. This also prevents race conditions when multiple threads try to increment the count variable simultaneously.

Mukes877Options: CD

D & C is correct And E is not because synchronized can only be used with objects or references to objects and used to lock objects.

RP384Options: CD

E is syntactically wrong