[concurrency-interest] BigDecimal Safe Publication
Vitaly Davidovich
vitalyd at gmail.com
Sun Aug 26 10:18:37 EDT 2012
Compiler can turn that code into:
BigDecimal tmp = priceBD;
if (priceBD == null)
{
// init priceBD
tmp = priceBD;
}
return tmp;
Imagine that thread 1 reads null into temp but then gets preempted and
thread 2 goes through and initializes priceBD. When thread 1 resumes,
it'll see a non-null priceBD and then happily return a null, which breaks
the logic.
Reading and returning a temp yourself prevents this type of reordering.
Sent from my phone
On Aug 26, 2012 6:32 AM, "Per Mildner" <Per.Mildner at sics.se> wrote:
>
> On Aug 20, 2012, at 7:58 PM, Zhong Yu <zhong.j.yu at gmail.com> wrote:
>
> > On Mon, Aug 20, 2012 at 6:49 AM, James <james at inaseq.com> wrote:
> >> I have a system that processes a lot of Doubles. From time to time I
> need
> >> the accuracy of BigDecimal math but creating a BigDecimal is relatively
> >> expensive so I only do it when needed. Hence I use lazy initialization
> as
> >> shown below.
> >>
> >> private Double price; // although not final is effectively immutable
> and
> >> guaranteed non-null when used below
> >> private transient BigDecimal priceBD;
> >>
> >> public BigDecimal getPriceBD() {
> >> if (priceBD == null) {
> >> priceBD = BigDecimal.valueOf(price); // strict singleton semantics not
> >> required
> >> }
> >> return priceBD;
> >> }
> >
> > You may have omitted it for brevity, but a local variable is necessary
> > here for correctness. See String.hashCode()
>
> Where, and why, would a local variable help?
>
> Also, I do not see how this relates to String.hashCode().
>
> What am I missing?
>
> For reference, String.java:
> {
> ...
> private int hash; // Default to 0
> ...
> public int hashCode() {
> int h = hash;
> if (h == 0 && count > 0) {
> int off = offset;
> char val[] = value;
> int len = count;
>
> for (int i = 0; i < len; i++) {
> h = 31*h + val[off++];
> }
> hash = h;
> }
> return h;
> }
> ...
> }
>
> Regards,
>
> Per Mildner
> Per.Mildner at sics.se
>
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120826/1366bc7a/attachment.html>
More information about the Concurrency-interest
mailing list