Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Autoboxing and Performance ? Date: Wed, 21 Aug 2013 07:19:06 -0400 Organization: A noiseless patient Spider Lines: 46 Message-ID: References: <52140491$0$299$14726298@news.sunsite.dk> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 21 Aug 2013 11:19:10 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="0d73d8cc209bff1c6395088b400d0605"; logging-data="25603"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18BKZ2JxdBXVHYH3n+sTGG6" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130801 Thunderbird/17.0.8 In-Reply-To: Cancel-Lock: sha1:I25SUpkJSroHcnyIt7P9u2SX1EQ= Xref: csiph.com comp.lang.java.programmer:25091 On 8/21/2013 4:05 AM, Joerg Meier wrote: > On Tue, 20 Aug 2013 21:19:36 -0400, Eric Sosman wrote: > >> Nonetheless, I'm still of the opinion that autoboxing is Satan's >> work. Another thread, somewhat further back, wondered why this >> apparently thread-safe code wasn't thread-safe at all: > >> class Whatever { >> private static Integer counter; >> void someMethod() { >> synchronized(counter) { >> ++counter; >> ... >> } >> } >> ... >> } > > I still don't see how that wouldn't be thread-safe, could you elaborate ? > Or are we to assume other code touches counter without being in a > synchronized(counter) block itself in this example ? The `counter' variable is not an Integer object, but a reference to an Integer object. The `++counter' line brings a second Integer into the picture, and makes `counter' refer to that new Integer instead of to the original. However, the block is still synchronized on the first one; it doesn't somehow magically re-synchronize on the second. Assume `counter' points to Integer.valueOf(0) initially (I ought to have showed the initialization in the snippet; sorry). Then with threads T1 and T2 executing: T1: synchronized(counter) // locks the 0 object T1: ... now in critical section ... T1: ++counter; // counter now points to the 1 object T1: ... still in critical section ... T2: synchronized(counter) // locks the *1* object T2: ... now in critical section ... Both T1 and T2 are now in the synchronized block simultaneously, holding the locks of two different Integer objects. -- Eric Sosman esosman@comcast-dot-net.invalid