Path: csiph.com!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Sebastian Newsgroups: comp.lang.java.programmer Subject: Re: multithreaded cache? Date: Sun, 20 May 2012 01:48:04 +0200 Organization: albasani.net Lines: 38 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net BJyEguu4e0Q89W5hI5SvmZX/Pj7I9EJ/m9MuaFBrd2mQLFFxIfmi7MJU3nZuDP0SLNA0+qkx/YAA2k1fK60CdrUlyYN2uPntM+UnkcLpj3VORsnkSK+XiD9GhqlDeWZv NNTP-Posting-Date: Sat, 19 May 2012 23:48:01 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="w2qSEFF7jCE6Or6ajylJ6em6JuQn6iy8ad52J1aL5WO7/h/JspndaGaBVY19zVXTXOPmENFeiGS9xthwCE7wpxUia1qoRgLWh6TdJ3QOuC8vxDBA1sISOjP5kUqIC1a6"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.15) Gecko/20110303 Thunderbird/3.1.9 In-Reply-To: Cancel-Lock: sha1:Rxmid6NmuG60HQdHmUmku1qVnNc= Xref: csiph.com comp.lang.java.programmer:14659 Am 20.05.2012 01:35, schrieb Sebastian: > Am 17.05.2012 12:06, schrieb Robert Klemme: >> On 05/17/2012 11:54 AM, Robert Klemme wrote: >>> On 05/15/2012 11:14 AM, bugbear wrote: >>>> However, if the underlying function is slow >>>> and/or resource hungry (consider cacheing >>>> a ray traced image!) many threads can >>>> end up calling the real function (second >>>> and subsequent threads to the first get a miss >>>> during the first threads call to the underlying function). >>>> >>>> "obviously..." what I want is for only >>>> the thread that FIRST has a cache miss >>>> calls the underlying function, whilst other >>>> threads (for the same key) wait. >>> >>> I provide a variant of Silvio's, Eric's and Daniel's solution which >>> should yield higher throughput because it works without read write >>> locking. You can find it as gist in case the code is garbled in the >>> newsgroup posting: >>> https://gist.github.com/2717818 >> >> There was one important detail missing. This is the corrected code (gist >> is updated as well): >> > [snip] > The important detail obiously is the extra check with the "here" flag. > Would you mind explaining why that is necessary? Everyone seems to have > got it, but I must admit I haven't. Why is it not enough that > Reference#get() is synchronized? As you yourself have missed this at > your first attempt, I hope the reason isn't trivial... > -- Sebastian > I think I've got it - the check prevents double calculation of the value by two threads calling get() on that same reference instance. Which may occur if putIfAbsent() returns a non-null value before the "calculating reference" has had time to replace itself with the constant reference. Is that right? -- Sebastian