Let's suppose I have a very simple id generator class which can be use my many threads simultaneously. Will the following code work fine - I mean it will always return unique ids?
class Generator{
private int counter=0;
public int getId(){
return counter++;//the key point is here
}
}
No. It's not thread safe at all, you would need to synchronize
your getId()
method.
However it's better to use AtomicInteger.incrementAndGet()
instead.
public class Generator {
private final static AtomicInteger counter = new AtomicInteger();
public static int getId() {
return counter.incrementAndGet();
}
}
You need to make counter as static
variable. And get method as static synchronize
.
class Generator{
private static int counter=0;
public static synchronized int getId(){
return counter++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.