1Z0-804 · Question #83
Given the interface: Public interface Idgenerator { int getNextId(); } Which class implements IdGenerator in a thread-safe manner, so that no threads can get a duplicate id valuecurrent access?
The correct answer is D. Public class Generator Implements IdGenerator { private int id = 0. Code that is safe to call by multiple threads simultaneously is called thread safe. If a piece of code is threadsafe, then it contains no race conditions. Race condition only occur when multiple threads update sharedresources. Therefore it is important to know what resources…
Question
Given the interface:
Public interface Idgenerator { int getNextId(); } Which class implements IdGenerator in a thread-safe manner, so that no threads can get a duplicate id valuecurrent access?
Options
- APublic class generator Implements IdGenerator { Private AtomicInteger id = new AtomicInteger (0);
- BPublic class Generator Implements idGenerator { private int id = 0;
- CPublic class Generator Implements IdGenerator { private volatile int Id = 0;
- DPublic class Generator Implements IdGenerator { private int id = 0;
- EPublic class Generator Implements IdGenerator { private int id = 0;
How the community answered
(55 responses)- A4% (2)
- B15% (8)
- C2% (1)
- D73% (40)
- E7% (4)
Explanation
Code that is safe to call by multiple threads simultaneously is called thread safe. If a piece of code is threadsafe, then it contains no race conditions. Race condition only occur when multiple threads update sharedresources. Therefore it is important to know what resources Java threads share when executing. In Java you can mark a method or a block of code as synchronized. Synchronized blocks can be used to avoidrace conditions. A, B, C : false: wrong Implementation ( missing int getNextId(); ) E: false: synchronized (mutex Object! not Simple Data Type)
Topics
Community Discussion
No community discussion yet for this question.