Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use long instead of int can bulletproof the following method - Effective Java

Tags:

java

Consider the following code picked from Joshua Bloch - Effective Java, page 263

// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
    return nextSerialNumber++;
}

One way to fix the generateSerialNumber method is to add the synchronized modifier to its declaration. This ensures that multiple invocations won’t be interleaved, and that each invocation will see the effects of all previous invocations. Once you’ve done that, you can and should remove the volatile modifier from nextSerialNumber. To bulletproof the method, use long instead of int, or throw an exception if nextSerialNumber is about to wrap.

  1. I understand that we can remove volatile after we make generateSerialNumber synchronized, as it is redundant. But, does it make any harm? Any performance penalty if I am having both synchronized and volatile like

private static volatile int nextSerialNumber = 0;
public static synchronized int generateSerialNumber() {
    return nextSerialNumber++;
}

  1. What does, use long instead of int means? I do not understand how this bulletproof the method?
like image 895
Cheok Yan Cheng Avatar asked Nov 28 '25 20:11

Cheok Yan Cheng


1 Answers

It simply means that long will hold many more numbers than int.

or throw an exception if nextSerialNumber is about to wrap

implies that the concern here is that you run out of numbers and you end up with an overflow. You want to ensure that does not happen. The thing is, if you are at the maximum integer possible and you increment, the program does not fail. It happily goes not incrementing but the result is no longer correct.

Using long will postpone this possibility. Throwing the exception will indicate that it has happened.

like image 99
Vincent Ramdhanie Avatar answered Nov 30 '25 09:11

Vincent Ramdhanie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!