Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are many possible solutions:</p> <ul> <li>Use an existing caching solution like <a href="http://ehcache.org/" rel="nofollow">EHcache</a></li> <li>Use the Spring framework which got an easy way to cache results of a method with a simple <a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html" rel="nofollow">@Cacheable annotation</a></li> <li>Use one of the synchronized maps like <code>ConcurrentHashMap</code></li> <li>If you know all keys in advance, you can use a <a href="http://blog.pdark.de/2010/03/04/java-tricks-lazy-initialization/" rel="nofollow">lazy init code</a>. Note that everything in this code is there for a reason; change anything in <code>get()</code> and it <strong>will</strong> break eventually (eventually == "your unit tests will work and it will break after running one year in production without any problem whatsoever").</li> </ul> <p><code>ConcurrentHashMap</code> is most simple to set up but it has simple way to say "initialize the value of a key once".</p> <p>Don't try to implement the caching by yourself; multithreading in Java has become a very complex area with Java 5 and the advent of multi-core CPUs and memory barriers.</p> <p><strong>[EDIT]</strong> yes, this might happen even though the map is synchronized. Example:</p> <pre><code>SoftReference&lt;...&gt; value = cache.get( key ); if( value == null ) { value = computeNewValue( key ); cache.put( key, value ); } </code></pre> <p>If two threads run this code at the same time, <code>computeNewValue()</code> will be called twice. The method calls <code>get()</code> and <code>put()</code> are safe - several threads can try to put at the same time and nothing bad will happen, but that doesn't protect you from problems which arise when you call several methods in succession <strong>and</strong> the state of the map must not change between them.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload