<?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>Java Tuning &#187; memory</title>
	<atom:link href="http://www.javatuning.com/category/memory/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javatuning.com</link>
	<description>Software Development, Java, and some more.</description>
	<lastBuildDate>Tue, 29 Jun 2010 10:29:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Myth busting &#8211; String.intern() object allocations are never garbage collected</title>
		<link>http://www.javatuning.com/myth-busting-string-intern-object-allocations-are-never-garbage-collected/</link>
		<comments>http://www.javatuning.com/myth-busting-string-intern-object-allocations-are-never-garbage-collected/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 16:07:29 +0000</pubDate>
		<dc:creator>Gili Nachum</dc:creator>
				<category><![CDATA[memory]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[multithreading]]></category>

		<guid isPermaLink="false">http://www.javatuning.com/?p=212</guid>
		<description><![CDATA[Java is becoming quite old (version 1.0 came out in 1996 if I&#8217;m not mistaken). When something turns old, legends, myths, and other perceived truths are quick to form around it (just imagine an old Gothic mansion with its stack of scare tales). Most of the accumulated knowledge is beneficial and helpful, but some of [...]]]></description>
			<content:encoded><![CDATA[<p>Java is becoming quite old (version 1.0 came out in 1996 if I&#8217;m not mistaken). When something turns old, legends, myths, and other perceived truths are quick to form around it (just imagine an old Gothic mansion with its stack of scare tales).<br />
Most of the accumulated knowledge is beneficial and helpful, but some of it is not relevant anymore or just plain wrong.<br />
Remembering that Java is 14 yeas old (2010), when I google for something, for Java info/answers, I always inspect the date of the article I landed on.<br />
If you stumble upon somebody claiming that java can/can&#8217;t do something, always check his comment&#8217;s date. If I see something from 2001, you better search for newer references, instead of accepting it as is.</p>
<p><img class="alignleft size-thumbnail wp-image-216" title="old-woman-748479" src="http://www.javatuning.com/wp-content/uploads/2010/01/old-woman-748479-150x150.jpg" alt="old" width="150" height="150" />Some sites like <a href="http://Javaworld.com">http://Javaworld.com</a>, have been there from the get go, were big then, but after losing popularity, are now a grave yard for old Java skeletons (I myself have a not that relevant <a href="http://www.javaworld.com/javaworld/jw-12-2006/jw-1201-dst.html">article there).</a></p>
<p>The story with String.intern() is the same, you&#8217;ll find people all around the place, claiming that over using it will finish up the perm area, because the perm area is never garbage collected. As discussed <a href="http://stackoverflow.com/questions/1091045/is-it-good-practice-to-use-java-lang-string-intern/2012661#2012661">here</a>, that&#8217;s just not true.</p>
<p>Something I enjoy doing is not taking so called &#8220;facts&#8221; as granted, and re-validating on my IDE.<br />
Thinking that those intern() allocations will never be GCed, I was planing a presentation on how to use weakHashMap based solution can serve as an alternative cache repository for Strings, wrote a program to demonstrate an OMME caused by intern() only to find out that intern() is not so bad  as I originally thought.<br />
Try stuff yourself. You be surprised&#8230;</p>
<p>Other myths I&#8217;ll should wright about some day are:</p>
<ol>
<li><strong>Regular expressions in Java are slow &#8211; FALSE!</strong> I&#8217;ve tested this myself, and after compiling the regex, I was able to run over than 1 million matches per second (small strings of course).</li>
<li><strong>Always use StringBuffer to concatenate strings &#8211; dead wrong! </strong>if you have all concatenations in a single line, like the following, the compiler auto does it for you:<br />
s= <em>&#8220;Hi my name is: &#8220;+myName+ &#8220;. my lucky number is: &#8220;+num;</em><br />
Run Javap on a class file using and not using StringBuffer to see that the byte code is the same.<br />
Though this piece of code could benefit from StringBuffer to prevent rapid object creation:<br />
<em>for (&#8230;) {<br />
s += strOfThisCycle;<br />
}<br />
</em>In any case, Java5 introduces StringBuilder which is the unsynchronized tween of the synchronized StringBuffer class. I guess you will rarely access the same builder from different threads, therefore StringBuilder should be the default choice for ya.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.javatuning.com/myth-busting-string-intern-object-allocations-are-never-garbage-collected/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Why catch Throwable is evil &#8211; A real life story</title>
		<link>http://www.javatuning.com/why-catch-throwable-is-evil-real-life-story/</link>
		<comments>http://www.javatuning.com/why-catch-throwable-is-evil-real-life-story/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 23:25:38 +0000</pubDate>
		<dc:creator>Gili Nachum</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[availability]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[OOME]]></category>
		<category><![CDATA[out of memory]]></category>
		<category><![CDATA[system startup]]></category>
		<category><![CDATA[throwable]]></category>
		<category><![CDATA[try-catch]]></category>

		<guid isPermaLink="false">http://www.javatuning.com/?p=110</guid>
		<description><![CDATA[Disclaimer: Now I know that this is an old idiom, I&#8217;m just presenting my own real life incident taken straight away from the bloody Java trenches. Exceptions can be threads assassins when running on top of Websphere thread pool, any Runtime exception that isn&#8217;t caught by the applicative code, will bubble up in the stack, [...]]]></description>
			<content:encoded><![CDATA[<p>Disclaimer: Now I know that this is an old idiom, I&#8217;m just presenting my own real life incident taken straight away from the bloody Java trenches.</p>
<p><strong>Exceptions can be threads assassins</strong><br />
when running on top of Websphere thread pool, any Runtime exception that isn&#8217;t caught by the applicative code, will bubble up in the stack, ending up killing the specific thread. WAS helps here, by automatically creating a new thread that will take the place of the murdered one, but still, killing and immediately creating a thread is everything but the thread pool rational.</p>
<p><strong>Hiring a thread bodyguard</strong><br />
<img class="size-full wp-image-111 alignright" title="bodyguard" src="http://www.javatuning.com/wp-content/uploads/2009/02/bodyguard.jpg" alt="bodyguard" width="229" height="285" />A simple way to avoid thread death is wrapping the first applicative layer (e.g., Run() method) with a try block that catches and swallows any Exception that&#8217;s thrown from anywhere in the application code.<br />
Our project&#8217;s code also used this concept, but instead of <em>catch (Exception e), </em>it had a <em>catch (Throwable t)</em>, When I noticed that I didn&#8217;t rushed to fix it, just in case someone before me had done funky stuff with dynamic class loading that might throw ClassNotFoundError (although this should be caught at a very localized resolution), or maybe it&#8217;s there for some other historical reason that not being one the code&#8217;s forefathers I’m just not aware of. In any case, I did promise myself that I&#8217;ll revisit this piece of code in the future.</p>
<p><strong>Getting some bulls to do correct things</strong><br />
today I finally got the excuse I needed in order to change the catch Throwable in a catch Exception:<br />
We were running stress tests, when the server had an OOME (out of memory error). Since the catch Throwable caught and swallowed the OOME (as OOME is a subclass of Error which is a subclass of Throwable), the thread that generated the OMME kept on living, instead of dieing right there, and so, the JVM continued running, crippled and limping, instead of turning to an honorable solution like <a href="http://en.wikipedia.org/wiki/Seppuku">hara-kiri</a>. Choosing the quick death route would have been rewarded with a quick resurrection to be provided by the gracious NodeAgent and its watchdog mechanism, and the end result would have been a newly born healthy server ready to get back in business. A retreat in order to attack, you might put it.<br />
Instead, the server had to limp for long minutes, suffering from a series of consecutive strokes (OOME), until the OOME was so bad that the JVM just had to exit.</p>
<p><strong>Conclusions</strong><br />
The Catch Throwable was causing down time, by preventing an imminent restart of the JVM due to an OOME.</p>
<p><strong>Open Questions</strong></p>
<ol type="1">
<li class="MsoNormal">I know that an uncaught      exception kills only the specific thread does the JVM treats an error      differently? Put other words, if the OOME is not caught, will the entire      JVM die or only the specific thread? I assume that the answer is the      entire JVM, maybe this is implemented by the JVM itself, or maybe it&#8217;s      implemented somewhere in the WAS bedrock. If for some reason it&#8217;s not the      case, one could catch an Error and then execute System.exit(1); in order      to hasten the process imminent death.</li>
</ol>
<p class="MsoNormal">
]]></content:encoded>
			<wfw:commentRss>http://www.javatuning.com/why-catch-throwable-is-evil-real-life-story/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Saving on memory usage in Java #1 &#8211; the Byte.valueOf method</title>
		<link>http://www.javatuning.com/saving-on-memory-the-valueof-method/</link>
		<comments>http://www.javatuning.com/saving-on-memory-the-valueof-method/#comments</comments>
		<pubDate>Fri, 26 Dec 2008 23:02:44 +0000</pubDate>
		<dc:creator>Gili Nachum</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[efficiency]]></category>

		<guid isPermaLink="false">http://www.javatuning.com/?p=7</guid>
		<description><![CDATA[Say you wanna keep in memory a list of martial arts experts and their respective shoe size. One way to implement it would be to populate a Map structure with the following sets of key and value: Map map = ... map.put("Jean-Claude Van Damme", new Byte(45)); map.put("Jet Li", new Byte(45)); map.put("Chuck Norris", new Byte(112)); ... [...]]]></description>
			<content:encoded><![CDATA[<p>Say you wanna keep in memory a list of martial arts experts and their respective shoe size. One way to implement it would be to populate a Map structure with the following sets of key and value<code>:</code></p>
<p><code>Map map = ...<br />
map.put("Jean-Claude Van Damme",  new Byte(45));<br />
map.put("Jet Li",  new Byte(45));<br />
map.put("Chuck Norris", new Byte(112));<br />
...<br />
map.put("person number million", new Byte(45));<br />
</code><br />
What if your JVM runs on a <a href="http://stochastix.wordpress.com/2006/12/29/building-a-calculating-machine-using-lego/">Lego mechanical computer</a> that has a very limited amount of memory, you would probably want to save on memory wherever possible.</p>
<div id="attachment_65" class="wp-caption alignnone" style="width: 310px"><a href="http://www.javatuning.com/wp-content/uploads/2008/12/lego.jpg"><img class="size-medium wp-image-65" title="A state of the art 3Hz Lego computer" src="http://www.javatuning.com/wp-content/uploads/2008/12/lego-300x218.jpg" alt="A Lego computer" width="300" height="218" /></a><p class="wp-caption-text">A state of the art 3Hz Lego computer</p></div>
<h3>Autoboxing anybody?</h3>
<p>Keeping in mind that an object instance weights much more than just the primitive it holds, as it hold additional &#8220;plumbing&#8221; data (monitor, etc). Even an Object class instance weighs 8 bytes while not holding to any application information. What about keeping only primitives as the map value?<br />
Autoboxing, introduced in Java 5 onwards, allows to pass a byte primitive argument instead of a Byte object instance argument in the following manner:</p>
<p><code>map.put("Bruce Lee", 42);</code></p>
<p>Does this help us avoid the costly Byte Objects? Not really, the auto-boxing feature, as the name hints, just statically replaces the 42 literal with a new Byte object instance, this is done during compilation. So there&#8217;s no real saving opportunity here, and we&#8217;re back where we started.</p>
<div id="attachment_66" class="wp-caption alignnone" style="width: 310px"><a href="http://www.javatuning.com/wp-content/uploads/2008/12/boxes.jpg"><img class="size-medium wp-image-66" title="boxes" src="http://www.javatuning.com/wp-content/uploads/2008/12/boxes-300x210.jpg" alt="AutoBoxing" width="300" height="210" /></a><p class="wp-caption-text">AutoBoxing</p></div>
<h3>How about a plain old cache?</h3>
<p>Examining the code above, you notice that you are creating one million unique Byte objects to hold the fighters&#8217; shoe size, even though there are only 256 different shoe size values. Is this a venue for saving?<br />
Considering the fact that Byte objects are immutable, why not have just a single Byte object for each distinct byte value (we&#8217;ll need only 256 instance to cover all values). This way we&#8217;ll pass the same Byte instance to all people with a 45 shoe size, Jean-Claude and Jet-Li map in our case. This will reduce the number of Byte instance from a million to only 256. Sounds super!</p>
<div id="attachment_67" class="wp-caption alignnone" style="width: 211px"><a href="http://www.javatuning.com/wp-content/uploads/2008/12/too_many_objects.jpg"><img class="size-medium wp-image-67" title="Too much objects in memory" src="http://www.javatuning.com/wp-content/uploads/2008/12/too_many_objects-300x181.jpg" alt="Memorizing too many objects is hard" width="201" height="121" /></a><p class="wp-caption-text">Too much objects in memory</p></div>
<p>How do you implement this? You&#8217;ll might rush into initializing an array of 256 Byte objects during application start-up, giving birth to something of this sort:<br />
<code><br />
// init instances array<br />
int RANGE_OF_VALUES = 2^8; // we don't care about negatives<br />
Static Byte constShoeSizes = new Byte[</code><code>RANGE_OF_VALUES</code><code>];<br />
for (byte b=0; b&lt;</code><code>RANGE_OF_VALUES</code><code>; b++) {<br />
constShoeSizes[b] = new Byte(B</code><code>yte.MIN_VALUE</code><code> + b);<br />
}<br />
map.put("Jean-Claude Van Damme", constShoeSizes[45]);<br />
map.put("Jet Li", constShoeSizes[45]);<br />
map.put("Chuck Norris", constShoeSizes[112]);<br />
</code></p>
<h3>Enter the valueOf() method</h3>
<p>WHOA! Hold you horses! Doesn&#8217;t this use case seems to be just too common and trivial?! haven&#8217;t the Java language designers and implemented came accross the same problem? Surely, some of the JRE classes themselves must have Byte instances data members. In an effort to reduce the JRE memory footprint, won&#8217;t the JRE programmers cache instances using something very much like the static Byte array we implemented ourselves?<br />
The short answer of course is YES! Java 5 presents a new overloaded Byte.valueOf(byte b) method. This method returns a reference to a Byte instance taken from a shared cache. This trivial cache strategy save memory and CPU, as there&#8217;s no need to construct new objects and later on garbage collect them.<br />
Here&#8217;s the relevant Byte.valueOf method source code taken from Byte.java source:<br />
<code><br />
private static class ByteCache {<br />
private ByteCache(){}</code></p>
<p><code>static final Byte cache[] = new Byte[-(-128) + 127 + 1];</code></p>
<p><code>static {<br />
for(int i = 0; i &lt; cache.length; i++)<br />
cache[i] = new Byte((byte)(i - 128));<br />
}<br />
}<br />
...<br />
public static Byte valueOf(byte b) {<br />
final int offset = 128;<br />
return ByteCache.cache[(int)b + offset];<br />
}</code></p>
<p>Using the valueOf method, here&#8217;s how the final version of our code will look like:<br />
<code><br />
map.put("Jean-Claude Van Damme", Byte.valueOf(45));<br />
map.put("Jet Li", Byte.valueOf(45));<br />
map.put("Chuck Norris", Byte.valueOf(112));<br />
</code></p>
<h3>Wrapping up quickly:</h3>
<ol>
<li>From Java 5 onwards, use the valueOf method for Number extenders like: Byte, Short, and Integer. Notice that as the Integer object has 2^32 different values, only the (-128) to 127 values range is cached. Meaning that expression (Integer.valueOf(129)==Integer.valueOf(129)) will always be false, since it returns a new Integer object on every call.<br />
Other object types  (Double,Float, etc&#8230;) valueOf method does not implement a cache at all. If your value range is limited in nature, you might choose to create a caching scheme of your own.</li>
<li>Always be on the lookout and Inspect repetetive Instance creation closely, see if you can avoid it by referencing an shared immutable object, or by borrowing an instance from an object pool.</li>
<li>Strings can have an even larger space and time performance gains than numbers objects, though at the same time they are inherently harder to reuse. You might want to take time to learn about Strings instances reuse strategies; start with the <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()">String.intern()</a> method.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.javatuning.com/saving-on-memory-the-valueof-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
