<?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>ChiaoCheng.com</title>
	<atom:link href="http://www.chiaocheng.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.chiaocheng.com</link>
	<description></description>
	<lastBuildDate>Thu, 08 Dec 2011 07:26:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Changing a wordpress domain name</title>
		<link>http://www.chiaocheng.com/blog/2011/09/changing-a-wordpress-domain-name/</link>
		<comments>http://www.chiaocheng.com/blog/2011/09/changing-a-wordpress-domain-name/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 06:35:00 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=467</guid>
		<description><![CDATA[Holy permanent domain names Batman! Once in a while, I discover something about wordpress that makes me wonder how it ever got so popular. The most recent discovery is that wordpress stores your site&#8217;s domain name into the mysql database. &#8230; <a href="http://www.chiaocheng.com/blog/2011/09/changing-a-wordpress-domain-name/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: right;"><em>Holy permanent domain names Batman!</em></p>
<p>Once in a while, I discover something about wordpress that makes me wonder how it ever got so popular. The most recent discovery is that wordpress stores your site&#8217;s domain name into the mysql database. Worst of all, it doesn&#8217;t just store it in one place but litters it throughout several tables and records. And of course wordpress does not come with any way to migrate the site to a different domain name.</p>
<p>This is a problem because I want to be able to setup a pre-production site on a pre-production domain and then move it to a production domain once it&#8217;s ready.  For example, I recently wanted move this blog to wordpress 3.2 but I wanted to see it in action on my test url first.</p>
<p>After doing some research, there were no official list of where the domain name may be stored and there were just too many tables and records to look through manually.  In addition, I knew I had to change the domain a few times so I put in some time and wrote a php script to look through all the tables, records, fields, etc for the existing domain name.  When it finds one in a particular field, it updates the value to the new domain.</p>
<pre>&lt;?php

$longopts = array(
  "db_name:",
  "db_user:",
  "db_pw:",
  "find_string:",
  "replace_string:",
  "replace_guid_field"
);

$options = getopt("", $longopts);
print "Found arguments:\n";
print_r($options);

$database = $options["db_name"];
$database_user = $options["db_user"];
$database_pw = $options["db_pw"];
$find_string = $options["find_string"];
$replace_string = $options["replace_string"];
$replace_guid = array_key_exists("replace_guid_field", $options);

$link = mysql_connect("localhost", $database_user, $database_pw);
mysql_select_db($database);

$query = "SHOW TABLES FROM $database";
$result = mysql_query($query);

while ($arr = mysql_fetch_array($result, MYSQL_NUM)) {
  foreach ($arr as $table) {
    process_table($table, $find_string, $replace_string, $replace_guid);
  }
}
mysql_close($link);

print "done";

function process_table($table, $find_string, $replace_string, $replace_guid) {
  print "\nprocessing $table....";

  $field_arr = array();
  $query = "SELECT * FROM $table";
  $result = mysql_query($query);
  while ($row_arr = mysql_fetch_array($result, MYSQL_ASSOC)) {
    foreach ($row_arr as $key =&gt; $value) {
      if (strpos($value, $find_string) !== false) {
        // Create a list of fields which contain the found string.
        $field_arr[$key] = true;
        //print_r($row_arr);
      }
    }
  }

  if (count($field_arr) == 0) {
    print " string not found.";
  } else {
    print " string found in field(s): " . implode(', ', array_keys($field_arr)) . "\n";
    foreach (array_keys($field_arr) as $field) {
      if ($field != "guid") {
        $query = "UPDATE $table SET $field = replace($field, '$find_string', '$replace_string') WHERE $field LIKE '%$find_string%'";
        update_table($query);
      } else {
        if ($replace_guid) {
          $query = "UPDATE $table SET $field = replace($field, '$find_string', '$replace_string') WHERE $field LIKE '%$find_string%'";
          update_table($query);
        } else {
          print "\nString found in guid field but not replacing. Override this by using the --replace_guid_field flag.\n";
        }
      }
    }
  }
}

function update_table($query) {
  print "\n$query\n";
  $result = mysql_query($query);
  $num_updated = mysql_affected_rows();
  print "... updated $num_updated records\n";
}
?&gt;</pre>
<p>The script is designed to be run from the command line.  Run the script by passing in the following options:</p>
<pre>php change-domain.php --db_name=&lt;your_db_name&gt; --db_user=&lt;db_login&gt; --db_pw=&lt;db_password&gt; --find_string=&lt;original_domain&gt; --replace_string=&lt;new_domain&gt; --replace_guid_field</pre>
<p>You can <a href="http://download.chiaocheng.com/code/change-domain.txt">download the script</a> but use at your own risk. If you do use it, I suggest you backup your database first.</p>
<p>Your php may not have the command line interpreter installed.  You&#8217;ll need the php5-cli package in order to run php from the shell.</p>
<pre>apt-get install php5-cli</pre>
<pre>&gt;&gt; dpkg --list |grep php
ii  libapache2-mod-php5              5.3.2-1ubuntu4.9                  server-side, HTML-embedded scripting languag
ii  php5-cli                         5.3.2-1ubuntu4.9                  command-line interpreter for the php5 script
ii  php5-common                      5.3.2-1ubuntu4.9                  Common files for packages built from the php
ii  php5-gd                          5.3.2-1ubuntu4.9                  GD module for php5
ii  php5-mysql                       5.3.2-1ubuntu4.9                  MySQL module for php5</pre>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2011/09/changing-a-wordpress-domain-name/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rosewill Metas external hard drive enclosure</title>
		<link>http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/</link>
		<comments>http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/#comments</comments>
		<pubDate>Sun, 04 Sep 2011 04:14:06 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[Gadgets]]></category>
		<category><![CDATA[enclosure]]></category>
		<category><![CDATA[review]]></category>
		<category><![CDATA[usb 3]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=428</guid>
		<description><![CDATA[&#160; My wife and I started using a shared network drive recently to store our collective media. To make this media portable, I decided to get the Rosewill Metas 3.5&#8243; external hard drive enclosure.  The Metas has both esata and &#8230; <a href="http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p style="text-align: left;"><a href="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas.jpg"><img class="aligncenter size-medium wp-image-439" title="rosewill_metas" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas-300x199.jpg" alt="" width="300" height="199" /></a>My wife and I started using a shared network drive recently to store our collective media. To make this media portable, I decided to get the Rosewill Metas 3.5&#8243; external hard drive enclosure.  The Metas has both esata and usb 3 support.  The e-sata will be used most of time as it&#8217;s connected to my NAS while the usb connector will mostly be used when it goes portable.</p>
<h1 style="text-align: left;">Quick Overview</h1>
<p>Plus</p>
<ul>
<li>Both esata and usb 3</li>
<li>Fan speed control</li>
<li>Vertical stand</li>
</ul>
<p>Minus</p>
<ul>
<li>Installing drive requires screw</li>
<li>Flimsy plastic clips hold both case and tray</li>
<li>noisy when laid flat due to lack of rubber feet on body</li>
</ul>
<h1 style="text-align: left;">Back panel</h1>
<ul>
<li>usb 3 type B connector</li>
<li>esata connector</li>
<li>power connector</li>
<li>power switch</li>
<li>variable fan speed control dial.</li>
</ul>
<p><img class="aligncenter size-medium wp-image-440" title="Rosewill Metas back panel" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_back_panel-300x199.jpg" alt="" width="300" height="199" /></p>
<p>The fan turned down all the way is pretty quiet but turned up all the way, it becomes very loud.  Fortunately you can adjust it to your liking.</p>
<h1>Included</h1>
<ul>
<li>1 36 inch esata cable</li>
<li>1 36 usb 3 cable (type a on one end, type b on the other)</li>
<li>1 power cable</li>
<li>1 vertical stand</li>
</ul>
<h1><a href="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_contents.jpg"><img class="aligncenter size-medium wp-image-443" title="Rosewill Metas box contents" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_contents-300x199.jpg" alt="" width="300" height="199" /></a>Inside the case</h1>
<p>There is one plastic clip which holds the lid in place.  While this clip feels very fragile, there is not a lot of force pushing against the lid.</p>
<p>Opening the lid reveals the internal fan which sits right below the lid and directly on the top of the hard drive.  While the fan is 80mm, it&#8217;s much thinner which means you won&#8217;t be able to replace it with a normal 80mm computer fan.</p>
<p><a href="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_open.jpg"><img class="aligncenter size-medium wp-image-444" title="Rosewill Metas fan" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_open-300x199.jpg" alt="" width="300" height="199" /></a></p>
<p>The hard drive and tray slides out towards the front of the case once the lid is open.  There are two flimsy plastic tabs next to the fan which are suppose to lock the tray and drive in place but unfortunately does not do a good job of it.  Putting a little pressure on the tray, I can feel it wiggle side to side.  My guess is that they wanted to allow you to easily remove the hard drive without tools.  The only problem is that the hard drive must be screwed onto the tray as shown below.  Since a screw driver is going to be needed anyways, it makes the ability to pull out the tray quickly to be quite useless.</p>
<p style="text-align: center;"><a href="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_tray.jpg"><img class="size-medium wp-image-446" title="Rosewill Metas tray underside" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_tray-300x199.jpg" alt="" width="300" height="199" /></a><a href="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_open_apart.jpg"><img class="size-medium wp-image-445" title="Rosewill Metas tray out" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_open_apart-300x199.jpg" alt="" width="300" height="199" /></a></p>
<h1> Hard drive activity indicator</h1>
<p><a href="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_blue_light.jpg"><img class="aligncenter size-medium wp-image-441" title="Rosewill Metas hard drive activity indicator" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_blue_light-300x199.jpg" alt="" width="300" height="199" /></a></p>
<h1>Physical features</h1>
<p>The top, front and back are black plastic with the exception of the top fan intake grate which is a thin piece of metal.  The bottom and sides is silver and metal.</p>
<h1>Vertical Stand recommended</h1>
<p>Another problem with the enclosure is the lack of rubber feet on the metal underside. Because of this, the enclosure vibrates against my desk as my 7200 rpm drive spins up. To keep it quiet, I had to use the vertical stand which does have rubber feet. If you wanted to put it flat, I would have to recommend a different enclosure or to go out and buy some rubber feet.</p>
<p><img class="aligncenter size-medium wp-image-447" style="border-style: initial; border-color: initial;" title="Rosewill Metas vertical stand" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_vertical_stand-300x199.jpg" alt="" width="300" height="199" /></p>
<h1>Summary</h1>
<p>If you want both usb 3 and esata, then this enclosure is a good choice.  Quite frankly, there are not a lot of other choices out there.  But this enclosure is nice and I feel confident that if there were more choices, this enclosure would still be in the top.  There are definitely small areas for improvement but nothing major.</p>
<p>Since I got the metas, Rosewill upgraded their RX models from usb 2 to usb 3.  At this point, I would also consider getting the RX-358 U3C SLV which has a lower price point.</p>
<div>

<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas/' title='Rosewill Metas'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas" title="Rosewill Metas" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_vertical_stand/' title='Rosewill Metas vertical stand'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_vertical_stand-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas vertical stand" title="Rosewill Metas vertical stand" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_back_panel/' title='Rosewill Metas back panel'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_back_panel-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas back panel" title="Rosewill Metas back panel" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_contents/' title='Rosewill Metas box contents'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_contents-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas box contents" title="Rosewill Metas box contents" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_open/' title='Rosewill Metas fan'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_open-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas fan" title="Rosewill Metas fan" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_open_apart/' title='Rosewill Metas tray out'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_open_apart-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas tray out" title="Rosewill Metas tray out" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_tray/' title='Rosewill Metas tray underside'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_tray-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas tray underside" title="Rosewill Metas tray underside" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_blue_light/' title='Rosewill Metas hard drive activity indicator'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_blue_light-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas hard drive activity indicator" title="Rosewill Metas hard drive activity indicator" /></a>
<a href='http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/rosewill_metas_box/' title='Rosewill Metas retail box'><img width="150" height="150" src="http://www.chiaocheng.com/wp-content/uploads/2011/09/rosewill_metas_box-150x150.jpg" class="attachment-thumbnail" alt="Rosewill Metas retail box" title="Rosewill Metas retail box" /></a>

<p>&nbsp;</p>
<p>&nbsp;</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2011/09/rosewill-metas-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remove url / website from wordpress comments</title>
		<link>http://www.chiaocheng.com/blog/2011/08/wordpress-remove-comment-url/</link>
		<comments>http://www.chiaocheng.com/blog/2011/08/wordpress-remove-comment-url/#comments</comments>
		<pubDate>Tue, 23 Aug 2011 09:47:37 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[spam]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=414</guid>
		<description><![CDATA[Holy spam bots Batman! I finally got fed up with comment spam on my wordpress blog.  To help solve my problem, I decided to remove all the the url / website values for comments in my blog.  It seems like &#8230; <a href="http://www.chiaocheng.com/blog/2011/08/wordpress-remove-comment-url/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><em>Holy spam bots Batman!</em></p>
<p>I finally got fed up with comment spam on my wordpress blog.  To help solve my problem, I decided to remove all the the url / website values for comments in my blog.  It seems like the most popular use of the author url value in a comment is for spam.  In fact, I would say over 90% of all my comments containing an author url is some form of ad spam. For these cases, the author url usually links to some random site with no relevant content. On the other hand, almost all my readers who post legitimate comments do not bother putting in a comment author url.</p>
<p>So I decided the author url is useless and decided take aggresive action against it:</p>
<ol>
<li>remove the url field from the comment form</li>
<li>prevent comment posts with author url in it</li>
<li>remove urls for existing comments</li>
<li>remove comments which contained random author urls which has a slight hint of being spam.</li>
</ol>
<h1>Customize the comment form</h1>
<p>To remove the url or website field from the comment form, you can customize the wordpress comment form by adding a filter and using the &#8220;comment_form_default_fields&#8221; hook. Go into your theme and find all usages of the function comment_form().  Before each usage, add the following filter:</p>
<pre>    &lt;?php
      function remove_url_field($fields) {
        unset($fields['url']);
        return $fields;
      }
      add_filter('comment_form_default_fields', 'remove_url_field')
    ?&gt;

    &lt;?php comment_form(); ?&gt;</pre>
<p>I&#8217;m using the default twenty-eleven theme and the above appears in comments.php.</p>
<h1>Validate server comment post</h1>
<p>Customizing the comment form is great for your users but it will not make a bit of difference for spam bots.  Spam bots can post comments directly to your wordpress and bypass the form directly.  Because of this, you need to add validation to the php file that accepts comments.  Inside wp-comments-post.php, find the following lines of code (should be somewhere near the middle of the file):</p>
<pre>$comment_author       = ( isset($_POST['author']) )  ? trim(strip_tags($_POST['author'])) : null;
$comment_author_email = ( isset($_POST['email']) )   ? trim($_POST['email']) : null;
$comment_author_url   = ( isset($_POST['url']) )     ? trim($_POST['url']) : null;
$comment_content      = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null;</pre>
<p>Put the following if statement right after:</p>
<pre>if ($comment_author_url) {
   wp_redirect('/');
   exit;
}</pre>
<p>This will redirect anyone who submits a comment author url back to the main page.  This should only affect bots which bypassed your form since it will not realize you do not have a url input anymore.</p>
<p><span class="Apple-style-span" style="color: #000000; font-weight: bold;">Remove existing author url</span></p>
<p>Finally, remove the existing urls from the mysql database.  The urls are stored in wp_comments in the comment_author_url field.</p>
<pre>mysql&gt; update wp_comments set comment_author_url = '';</pre>
<h1>Notes</h1>
<p>The above changes were performed on wordpress 3.2.1.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2011/08/wordpress-remove-comment-url/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Ideal home network</title>
		<link>http://www.chiaocheng.com/blog/2010/05/ideal-home-network/</link>
		<comments>http://www.chiaocheng.com/blog/2010/05/ideal-home-network/#comments</comments>
		<pubDate>Tue, 18 May 2010 08:13:28 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[file server]]></category>
		<category><![CDATA[nas]]></category>
		<category><![CDATA[network]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=314</guid>
		<description><![CDATA[I&#8217;ve been thinking about home networking a lot lately.  Specifically a network attached storage (NAS), or basically a shared hard drive on the network. Why&#8230; No, it&#8217;s not because I love technology or gadgets or because I&#8217;m geeky like that.  &#8230; <a href="http://www.chiaocheng.com/blog/2010/05/ideal-home-network/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been thinking about home networking a lot lately.  Specifically a network attached storage (NAS), or basically a shared hard drive on the network.</p>
<h2>Why&#8230;</h2>
<p>No, it&#8217;s not because I love technology or gadgets or because I&#8217;m geeky like that.  Actually, it&#8217;s mostly because I&#8217;m not living by myself anymore.  All problems associated with computer files (e.g. backup, drive crash, computer crash, blue screens, no screen, defrag, crash without saving, power fail without saving, backup, out of space, too slow, too messy, security, mobility, restore, backup, sync, transfers, sharing, duplication, backup) that I normally have is now multiplied by two.  And this translates to bad things happening twice as often.</p>
<h2>The ideal solution</h2>
<p>Put all files on a shared network drive which is fast and backed up.  Then have nothing on the local computer except for applications.  This has a lot of advantages and a couple disadvantages.</p>
<h3>Advantages</h3>
<ul>
<li>Automatically backed up for anyone on the network.</li>
<li>Hard drive space efficiency.  Some people use a lot of space and some people use a little.  Having all All free drive space pooled together allowed it to be shared so in the long run, you probably save money on hard drives.</li>
<li>Share files without needing to email or copy them to a flash drive.</li>
<li>Centralized maintenance and enhancement.  An improvement on the network share is automatically realized by everyone using it.</li>
</ul>
<h3>Disadvantages</h3>
<ul>
<li>If you travel a lot, then synchronizing the files to your mobile drive can be a pain.</li>
<li>Potentially slower.  With the same exact hardware, a file loaded from a network drive cannot be faster than a file loaded from the local drive.</li>
</ul>
<p>Since I do not travel a lot, the only disadvantage for me is the performance.  Which bring me back to how I started&#8230; I&#8217;ve been thinking about home networking a lot lately, mostly about what kind of speed I can expect from a NAS.</p>
<h2>Speed</h2>
<p>To get a rough idea of how fast I can transfer a file from a NAS to a computer, I have to understand the performance of all components on the transfer path.   Each person may have a different computer or and different usages so the transfer path will be different for each situation.  The fastest transfer speed will be determined by the slowest component (bottleneck) on the path.  I found numbers that were all normalized to megabytes (MB) per second and plotted them from slowest to fastest.</p>
<p>&nbsp;</p>
<p><a href="http://www.chiaocheng.com/wp-content/uploads/2010/05/speed_chart.png"><img class="size-large wp-image-339 alignnone" style="border: 1px solid black;" src="http://www.chiaocheng.com/wp-content/uploads/2010/05/speed_chart-1024x293.png" alt="performance chart" width="1024" height="293" /></a></p>
<p>The chart above gives a pretty good idea of what really matters during a file transfer.  For example, if you were trying to copy something to a usb 1.1 device, then it doesn&#8217;t matter how fast your network, or network drive is, the usb device is going to be too slow anyways.</p>
<p>Ideally, if I can make my gigabit wired network the slowest component in my transfer path, that would be pretty darn good.  A single hard drive would only acheive roughly 70 MB/s which is not enough to keep up with a 125 MB/s gigabit network.  To get network saturation, it looks like a hard drive in raid 0 or raid 5 configuration may be warranted.</p>
<ul>
<li>7200 rpm hard drive [~70 MB/s]</li>
<li>7200 rpm hard drives with raid 0 [~140 MB/s]</li>
<li>pata UDMA/100 (ide) [~100 MB/s]</li>
<li>pata UDMA/133 (ide) [~133 MB/s]</li>
<li>1.5 Gb/s sata connection [~150 MB/s]</li>
<li>3 Gb/s sata connection [~300 MB/s]</li>
<li>wired 100 Mb network / 100 Mb switch [~12.5 MB/s]</li>
<li>wired gigabit network/ gigabit switch [~125 MB/s]</li>
<li>wireless 802.11a [~6.75 MB/s]</li>
<li>wireless 802.11b [~1.4 MB/s]</li>
<li>wireless 802.11g [~6.75 MB/s]</li>
<li>wireless 802.11n [~37.5 MB/s]</li>
<li>usb 2.0 [~60 MB/s]</li>
<li>usb 3.0 [~625 MB/s]</li>
<li>firewire [~98.3 MB/s]</li>
</ul>
<pre>MB = megabyte, mb = megabit, 8 megabit (mb) = 1 megabyte (MB)</pre>
<h2>Increase total throughput with link aggregation</h2>
<p>Some motherboards and routers support IEEE 802.3ad, also known as link aggregation, dual lan and teaming.  The theory behind this is that two lan ports can be paried up on a single ip to accept connections and therefore handle more throughput than a single ethernet cable.  Think of this like a load balancer for web servers.  It won&#8217;t really increase the speed of a single request but can allow the network to handle more requests, thus increasing total throughput.</p>
<p><a href="http://en.wikipedia.org/wiki/Link_aggregation">http://en.wikipedia.org/wiki/Link_aggregation</a></p>
<p>I have read a few forums now and it is still unclear to me whether link aggregation works in practice.   Increased transfer rate  for a single connection seems unlikely unless there is a way to over-come the overhead in dealing with out of order packets.  But even without increase transfer rate for a single connection, load balancing multiple connections should help in a multi-user environment.  For now the only thing that people appear to agree on is that it does provide network redundancy which is something I&#8217;m not interested in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2010/05/ideal-home-network/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Turtle pond design</title>
		<link>http://www.chiaocheng.com/blog/2010/05/turtle-pond-design/</link>
		<comments>http://www.chiaocheng.com/blog/2010/05/turtle-pond-design/#comments</comments>
		<pubDate>Tue, 11 May 2010 02:07:08 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[DIY]]></category>
		<category><![CDATA[pond]]></category>
		<category><![CDATA[red ear slider]]></category>
		<category><![CDATA[sketchup]]></category>
		<category><![CDATA[turtle]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=287</guid>
		<description><![CDATA[I&#8217;m close to getting a backyard which is one step closer to my three red ear sliders&#8217; dream house, &#8230; a turtle pond, or what I like to call a turtle oasis!  How close they come to realizing their dream living condition &#8230; <a href="http://www.chiaocheng.com/blog/2010/05/turtle-pond-design/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m close to getting a backyard which is one step closer to my three red ear sliders&#8217; dream house, &#8230; a turtle pond, or what I like to call a turtle oasis!  How close they come to realizing their dream living condition depends greatly on my craftsmanship.  To get a rough idea of what I want my turtle pond to look like, I loaded up Google sketchup and viola!&#8230;</p>
<p><img class="size-large wp-image-289 alignnone" src="http://www.chiaocheng.com/wp-content/uploads/2010/05/turtle-pond-wood-1024x642.jpg" alt="Turtle pond design" width="1024" height="642" /></p>
<h2>Components</h2>
<p>My first design had used a lot more cinder blocks around the pond as walls but my wife was not too happy about that.  Considering how often she bumps into furniture, she had a valid concern.  So this is actually my second design which has a lot more wood than the first.  The frame is now entirely wood with cinder blocks only being used as the underlying foundation for the pool and dirt.  The dimensions for the pond are based around the size of the kiddie pool in the middle (which I already bought!).  The empty space around the pool will be filled with dirt and plants.</p>
<ul>
<li>2 x 10 wood board</li>
<li>2 x 2 wood beams</li>
<li>54&#8243; diameter kiddie pool</li>
<li>chicken wire</li>
<li>cinder blocks</li>
<li>plexi-glass</li>
<li>dirt</li>
<li>plants (imagine foerster feather grass swaying in the breeze!  awesome!)</li>
</ul>
<p><img class="size-large wp-image-290 alignnone" src="http://www.chiaocheng.com/wp-content/uploads/2010/05/turtle-pond-wood1-1024x642.jpg" alt="Turtle pond design apart" width="1024" height="642" /></p>
<h2>Features</h2>
<h3>Pond drain&#8230;</h3>
<p>One thing I have learned in my years of experience with fish and now turtles, is that a easy way to change the water is absolutely essential.  A good filter will take you a long way but eventually the water will need to be changed either in part or in full.  Years before, I figured out that I can replace one side of my 10 gallon fish tank with plexi-glass.  This allowed me to cut a hole at the bottom and plug it with a valve (I chose an opening of a 2 liter plastic soda bottle).  It greatly increased the speed that I was able to replace the water.  Now, I hope I can apply the same concept to my pool.  I plan on cutting a hole at the bottom of the pool and attaching a valve and hose to let the water out.  The pool will be slightly raised on a layer of cinder block and gravity allow the water to be drained.</p>
<h3>Protective fencing&#8230;</h3>
<p>I heard that turtles can be attacked by common animals such as cats, squirrels, and birds.  Considering my turtles have always lived indoors and are most likely extremely domesticated, I doubt they have the instinct to hide if approached.  To protect them, I will need to wrap the entire pond in a protective fence, chicken wire (not pictured).</p>
<h3>Heated pool&#8230;</h3>
<p>This is the tricky one and will be the biggest hurdle.  I am not sure how feasible it will be to maintain my pond at a livable temperature.  If I cannot heat the pond at a reasonable cost, I may have to give up on the dream oasis completely!  Oh no!  The kiddie pool is roughly 100 gallons and I know they sell aquarium heaters that can easily handle that indoors.  It will be much colder outdoors so I am not sure if they will work.  Hopefully I can find a cost effective way to keep them warm.  Everyone has to live within their means, even my turtles.  In the worst case, I keep them in the house with a larger tank now that there is more space.  I am keeping my fingers crossed!</p>
<h3>Sun-roof&#8230;</h3>
<p>Well, this one is still under debate.  Does my pond really need a roof?  I think my turtles will do just fine with a bit of rain but keeping rain out will probably make heating easier.  If I do make a roof, then it would have to be glass or plexi-glass for sure.  Turtles need uv light and heat so I have to allow as much sun in as possible.</p>
<h3>Giant Doors&#8230;</h3>
<p>Remember the fencing?  I have to have access to the pond of course!  So the top frame of the turtle enclosure will have a set of doors bigger than my house doors!  Ok, that was an exaggeration but they will be pretty darn big.</p>
<h3>Convertible&#8230;</h3>
<p>So I got doors, but why stop there!  That&#8217;s right, I&#8217;m sparing no expenses** on this turtle resort.  For even more access in cases of major landscaping or pond cleaning, the entire top frame will be detachable as shown in the picture.  This will give completely 360 degree access to anything in my pond.</p>
<p><span style="color: #999999">** Actually not true.  I will most likely be on the strictest of budgets.  Approved and audited closely by my CFO (a.k.a. my wife).</span></p>
<h3><span style="color: #000000">Filter&#8230;</span></h3>
<p><span style="color: #000000">To help conserve water, a filter is a must.  100 gallons of water is a decent amount of water so it&#8217;s important to use it for as long as possible.  I am hoping that a good filter can keep the pond clean for a couple months before a partial water change. </span></p>
<h2><span style="color: #000000">Cost?</span></h2>
<p><span style="color: #000000">I have not done a cost calculation yet but it looks like this project is going to be a few hundred bucks at the minimum.  The cost may delay this project but since I already have the kiddie pool, it&#8217;s no longer a matter of &#8221;if&#8221; but just a matter &#8221;when&#8221;.</span></p>
<p><span style="color: #000000"> </span></p>
<address><span style="color: #000000">BTW&#8230; Google sketchup&#8230; you rock!  The nice design images above were done in sketchup.</span></address>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2010/05/turtle-pond-design/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Battlefield Bad Company 2: thoughts</title>
		<link>http://www.chiaocheng.com/blog/2010/03/battlefield-bad-company-2-thoughts/</link>
		<comments>http://www.chiaocheng.com/blog/2010/03/battlefield-bad-company-2-thoughts/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 08:20:31 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[Games]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=281</guid>
		<description><![CDATA[Bad Company 2 has finally been released. Since I passed on Modern Warfare, I hoped that Bad Company 2 would be everything I wanted.  As reviews for the game came out, I realized that at least one aspect of the &#8230; <a href="http://www.chiaocheng.com/blog/2010/03/battlefield-bad-company-2-thoughts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: center"><img class="size-full wp-image-282 aligncenter" src="http://www.chiaocheng.com/wp-content/uploads/2010/03/battlefield-bad-company-2.jpg" alt="battlefield-bad-company-2" width="490" height="347" /></p>
<p>Bad Company 2 has finally been released.  Since I passed on Modern Warfare, I hoped that Bad Company 2 would be everything I wanted.   As reviews for the game came out, I realized that at least one aspect of the game did not meet my expectations.  But overall, it appears that the game got good reviews and most importantly it does not have any deal breakers for me.</p>
<h2>The Bad</h2>
<p>Before the game was released, I had see online reports that Bad Company 2 was going to support up to 40 players on the PC.  But unfortunately, it seems like the game only supports 32 players now.  Even though this is still better than the measly 18 players for Modern Warfare 2, I am still disappointed that it&#8217;s not 40 players.</p>
<h2>The Good</h2>
<p>Destruction, destruction, destruction.  Can&#8217;t really say this enough because almost everything can be destroyed in the game.  No words can do this justice so just go out and find a video where you can see this happen!</p>
<p>Although 32 players are not as good as my expected 40 or 64 from other Battlefield games, I will give this game credit for increasing the number of players for the PC.  The xbox and playstation versions of the game are limited to 24 players which is too bad.  But understanding that the PC can handle more and actually using that power is just a smart move on the developer and should keep the PC gamers, including me, happy.</p>
<h2>Conclusion</h2>
<p>I will be giving this game a go as soon as soon as I get my new graphics card.  I&#8217;ll see you on the battlefield solder!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2010/03/battlefield-bad-company-2-thoughts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linux remote screen lock</title>
		<link>http://www.chiaocheng.com/blog/2009/12/linux-remote-screen-lock/</link>
		<comments>http://www.chiaocheng.com/blog/2009/12/linux-remote-screen-lock/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 02:45:03 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[screen saver]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[x11]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=274</guid>
		<description><![CDATA[You can activate your linux screen saver or screen lock by running this command: gnome-screensaver-command --lock or xlock But if you ssh into your linux machine to activate the screen lock or screen saver, you might run into this error: &#8230; <a href="http://www.chiaocheng.com/blog/2009/12/linux-remote-screen-lock/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>You can activate your linux screen saver or screen lock by running this command:</p>
<pre>gnome-screensaver-command --lock</pre>
<p>or</p>
<pre>xlock</pre>
<p>But if you ssh into your linux machine to activate the screen lock or screen saver, you might run into this error:</p>
<pre>** Message: Failed to connect to the D-BUS daemon: dbus-launch failed to
autolaunch D-Bus session: Autolaunch error: X11 initialization failed.</pre>
<p>or</p>
<pre>No protocol specified
xscreensaver: Can't open display: :0.0</pre>
<p>You have to set the DBUS_SESSION_BUS_ADDRESS environment variable in order the command to work.  You can find the current running DBUS address by first getting the process id of the running screen saver.  Then grepping for the address in the environ file.  The following script will lock your linux terminal:</p>
<pre>#!/bin/sh

PID=`pgrep -u $USER -f "gnome-screensaver"`
DBUS_SESSION_BUS_ADDRESS=`grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ`
DBUS_SESSION_BUS_ADDRESS=`echo $DBUS_SESSION_BUS_ADDRESS | sed -e 's/DBUS_SESSION_BUS_ADDRESS=//'`
export DBUS_SESSION_BUS_ADDRESS

gnome-screensaver-command --lock</pre>
<p>Holy remote locking Batman!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2009/12/linux-remote-screen-lock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modern Warfare 2: Released but not recommended</title>
		<link>http://www.chiaocheng.com/blog/2009/11/modern-warfare-2-released-but-not-recommended/</link>
		<comments>http://www.chiaocheng.com/blog/2009/11/modern-warfare-2-released-but-not-recommended/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 20:43:23 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[doa]]></category>
		<category><![CDATA[fps]]></category>
		<category><![CDATA[recommendation]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=254</guid>
		<description><![CDATA[I have been urging to get my hands on a new FPS (first person shooter) game for a while now since my main FPS is the super old Battlefield 2 game! I thought about getting Modern Warfare 1 but I noticed &#8230; <a href="http://www.chiaocheng.com/blog/2009/11/modern-warfare-2-released-but-not-recommended/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have been urging to get my hands on a new FPS (first person shooter) game for a while now since my main FPS is the super old Battlefield 2 game! I thought about getting Modern Warfare 1 but I noticed both Modern Warfare 2 and Bad Company 2 were coming out soon. I decided to wait and see.</p>
<p><img class="size-full wp-image-270 alignright" src="http://www.chiaocheng.com/wp-content/uploads/2009/11/mw2logo.png" alt="mw2logo" width="202" height="39" />Well today Modern Warfare 2 has been released! So I decided to poke around the internet to see what the word is. And my verdict is&#8230; not recommended.  I have decided that I will not buy Modern Warfare 2 based on two main deal breakers.</p>
<h2>Deal breaker #1: 18 player limit</h2>
<p>Say what!  That&#8217;s right, it appears that Modern Warfare 2 is limited to 18 players.  Not 18 players on each side, but 18 players total, that&#8217;s 9v9 tops.  Personally, I love playing with a huge number of players because it just feels more like the scenes from the movie Saving Private Ryan.  And I think that&#8217;s awesome.  I love the concept of organized chaos which is what you get from 32 or 64 players duking it out while sub-dividing into miniature rambo teams.  With a maximum of 9 players on your side, half of them may be dead at any one time so that really leaves you 4 guys running around at a time.</p>
<p>If you&#8217;re a console guy, then you&#8217;re probably saying what&#8217;s the big deal?  And I would say it&#8217;s not a big deal to you.  For console games, this is pretty much the norm and this is what you expect.  More power to you.  But I am personally a PC guy and I am accustom to games that support up to 64 players.</p>
<h2>Deal breaker #2: no dedicated servers</h2>
<p>Initially I didn&#8217;t even know what this meant.  This basically means Infinity Ward, the creators of the game, will not have any game servers setup for people to play on.  The game is designed to be hosted directly on one of the client&#8217;s or player&#8217;s machines.  So yes, one lucky player in a given game will be hosting the game.  Based on my experience with FPS games and ping, this may give an unfair advantage to the player hosting the game as his ping will be virtually zero.  I have on many occassions, when my ping was super low, been able to defy death, almost in an omni-potent way, seen hoards of enemy shooting at me but always missing, as if they were targeting thin air.</p>
<h2>Conclusion</h2>
<p>A good summary is the title I have been seeing around the internet&#8230; Modern Warfare 2, DOA.  For those who are unfamiliar with that acronym, it stands for dead on arrival and is a common phrase seen when purchasing computer hardware.</p>
<p>Check out the funny ratings from <a title="GameSpot" href="http://www.gamespot.com/pc/action/modernwarfare2/players.html?tag=player-reviews;header;more" target="_blank">GameSpot</a> and <a title="IGN" href="http://pc.ign.com/objects/142/14280895.html" target="_blank">IGN</a>.</p>
<div id="attachment_266" class="wp-caption aligncenter" style="width: 410px"><img class="size-full wp-image-266" src="http://www.chiaocheng.com/wp-content/uploads/2009/11/modern-warfare-2-rating1.gif" alt="Ratings from GameSpot and IGN" width="400" height="400" /><p class="wp-caption-text">Ratings from GameSpot and IGN</p></div>
<p>For now, I will be waiting for Bad Company 2.  While I have read that it can support a maximum of 40 players, the game is still to a bit too far from release to know for sure.  So hopefully it won&#8217;t let me down.  If it does, well there is always Modern Warfare 1.</p>
<p>Finally, here are some direct quotes that made me laugh (disclaimer: quotes do not necessarily represent the author&#8217;s opinions):</p>
<ul>
<li>Take $60 out and burn it&#8230;least you get warm -zippythezip (GameSpot)</li>
<li>it&#8217;s like mw but then crippled -ATFNeOpHyTe (GameSpot)</li>
<li>Screw you consoles!!!!!!! -ZeppelinE6 (GameSpot)</li>
<li>outside of consoles this game is already DOA -doorules (IGN)</li>
<li>If I wanted to play 9 vrs 9 on small maps I would just reinstall my old Doom disks. -jdwksu (IGN)</li>
<li>Complete and utter failure, a 10 year step back in PC gaming -Liksecken (GameSpot)</li>
</ul>
<p>Holy bad PR, Batman!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2009/11/modern-warfare-2-released-but-not-recommended/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>WordPress: No Page comments</title>
		<link>http://www.chiaocheng.com/blog/2009/07/wordpress-no-page-comments/</link>
		<comments>http://www.chiaocheng.com/blog/2009/07/wordpress-no-page-comments/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 00:45:42 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=213</guid>
		<description><![CDATA[It seems like the &#8220;Allow Comments&#8221; option on the &#8220;Add new page&#8221; screen does not work in wordpress.  Specifically, it does not work for the default theme Kubrick. Seeing this option, it&#8217;s easy to assume this enables comments on your &#8230; <a href="http://www.chiaocheng.com/blog/2009/07/wordpress-no-page-comments/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It seems like the &#8220;Allow Comments&#8221; option on the &#8220;Add new page&#8221; screen does not work in wordpress.  Specifically, it does not work for the default theme Kubrick.</p>
<div id="attachment_215" class="wp-caption alignnone" style="width: 540px"><img class="size-full wp-image-215" src="http://www.chiaocheng.com/wp-content/uploads/2009/07/wordpress-allow-discussion.png" alt="Allow comments option" width="530" height="113" /><p class="wp-caption-text">Allow comments option</p></div>
<p>Seeing this option, it&#8217;s easy to assume this enables comments on your wordpress Pages, especially for the default theme.  But unfortunately, this particular option in the admin page has no affect on the default Kubrick theme.  To enable comments on your Page(s), you have to select a theme which includes them or modify your default Kubrick theme.</p>
<h2>Default theme with page comments</h2>
<p>To change your default theme, add the following line to <code>/wp-content/themes/default/page.php</code></p>
<p><!--no-encode--></p>
<pre>&lt;?php
/**
 * @package WordPress
 * @subpackage Default_Theme
 */

get_header(); ?&gt;

    &lt;div id="content" class="narrowcolumn"&gt;

        &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;
        &lt;div class="post" id="post-&lt;?php the_ID(); ?&gt;"&gt;
        &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;
            &lt;div class="entry"&gt;
                &lt;?php the_content('&lt;p class="serif"&gt;Read the rest of this page &amp;raquo;&lt;/p&gt;'); ?&gt;

                &lt;?php wp_link_pages(array('before' =&gt; '&lt;p&gt;&lt;strong&gt;Pages:&lt;/strong&gt; ', 'after' =&gt; '&lt;/p&gt;', 'next_or_number' =&gt; 'number')); ?&gt;

            &lt;/div&gt;
        &lt;/div&gt;
        &lt;?php endwhile; endif; ?&gt;
    &lt;?php edit_post_link('Edit this entry.', '&lt;p&gt;', '&lt;/p&gt;'); ?&gt;

    &lt;?php comments_template(); ?&gt;
    &lt;/div&gt;

&lt;?php get_footer(); ?&gt;</pre>
<h2>Additional References</h2>
<p><a href="http://wordpress.org/support/topic/246879" target="_blank">http://wordpress.org/support/topic/246879</a></p>
<p><a href="http://wordpress.org/support/topic/196788" target="_blank">http://wordpress.org/support/topic/196788</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2009/07/wordpress-no-page-comments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Singleton</title>
		<link>http://www.chiaocheng.com/blog/2009/07/java-singleton/</link>
		<comments>http://www.chiaocheng.com/blog/2009/07/java-singleton/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 06:43:44 +0000</pubDate>
		<dc:creator>chiao</dc:creator>
				<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.chiaocheng.com/?p=386</guid>
		<description><![CDATA[After going through a couple job interviews, I quickly realized that there are many differing &#8220;opinions&#8221; (yes even among seasoned Java programmers) about the best way to initialize a singleton class. For the record, there are really only two fundamental &#8230; <a href="http://www.chiaocheng.com/blog/2009/07/java-singleton/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>After going through a couple job interviews, I quickly realized that there are many differing &#8220;opinions&#8221; (yes even among seasoned Java programmers) about the best way to initialize a singleton class. For the record, there are really only two fundamental ways of initializing a singleton properly in java: eager or lazy. Then there is a neat trick to try to get the best of both worlds so that makes a total of three. Depending on the person you talk to, one of these methods may be preferred over the others but all three listed below are thread safe.</p>
<h2>Eager Initialization</h2>
<p>In eager initialization, the singleton is instantiated when the programs starts whether or not it gets used. The problem with this approach is that valuable resources are allocated whether or not they ever get used. If the singleton has a large memory footprint, this may not be a good choice.</p>
<p>Example 1. Eager Initialization</p>
<pre class="brush: java; highlight: [4]">public class Singleton {

    // Eager initialization happens here.
    static private Singleton instance = new Singleton();

    // Prevent instantiation by public.
    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
}</pre>
<p>Eager initialization relies on the fact that the JVM will initialize the class members upon loading the class. And the class is loaded when it is first referenced.</p>
<h2>Lazy Initialization</h2>
<p>On the other end of the spectrum, we have lazy initialization which the object only get instantiated on the first time the getInstance() method is called. This has the advantage of not allocating the resources unless it is actually needed.</p>
<p>The problem with this approach is that the getInstance() method needs to be synchronized. Therefore there is a performance hit when acquiring the singleton.</p>
<p>Example 2. Lazy Initialization</p>
<pre class="highlight: [9]; brush:java;">public class Singleton {

    static private Singleton instance = null;

    // Prevent instantiation by public.
    private Singleton() {
    }

    synchronized public static Singleton getInstance() {
        if (instance == null) {
            // Lazy initialization happens here
            // on the first call to this method.
            instance = new Singleton();
        }
        return instance;
    }
}</pre>
<p>Do not try to circumvent the synchronized method by using a DCL (double check locking) mechanism as it does not work with the java memory model. Read more about that by following the resources links below.</p>
<h2>Initialize-on-demand holder class idiom</h2>
<p>There is one final way to get the best of both worlds and that is to use &#8220;Initialize-on-demand holder class&#8221; idiom which can be found in &#8220;Effective Java&#8221; by Joshua Bloch. This method relies on the JVM only intializing the class members upon first reference to the class. In this case, we have a inner class that is only referenced within the getInstance() method. This means SingletonHolder will get initialized on the first call to getInstance().</p>
<p>Example 3. Initialize-on-demand</p>
<pre class="brush: java">public class Singleton {

    // Prevent instantiation by public.
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    } 

    /**
     * Singleton implementation helper.
     */
    private static class SingletonHolder {
        // This gets initialized on first reference
        // to SingletonHolder.
        static final Singleton instance = new Singleton();
    }
}</pre>
<p>Now the singleton object will not get allocated until it is used and we did not need to incur the overhead of a synchronized method call.</p>
<p>Happy programming,<br />
Chiao</p>
<p>References and Resources</p>
<ul>
<li><a href="http://www.javaworld.com/jw-02-2001/jw-0209-double.html">Fixing the Java Memory Model, Part 2</a></li>
<li><a href="http://www.javaworld.com/jw-02-2001/jw-0209-double.html">Double-checked locking: Clever, but broken</a></li>
<li><a href="http://www.theserverside.com/patterns/thread.tss?thread_id=17614">Revisiting Singleton Pattern</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.chiaocheng.com/blog/2009/07/java-singleton/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

