<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>@InitBinder &#187; threads</title>
	<atom:link href="http://initbinder.com/categories/threads/feed" rel="self" type="application/rss+xml" />
	<link>http://initbinder.com</link>
	<description>My thoughts, notes and ideas as a passionate software engineer</description>
	<lastBuildDate>Sat, 24 Mar 2012 13:29:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Making Instance Variables Thread Safe</title>
		<link>http://initbinder.com/articles/making-instance-variables-thread-safe.html</link>
		<comments>http://initbinder.com/articles/making-instance-variables-thread-safe.html#comments</comments>
		<pubDate>Sat, 23 Oct 2010 12:01:06 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[threads]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[thread safety]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=787</guid>
		<description><![CDATA[One of the ways to achieve thread safety when creating instance variables is to make a use of ThreadLocal class.  When instance variable is wrapped in ThreadLocal, each thread accessing the variable has its own independent copy of the variable. &#8230; <a href="http://initbinder.com/articles/making-instance-variables-thread-safe.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the ways to achieve thread safety when creating instance variables is to make a use of <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> class.  When instance variable is wrapped in ThreadLocal, each thread accessing the variable has its own independent copy of the variable.</p>
<p>An even better approach is to wrap the instance variable in <a title="SoftReference" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ref/SoftReference.html" target="_blank">SoftReference</a>, which can eliminate the risk if getting <a title="OutOfMemoryError" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/OutOfMemoryError.html" target="_blank">OutOfMemoryError</a> if there is a need to keep a an object in memory for a long period of time, for example when implementing caching mechanism. The garbage collector will only collect softly referenced objects when it decides that memory is low enough to warrant it</p>
<p>Consider the following snippet:</p>
<p>[java]<br />
public class ThreadSafeExample {</p>
<p> private static final ThreadLocal&lt;SoftReference&lt;List&lt;SomeObject&gt;&gt;&gt; trhLocal =<br />
                                new ThreadLocal&lt;SoftReference&lt;List&lt;SomeObject&gt;&gt;&gt;();<br />
 .<br />
 .<br />
    public static List&lt;SomeObject&gt; getSafeList() {</p>
<p>      // Get the value of the current thread&#8217;s copy of this thread-local variable<br />
      SoftReference&lt;List&lt;SomeObject&gt;&gt; reference = trhLocal.get();</p>
<p>      if (reference != null)  {<br />
         // Get this reference object&#8217;s referent<br />
         List&lt;SomeObject&gt; safeList = reference.get();</p>
<p>            if (safeList != null)  {<br />
                 return safeList;<br />
            }<br />
       }</p>
<p>       // Ok, so we did not have previously anything,<br />
       // lets create thread-local variable<br />
       List&lt;SomeObject&gt; safeList = new LinkedList&lt;SomeObject&gt;();<br />
       reference = new SoftReference&lt;List&lt;SomeObject&gt;&gt;(safeList);<br />
       trhLocal.set(reference);</p>
<p>     return safeList;<br />
   }<br />
}<br />
[/java]</p>
<p>What happens in the above example is, when getSafeList() is called, the thread&#8217;s list is assigned the first time it invokes getSafeList(), which causes invocation of  trhLocal.get().  If get() does not return anything, a new copy of the instance variable is created and set to the <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> instance. Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> instance is accessible. This approach does not require  synchronization, which can create thread contention, and provides much faster access to the variable than via synchronization.</p>
<p>Off course one should consider whether <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a> is really needed. Normally, a good candidates for object re-use via thread local are objects that are frequently accessed by a given thread and are non-trivial to construct. Another scenario for making use of <a title="ThreadLocal" href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html" target="_blank">ThreadLocal</a>, would be when it is not really practical to extend Thread class (for example creating servlets) and thread safety is needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/making-instance-variables-thread-safe.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Brainteaser: Hidden Iterators</title>
		<link>http://initbinder.com/articles/brainteaser_hidden_iterators.html</link>
		<comments>http://initbinder.com/articles/brainteaser_hidden_iterators.html#comments</comments>
		<pubDate>Sun, 07 Sep 2008 08:05:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[brainteaser]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[threads]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2008/09/07/brainteaser_hidden_iterators.html</guid>
		<description><![CDATA[&#8230; While locking can prevent iterators from throwing ConcurrentMofdificationException, You have to remember to use locking everywhere a shared collection might be iterated. This is trickier than it sounds &#8230; Brian Goetz p.83-84 Question: The following code could throw ConcurrentMofdificationException, &#8230; <a href="http://initbinder.com/articles/brainteaser_hidden_iterators.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<blockquote><p>&#8230; While locking can prevent iterators from throwing <em>ConcurrentMofdificationException</em>, You have to remember to use locking everywhere a shared collection might be iterated. This is trickier than it sounds &#8230;</p></blockquote>
<p><a href="http://jcip.net/" target="_blank">Brian Goetz</a> p.83-84</p>
<p><strong>Question</strong>: The following code could throw <em>ConcurrentMofdificationException</em>, even though <em>add()</em> is synchronized, why?</p>
<p>[java]<br />
public class HiddenIterator  {<br />
     private final Set set = new HashSet();</p>
<p>public synchronized void add(Integer i) {<br />
     set.add(i);<br />
}</p>
<p>public synchronized void remove(Integer i) {<br />
     set.remove(i);<br />
}</p>
<p>public void addTenThings() {<br />
   Random r = new Random();<br />
   for (int index = 0; index &amp;lt; 10;  index++;) {<br />
       add(r.nextInt());<br />
   }</p>
<p>   System.out.println(&quot;Added ten elements to set: &quot; + set);<br />
}<br />
}<br />
[/java]</p>
<p>Looking forward for your answers dear readers</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/brainteaser_hidden_iterators.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singleton Pattern and Problem With Double Checked Locking</title>
		<link>http://initbinder.com/articles/singleton_pattern_and_problem_with_double_checked_locking.html</link>
		<comments>http://initbinder.com/articles/singleton_pattern_and_problem_with_double_checked_locking.html#comments</comments>
		<pubDate>Sat, 06 Sep 2008 02:56:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[threads]]></category>
		<category><![CDATA[design concepts]]></category>
		<category><![CDATA[idiom]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2008/09/06/singleton_pattern_and_problem_with_double_checked_locking.html</guid>
		<description><![CDATA[There are several ways to initialize singleton object. Some are thread safe and some are not. Until the last two days I thought that double-checked locking idiom offers the best solution for singleton initialization in multi threaded environment. Well its &#8230; <a href="http://initbinder.com/articles/singleton_pattern_and_problem_with_double_checked_locking.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There are several ways to initialize singleton object. Some are thread safe and some are not. Until the last two days I thought that double-checked locking idiom offers the best solution for singleton initialization in multi threaded environment. Well its not.</p>
<p>To begin, I want to describe briefly several ways to initialize singleton:</p>
<ul>
<li>Lazy initialization</li>
<li>Eager initialization</li>
<li>DCL</li>
<li>Class holder lazy initialization</li>
<li>Enum singleton</li>
</ul>
<p><strong>Lazy initialization</strong><br />
The goal of lazy initialization was to defer initialization of an object until it is actually needed, while making sure that initialization is done only once. Lazy initialization example illustrated below:</p>
<p>[java]<br />
public class Singleton{</p>
<p>	private static Singleton instance = null;</p>
<p>	private Singleton() {  }</p>
<p>	public static Singleton getInstance() {<br />
		if (instance == null)  {<br />
		instance = new Singleton();<br />
	}<br />
        return instance;<br />
    }<br />
}<br />
[/java]</p>
<p>This will work fine in single-threaded environment. Unfortunately since <em>getInstance</em>() is not synchronized, two different instances of the object can be returned if two threads will access <em>getInstance</em>() method concurrently. Which makes this lazy initialization unsafe in multi threaded environment.</p>
<p>Unsafe lazy initialization can be fixed by making <em>getInstance</em>() synchronized:</p>
<p>[java]</p>
<p>	public class Singleton{</p>
<p>	private static Singleton instance = null;</p>
<p>	private Singleton() {  }</p>
<p>	public static synchronized Singleton getInstance() {<br />
		if (instance == null)  {<br />
			instance = new Singleton();<br />
		}<br />
		return instance;<br />
	}<br />
	}<br />
[/java]</p>
<p>However, in this case there is performance hit for every invocation of <em>getInstance</em>() method. Synchronized methods runs very slow compared to unsynchronized methods. I haven&#8217;t tested this issue my self, so i cannot tell by how much slower.</p>
<p><strong>Eager initialization</strong><br />
By using eager initialization, the synchronization cost incurred for each method call is eliminated:</p>
<p>[java]<br />
	public class Singleton{<br />
		private static Singleton instance = new Singleton();</p>
<p>		private Singleton() {  }</p>
<p>		public static Singleton getInstance() {<br />
			return instance;<br />
		}<br />
	}<br />
[/java]</p>
<p>The problem with eager initialization that <em>Singleton </em>object is instantiated regardless whether it is going to be used or not.</p>
<p><strong>DCL</strong><br />
Double-checked locking (DCL) idiom was created to allow lazy initialization of a singleton object, without performance reducing costs as a result of synchronization. Unfortunately it does not work. Lets have a look why:</p>
<p>[java]<br />
public class Singleton {</p>
<p>  private static Singleton instance = null;</p>
<p>  private Singleton() {  }</p>
<p>  public static Singleton getInstance() {<br />
	if (instance == null)  {<br />
		synchronized(Singleton.class)  {<br />
			if (instance == null)  {<br />
				instance = new Singleton();<br />
			}<br />
		}<br />
	}<br />
	return instance;<br />
	}<br />
}<br />
[/java]</p>
<p>First there is a check whether initialization is needed with out synchronization, and if the <em>instance</em> is not null &#8211; then use it.<br />
Otherwise, synchronize and check again if <em>instance</em> is null by making sure that only one thread will initialize the shared <em>Singleton</em>.</p>
<p>The problem with DCL is that code of fetching reference to constructed <em>Singleton </em>object<em> </em>does not require synchronization.<br />
Lets say that thread &#8216;a&#8217; has entered synchronized block, made the <em>instance</em> not null  but hasn&#8217;t executed the constructor yet. At this stage thread &#8216;b&#8217; preempts thread &#8216;a&#8217;. Thread &#8216;b&#8217; checks if the <em>instance</em> is not null, and since its not, it returns reference to a partially constructed <em>Singleton </em>object.</p>
<p>In other words &#8211; thread &#8216;b&#8217; sees a current value of the <em>Singleton </em>object reference instead of its stale value, which causes the object to be seen in invalid or incorrect state.</p>
<p><strong>Class holder lazy initialization</strong></p>
<p>Instead of DCL, lazy initialization class holder idiom offers better solution for singleton initialization in multi threaded environment, with the same benefits as DCL:</p>
<p>[java]<br />
public class SingletonFactory {</p>
<p>  private static class SingletonHolder {<br />
     public static Singleton instance = new Singleton();<br />
  }</p>
<p>  public static Singleton getInstance()  {<br />
     return SingletonHolder.instance;<br />
  }<br />
}<br />
[/java]</p>
<p>The <em>SingletonHolder </em>class initialization is deferred until its actually used, and because <em>Singleton </em>is initialized with static initializer, no additional synchronization is needed.<br />
The first invocation of  <em>getInstance</em>() by any thread causes <em>SingletonHolder </em>to be loaded and initialized during which time the <em>Singleton </em>is initialized through static initializer.</p>
<p><strong>Enum singleton</strong><br />
Joshua Bloch in his book &#8220;<span class="removed_link" title="http://www.oracle.com/publications">Effective Java</span>&#8221; offers a new interesting solution to initialize a Singleton by using Enum with a single type:</p>
<p>[java]<br />
public class SingletonEnum {<br />
  INSTANCE;</p>
<p>  public void someMethod() {<br />
     &#8230;<br />
  }</p>
<p>  public void anotherMethod() {<br />
     &#8230;<br />
  }<br />
}<br />
[/java]</p>
<p>Joshua claims:</p>
<blockquote><p>&#8220;&#8230;a single-element enum type is the best way to implement a singleton&#8230;&#8221;</p></blockquote>
<p>Some people may argue against this approach by saying that this is not a class, but an enum &#8211; it enumarates plus enums cannot be subclassed. Well in case of a singleton there is no point in subclassing, since singletons have private constructors and singletons dont really ment to be subclassed. Lets have a look if Enum singleton is indeed the best solution so far:</p>
<p>1. Enum singleton is final<br />
2. It is serializable<br />
3. It is a single instance in multithreaded environment<br />
4. Does not allow invokation of private constructors through reflection attacks</p>
<p>I think its quite original solution.</p>
<p>I will appreciate your comments regarding this post. Cheers.</p>
<p>Resources:<br />
<em><span class="removed_link" title="http://www.oracle.com/publications">Effective Java</span></em><br />
<em><a href="http://jcip.net/" target="_blank">Java Concurrency in Practice</a></em></p>
<p><em><span class="removed_link" title="http://www.ibm.com/developerworks/java/library/j-dcl.html">Double-checked locking and the Singleton pattern</span></em></p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/singleton_pattern_and_problem_with_double_checked_locking.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  initbinder.com/categories/threads/feed ) in 0.21694 seconds, on May 18th, 2012 at 2:31 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 18th, 2012 at 3:31 pm UTC -->
