[concurrency-interest] Cloning in CachingFactorizer in JavaConcurrency in Practice

David Holmes dcholmes at optusnet.com.au
Tue Jan 22 23:40:41 EST 2008

The cloning isn't for concurrency reasons but just the usual defensive
copying so that the receiver of the array can't mess with the original

Effective Java item 24.

David Holmes
  -----Original Message-----
  From: concurrency-interest-bounces at cs.oswego.edu
[mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of Unmesh joshi
  Sent: Wednesday, 23 January 2008 2:09 PM
  To: concurrency-interest at cs.oswego.edu
  Subject: [concurrency-interest] Cloning in CachingFactorizer in
JavaConcurrency in Practice


  I just started reading Java Concurrency in practice. In the following
CachingFactorizer example

  BigInteger i = extractFromRequest(req);

  BigInteger[] factors = null;

  synchronized (this) {


  if (i.equals(lastNumber)) {


  factors = lastFactors.clone();



  if (factors == null) {

  factors = factor(i);

  synchronized (this) {

  lastNumber = i;

  lastFactors = factors.clone();



  encodeIntoResponse(resp, factors);


  factors and lastFactors are cloned in the synchronized blocks, but there
is no explanation at that point why they are cloned. In the Object Sharing
section, stack confinement is discussed, but using a different example. I
think it will help reader if a note is added at that point saying that
cloning here is for stack confinement, because assignments to factors or
lastfactors is indirectly publishing the array to other thread which can be
processing the array in encodeIntoResponse method.



  Live the life in style with MSN Lifestyle. Check out! Try it now!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20080123/45c1de5d/attachment-0001.html 

More information about the Concurrency-interest mailing list