Which class implements IdGenerator in a thread-safe manner, so that no threads can get a duplicate id value current access?

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 value current access?

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 value current access?

A.
Public class generator Implements IdGenerator {
Private AtomicInteger id = new AtomicInteger (0);
return id.incrementAndget();
}}

B.
Public class Generator Implements idGenerator {
private int id = 0;
return ++id;
}}

C.
Public class Generator Implements IdGenerator {
private volatile int Id = 0;
return ++Id;
}

D.
Public class Generator Implements IdGenerator {
private int id = 0;
public int getNextId() {
synchronized (new Generator()) {
return ++id;
}}}

E.
Public class Generator Implements IdGenerator {
private int id = 0;
public int getnextId() {
synchronized (id) {
return ++id;
}}}

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)



Leave a Reply 4

Your email address will not be published. Required fields are marked *


Tim

Tim

D is not thread-safe.

If A B C are all added the method signature “int getNextId();”, it should be A.

Humberto Bañuelos Flores

Humberto Bañuelos Flores

(y)

l0c

l0c

D definitely isn’t threadsafe indeed.

I hope the exam tells us that ABC have getNextId method signatures.

Then it should indeed be A:
B is not possible because it doesn’t involve any locking.
C Volatile has a different purpose.
D is not thread safe (“new Generator()” is a new Generator every time, so there’s no real locking going on here).
E cannot use synchronized on a primitve.

Humberto Bañuelos Flores

Humberto Bañuelos Flores

(y)