<?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>Piotr Nowicki&#039;s Homepage</title>
	<atom:link href="http://piotrnowicki.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://piotrnowicki.com</link>
	<description>&#34;Simplicity is the ultimate sophistication.&#34;</description>
	<lastBuildDate>Fri, 18 May 2012 22:39:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>After the Spring 3 Core Training</title>
		<link>http://piotrnowicki.com/2012/05/after-the-spring-3-core-training/</link>
		<comments>http://piotrnowicki.com/2012/05/after-the-spring-3-core-training/#comments</comments>
		<pubDate>Fri, 18 May 2012 22:38:46 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[springsource]]></category>
		<category><![CDATA[training]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=837</guid>
		<description><![CDATA[At the end of march 2012 I was attending a Spring 3 Core Training in Cracow which was organised by the SpringSource. Because I am more of a pure Java EE world type and mainly develop in this area, I wanted to improve my knowledge about Spring. Sure, I&#8217;ve used Spring, worked with it but [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of march 2012 I was attending a <a href="http://www.springsource.com/training/certification/springprofessional">Spring 3 Core Training</a> in Cracow which was organised by the SpringSource. Because I am more of a pure Java EE world type and mainly develop in this area, I wanted to improve my knowledge about Spring. Sure, I&#8217;ve used Spring, worked with it but never felt really comfortable with it. I was missing <strong>the big picture</strong> and so that&#8217;s why I decided to go to this training.</p>
<p><span id="more-837"></span></p>
<p>The training lasted <strong>4 days</strong> and it was really a full-day training: we started at 9.00 and finished at 17.00 with a few short, coffee, breaks and one longer &#8212; for a lunch. You can view the syllabus <a href="http://www.springsource.com/training/course?courseID=17750#course-syllabus">on this site</a>, but mainly, the course focused on <strong>the core of Spring Framework</strong>, so we&#8217;ve spent a lot of time discovering the dependency injection intricacies, bean factories, bean post processors, AOP (and how it is applied to the transactions, security and other cross-cutting concerns.) We&#8217;ve just scratched the surface of the Spring MVC, RMI, JMS and JMX.<br />
All this material was presented in a form of an active lecture where the questions were widely accepted during the talk. We were provided with <strong>printed version of the slides</strong>, so it was easy to make notes directly on the slides.</p>
<p>After each of the sections, there was a lab exercise / exercises &#8212; a hands-on session with Spring Tool Suite. For those labs, we were also provided with the printed version of the appropriate tutorial. The tasks were pretty easy, as they based on just presented material. All the source code used in this sessions was provided on a SpringSource 4GB pen-drive that every attendant was given.</p>
<p>The class itself was rather small, as it consists of <strong>6 attendants</strong>: 5 Poles and 1 Englishman (cheers Tom!) The lecturer, <strong>Tomas Lukosius</strong> put a lot of effort into passing the knowledge in easy and simple way &#8211; just as all good lecturers should do. The whole training was like <em>&#8220;look how simple it is&#8221;</em> or <em>&#8220;it just another bean post processor&#8221;</em> or things like that. It really showed how some complicated stuff like runtime aspects weaving, transactions or security constraints are organised under the hood. Not rarely it seemed quite simple and uncomplicated!<br />
At the beginning of each day there was a revision, a sum-up of all the topics discussed day before. It helped to refresh your memory as well as organise the knowledge better.</p>
<p>My overall opinion about this training is <strong>very good</strong>. I can see a major improvement of my knowledge about how the core of the Spring Framework works. I&#8217;m sure that if you&#8217;d put some more effort, read a decent book like <a href="http://www.amazon.co.uk/Spring-Action-Craig-Walls/dp/1935182358">&#8220;Spring in Action&#8221;</a> by Craig Walls and supplement your knowledge with Spring documentation, you&#8217;ll earn the same knowledge as in this training.<br />
This will, however, take <strong>a lot</strong> more time and you&#8217;d need <strong>a lot of self-discipline</strong>. Nevertheless, it&#8217;s achievable as the knowledge passed during the training wasn&#8217;t any kind of black or secret magic.</p>
<p>One of the nice things about the training is that after it you earn a voucher for <a href="http://www.springsource.com/training/certification/springprofessional"><strong>Spring Certified Professional</strong></a> exam. Although the passing score is fairly high (in comparison to the Oracle exams) I&#8217;ve heard that it&#8217;s enough just to re-read all the slides, notes and do once again all the labs. Hope to find some time to attempt to pass the exam soon!</p>
<p>PS. The beverages, snacks and lunch was provided by the company which held the training (Altkom Akademia.) Beverages and snacks were really nice but the lunches&#8230; well&#8230; just let&#8217;s say that I&#8217;ve eaten a lot of better things in my life ;-)</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/05/after-the-spring-3-core-training/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>DWR &#8211; Access Your Java Objects Directly From JavaScript</title>
		<link>http://piotrnowicki.com/2012/05/dwr-access-your-java-objects-directly-from-javascript/</link>
		<comments>http://piotrnowicki.com/2012/05/dwr-access-your-java-objects-directly-from-javascript/#comments</comments>
		<pubDate>Thu, 10 May 2012 22:38:22 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[dwr]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[xmlhttprequest]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=1059</guid>
		<description><![CDATA[I must admit &#8211; I&#8217;m neither very experienced in the field of user interfaces nor really familiarised with all that JavaScript, jQuery stuff. I was always thinking of myself more as a service layer guy. Nevertheless, I wanted to improve my knowledge, so I decided to learn more about something called DWR (Direct Web Remoting). [...]]]></description>
			<content:encoded><![CDATA[<p>I must admit &#8211; I&#8217;m neither very experienced in the field of user interfaces nor really familiarised with all that JavaScript, jQuery stuff. I was always thinking of myself more as a service layer guy.<br />
Nevertheless, I wanted to improve my knowledge, so I decided to learn more about something called DWR (<em>Direct Web Remoting</em>). I&#8217;ve heard about it few years ago but never actually passed the <em>&#8220;yeah, I&#8217;ve heard about it&#8221;</em> stage.</p>
<p>This will be very basic introduction, so I&#8217;m afraid that for those of you who know what DWR is and used it, this article won&#8217;t introduce nothing new.</p>
<p><span id="more-1059"></span></p>
<h3>XMLHttpRequest</h3>
<p>Up to know I&#8217;ve always thought that if the JavaScript have its <code>XMLHttpRequest</code> object, it can send asynchronous requests to the server &#8211; so this is basically the AJAX. Who needs anything more?</p>
<p>Well, it seems that the <code>XMLHttpRequest</code> is quite <strong>low-level</strong> and as usual, more high-level tools and frameworks arose. DWR is one of such frameworks, but it goes even further. Not only you don&#8217;t have to deal with those low-level <code>XMLHttpRequest</code> objects, but <strong>you can use your Java objects directly in the JavaScript code</strong>.</p>
<p>DWR creates a JavaScript&#8217;s <strong>proxy</strong> for your Java methods and sends the request to invoke particular method asynchronously &#8211; expecting the result in the callback method. You can easily define what Java methods should be accessible from the JS using the <code>dwr.xml</code> configuration file you&#8217;ll see in a moment.</p>
<h3>Server side</h3>
<p>Take a look at this Java code &#8211; it&#8217;s just a regular class with two methods. Let&#8217;s pretend it&#8217;s a <em>Dice Roller service</em>, so it allows you to roll a dice (<code>rollDice()</code>) and to scream at the dealer if you&#8217;re not happy with the resulting pips (<code>scream(String)</code>.)</p>
<pre><code>package com.piotrnowicki.dwr;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/** Simulates a 6-sided dice roll. Also allows to scream if you're not
 * satisfied with the result.
 *
 * @author PiotrNowicki
 **/
 public class DiceRollService {

    private Logger log =
                    Logger.getLogger(DiceRollService.class.getName());

    /**
     * Just for inspection when the object is created.
     */
    public DiceRollService() {
        log.info("Constructing an object");
    }

    /**
     * Roll a 6-sided dice.
     *
     * @return rolled pips.
     */
    public Integer rollDice() {
        return new Random().nextInt(6) + 1;
    }

    /**
     * Scream (e.g. at the dealer) given sentence. Shows how you can
     * deal with parameters in DWR.
     *
     * @param msg
     *            what to be screamed.
     */
    public void scream(String msg) {
        log.log(Level.INFO, "Screaming: {0}", msg);
    }
}
</code></pre>
<p>This is a class which methods we want to be accessible directly from the JS (embedded on our user-interface HTML page). To achieve this, we need to inform the DWR about the existence of the <code>DiceRollService</code> class. We do this by creating a <code>dwr.xml</code> file in <code>webapp/WEB-INF/</code> (just next to the <code>web.xml</code>):</p>
<pre><code>&lt;!DOCTYPE dwr
  PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
  "http://getahead.org/dwr/dwr30.dtd"&gt;
&lt;dwr&gt;
    &lt;allow&gt;
        &lt;create creator="new"
                javascript="JSDiceRollService"
                scope="application"&gt;
            &lt;param name="class"
                   value="com.piotrnowicki.dwr.DiceRollService" /&gt;
        &lt;/create&gt;
    &lt;/allow&gt;
&lt;/dwr&gt;
</code></pre>
<p>The above excerpt tells DWR to create an instance of <code>DiceRollService</code> using the <code>new</code> Java operator (you can as well use static method to obtain your class instance, access bean registered in the Spring Framework and so on &#8211; read <a href="http://directwebremoting.org/dwr/documentation/server/configuration/dwrxml/index.html">this page</a> for more details.)</p>
<p>This newly created object will be named <code>JSDiceRollService</code> and it&#8217;ll be bound to the application scope (similarly as in Servlets, we have: application, session, page and request scope.)</p>
<p>The last thing we need is to create a DWR Servlet which will be responsible for registering our classes / methods. It will make them accessible for the DWR client or RESTful client. We do that by creating a <code>web.xml</code> that looks somewhat like this:</p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0"&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;
        &lt;servlet-class&gt;
            org.directwebremoting.servlet.DwrServlet
        &lt;/servlet-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;jsonpEnabled&lt;/param-name&gt;
            &lt;param-value&gt;true&lt;/param-value&gt;
        &lt;/init-param&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;debug&lt;/param-name&gt;
            &lt;param-value&gt;true&lt;/param-value&gt;
        &lt;/init-param&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;dwr-invoker&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/dwr/*&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</code></pre>
<p>Notice the <code>/dwr/*</code> url-pattern has been bound to the DWR Servlet &#8211; this is the entry-point to the server-side DWR. You don&#8217;t really need the <code>jsonpEnabled</code> init-param, but in a moment I&#8217;ll show you why it can be useful.</p>
<p>The <code>debug</code> param allows you to see the test page when you enter the DWR Servlet URL, e.g.: <code>http://localhost:8080/DWRTest/dwr</code> (<code>DWRTest</code> is an application context.)</p>
<p>I&#8217;m not aware if this can be configured using the Servlets 3.0 <code>@WebServlet</code> annotation, but as I don&#8217;t see much added value using it here, I won&#8217;t even try digging it.</p>
<p>And that&#8217;s pretty much all there is &#8211; you&#8217;ve created your business logic class in pure Java, instructed DWR that it should create a JS proxy for your class and, finally, you&#8217;ve defined and configured the server-side DWR Servlet.</p>
<p>Now it&#8217;s time to go to the client layer.</p>
<h3>Client Side</h3>
<p>First thing you can check after you run your application, is to enter the already mentioned DWR test page (e.g. <code>http://localhost:8080/DWRTest/dwr</code>) and see if you can access your Java methods from it. You can observe that your Java object will be created as many times as appropriate, depending on your <code>scope</code> attribute value in <code>dwr.xml</code>. Every object instantiation is logged, so you can inspect your server logs if you want to check it.</p>
<p>However, let&#8217;s go to some more interesting stuff &#8211; accessing your Java objects from an arbitrary JavaScript code. Take a look at the code below (it&#8217;s called <code>index.jsp</code> and it&#8217;s located directly in the <code>webapp/</code> directory):</p>
<pre><code>&lt;!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;DWR Test&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;script type="text/javascript"
              src="dwr/engine.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"
              src="dwr/interface/JSDiceRollService.js"&gt;&lt;/script&gt;
      &lt;input type="button" value="Roll a dice" onclick="clicked()" /&gt;
      &lt;div id="diceRes"&gt;&lt;/div&gt; 

      &lt;script type="text/javascript"&gt;
        function clicked() {
          JSDiceRollService.rollDice({ callback : function(str) {
            document.getElementById("diceRes").innerHTML = str;
          } });
        } 

        // Taken from kdenney's post:
        //        http://stackoverflow.com/a/155265/920607
        function keyPressed(e) {
          if (typeof e == 'undefined' &amp;&amp; window.event) {
            e = window.event;
          } 

          if (e.keyCode == 13) {
            JSDiceRollService.scream(
                 document.getElementById("shoutField").value, {
                   callback : function(str) {
                     alert("Check your Java server logs");
                   }
                 }
            );
          }
        }

      &lt;/script&gt;
      &lt;br /&gt; &lt;br /&gt;
      Type any text to shout in Java System.out.println
      (ENTER sends the request):
      &lt;input id="shoutField"
             type="text"
             value="You bastard!"
             onkeypress="keyPressed(event)" /&gt;
    &lt;/body&gt;
  &lt;/html&gt;
</code></pre>
<p>It&#8217;s not the most elegant and prettiest HTML + JavaScript code in the world, but for this exemplary purpose &#8212; it does it work. I&#8217;m not sure if it will even pass the W3C validator, but that&#8217;s not the point now.</p>
<p>Take a look at the <code>&lt;script&gt;</code> imports at the beginning of the <code>&lt;body&gt;</code>. It&#8217;s value refers to our DWR Servlet URL, so those scripts are generated by DWR for you. Notice that you&#8217;ve also included a JavaScript code for DWR generated proxy &#8211; <code>dwr/interface/JSDiceRollService.js</code>.</p>
<p>Also, be very careful with <strong>the order of imports</strong>. The <code>engine.js</code> script import <strong>must occur</strong> before your JS proxy import.</p>
<p>This simple page shows you:</p>
<ul>
<li>a button which will invoke <code>DiceRollService#rollDice()</code> method and print the result in div with ID = <code>diceRes</code>, </li>
<li>an input field that after you hit ENTER, will invoke <code>DiceRollService#scream(msg)</code> where the <code>msg</code> is text typed into the field.</li>
</ul>
<p>That&#8217;s basically it &#8211; you should be able to successfully send an asynchronous HTTP request which will invoke one of your Java methods using <code>XMLHttpRequest</code> under the hood. Pretty neat, huh?</p>
<h3>REST</h3>
<p>One of the additional features of the DWR is the support for REST&#8217;style requests / responses. If you access the following URL: <code>http://localhost:8080/DWRTest/dwr/jsonp/JSDiceRollService/rollDice</code> (of course, substituting the appropriate parts like protocol, host, port and application context) you can access the <code>DiceRollService#rollDice</code> method as well. The response will be in the JSONP format and it should look something like this:</p>
<pre><code>{ "reply":5}
</code></pre>
<h3>Summary</h3>
<p>I didn&#8217;t test any reverse Ajax support, as I think I&#8217;ll write a separate post about it &#8211; just when I&#8217;ll try to do some tests with Server Sent Events and Web Sockets &#8212; so stay tuned!</p>
<p>For the first time I think I understood what the DWR really does and how it can improve your development.</p>
<p>However, I&#8217;m curious what will happen if the boundary of the service layer is an EJB. The EJB container is responsible for creation of the EJB&#8217;s and the EJB support for DWR doesn&#8217;t seem to be stable yet.<br />
What about the CDI and its scopes? Perhaps the <code>@Produces</code> CDI method and <code>scope = static</code> in DWR will do the work?</p>
<p>What is the place of DWR in JSF and managed beans world? What about the JSF managed beans scopes and DWR scopes &#8211; how do they comply?</p>
<p>There are a lot of questions I don&#8217;t know answer at this point. Nevertheless, I think it&#8217;s just a regular matter of picking the right tool to do the job.</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/05/dwr-access-your-java-objects-directly-from-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BTrace &#8211; a Simple Way to Instrument Running Java Applications</title>
		<link>http://piotrnowicki.com/2012/05/btrace-a-simple-way-to-instrument-running-java-applications/</link>
		<comments>http://piotrnowicki.com/2012/05/btrace-a-simple-way-to-instrument-running-java-applications/#comments</comments>
		<pubDate>Sat, 05 May 2012 14:13:17 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[btrace]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[instrumentation]]></category>
		<category><![CDATA[jmx]]></category>
		<category><![CDATA[jps]]></category>
		<category><![CDATA[jstat]]></category>
		<category><![CDATA[mbeans]]></category>
		<category><![CDATA[strong reference]]></category>
		<category><![CDATA[visualvm]]></category>
		<category><![CDATA[weak reference]]></category>
		<category><![CDATA[weaving]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=958</guid>
		<description><![CDATA[Sometimes you need to audit or profile your Java application. The easiest but most intrusive way to do this is to do a bunch of System.out.printlns (which is obviously bad) or to use loggers. After adding a lot of logging statements, your application becomes cluttered with unnecessary boilerplate code. Profiling, instrumentation or method measuring are [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to audit or profile your Java application. The easiest but most intrusive way to do this is to do a bunch of <code>System.out.println</code>s (which is obviously <strong>bad</strong>) or to use loggers. After adding a lot of logging statements, your application becomes cluttered with unnecessary boilerplate code.</p>
<p>Profiling, instrumentation or method measuring are great examples of cross-cutting concerns that might be nicely solved using <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a> (Aspect Oriented Programming.) Basically, it allows you to invoke a certain action upon some defined conditions without the need for changing the instrumented code. The process of applying the aspects to your code is called <strong>weaving</strong>.<br />
There are three types of weaving (not every AOP implementation must support all of them):</p>
<ol>
<li>source code weaving (the aspect is applied to the inspected source code before the compilation),</li>
<li>byte code weaving (the aspect is applied to the compiled, <code>.class</code> file),</li>
<li>runtime weaving (the aspect is applied to the running, live application within the JVM).</li>
</ol>
<p>As a side note, you can create your own simple runtime weaving AOP tool by using <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html">Java Agents</a> that are invoked before any other written source code method (in the matter of fact, agent methods are invoked even before the <code>static void main(String[] args)</code> method of your Java class.)</p>
<p><span id="more-958"></span></p>
<p><strong>Table of contents</strong> <ol class="toc-generator"><li><a href="#toc-what-is-the-btrace" title="Jump to What is the BTrace?">What is the BTrace?</a></li><li><a href="#toc-how-can-i-use-it" title="Jump to How Can I Use it?">How Can I Use it?</a></li><li><a href="#toc-exemplary-source-code-to-be-instrumented" title="Jump to Exemplary Source Code to be Instrumented">Exemplary Source Code to be Instrumented</a></li><li><a href="#toc-why-the-weakreference" title="Jump to Why the WeakReference?">Why the WeakReference?</a></li><li><a href="#toc-exemplary-btrace-script" title="Jump to Exemplary BTrace Script">Exemplary BTrace Script</a></li><li><a href="#toc-ways-of-getting-the-results" title="Jump to Ways of Getting the Results">Ways of Getting the Results</a></li><li><a href="#toc-invoking-the-script" title="Jump to Invoking the Script">Invoking the Script</a></li><li><a href="#toc-jstat-counter-access" title="Jump to JStat Counter Access">JStat Counter Access</a></li><li><a href="#toc-mbeans-access" title="Jump to MBeans Access">MBeans Access</a></li><li><a href="#toc-weak-references-and-garbage-collection" title="Jump to Weak References and Garbage Collection">Weak References and Garbage Collection</a></li><li><a href="#toc-strong-references-and-garbage-collection" title="Jump to Strong References and Garbage Collection">Strong References and Garbage Collection</a></li><li><a href="#toc-overhead" title="Jump to Overhead">Overhead</a></li><li><a href="#toc-summary" title="Jump to Summary">Summary</a></li></ol></p>
<h3 id="toc-what-is-the-btrace">What is the BTrace?</h3>
<p>One of the interesting tools for instrumenting your running applications is <strong>BTrace</strong>. It is a non-intrusive, read-only Java tool that allows you to create a script (compilable Java source code) that will be used to define probes and to monitor your running application (which I think is the same as the AOP runtime weaving).</p>
<p>The big advantage of runtime weaving is that you are not forced to recompile the source code you want to instrument nor to have to stop it. You can just plug into already executed application and start monitoring it right away.</p>
<h3 id="toc-how-can-i-use-it">How Can I Use it?</h3>
<p>Firstly, you need to execute your Java application that you want to monitor (well, there is a way to start an application and tracing at the same time, but you&#8217;ll need to read details on the <a href="http://kenai.com/projects/btrace/pages/Home">BTrace</a> website.) BTrace can be used in one of three ways:</p>
<ol>
<li>You can write the BTrace script and use <code>btrace</code> utility (it comes with the BTrace distribution) to apply your script to the running application,</li>
<li>You can write the BTrace script and compile it using BTrace provided compiler,</li>
<li>You can dynamically apply the BTrace script using the <a href="visualvm.java.net">VisualVM</a>.</li>
</ol>
<p>I&#8217;ll focus on the third option, as in my opinion it seems to be the easiest and fastest. Nevertheless, one command that might be very useful for you despite the chosen method is the <code>jps</code>. It allows you to show what Java processes are currently running. The PID showed in the output will be useful in some of the further commands.</p>
<h3 id="toc-exemplary-source-code-to-be-instrumented">Exemplary Source Code to be Instrumented</h3>
<p>At <a href="https://github.com/PiotrNowicki/BTrace-Cache-access-app">Github</a> you can find an exemplary application that will be instrumented by the BTrace and discussed in the rest of this article. The source code should be pretty straightforward. The purpose of this application is very simple &#8211; it is supposed to simulate a cache access. The whole application consists of three classes:</p>
<ul>
<li><code>Data.java</code> this is the data that will be stored in the cache; users will try to fetch it using the key which is a randomly generated integer number from range &lt;0, 100):</li>
</ul>
<script src = "http://gist-it.sudarmuthu.com/github/PiotrNowicki/BTrace-Cache-access-app/blob/master/src/com/piotrnowicki/btrace/Data.java?footer=minimal"></script>
<ul>
<li><code>DataAccessor.java</code> is the main logic of the application. It stores a cache (map of weak references to <code>Data</code> objects) and allows clients to access its <code>getData(-)</code> method.</li>
</ul>
<p>If the requested data is in the cache, it is retrieved and returned to the caller.<br />
If it&#8217;s not in the cache, a new data is created, stored in the cache and returned to the caller:</p>
<script src = "http://gist-it.sudarmuthu.com/github/PiotrNowicki/BTrace-Cache-access-app/blob/master/src/com/piotrnowicki/btrace/DataAccessor.java?footer=minimal"></script>
<ul>
<li><code>Executor.java</code> is the entry point for this application. It&#8217;s simulating a few hundreds data read access events, sleeping for a random time (0 &#8211; 1000 msec) between the requests:</li>
</ul>
<script src = "http://gist-it.sudarmuthu.com/github/PiotrNowicki/BTrace-Cache-access-app/blob/master/src/com/piotrnowicki/btrace/Executor.java?footer=minimal"></script>
<h3 id="toc-why-the-weakreference">Why the WeakReference?</h3>
<p>Take a look at the <code>DataAccessor</code>&#8216;s cache &#8211; it&#8217;s stored in:</p>
<pre><code>Map&lt;String, WeakReference&lt;Data&gt;&gt; cache =
       new HashMap&lt;String, WeakReference&lt;Data&gt;&gt;();
</code></pre>
<p>The weak references are good for caching purposes as they are eligible for collecting by GC despite the fact they are still accessible from the map instance.<br />
Note that the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html">WeakHashMap</a> wouldn&#8217;t be a good candidate for this purpose as it makes a weak references to the map <strong>keys</strong>, not values in which we&#8217;re interested in.</p>
<p>If you want to learn more about strong, soft, weak and phantom references please refer to <a href="http://weblogs.java.net/blog/2006/05/04/understanding-weak-references">Ethan Nicholas&#8217;s article</a>.</p>
<h3 id="toc-exemplary-btrace-script">Exemplary BTrace Script</h3>
<p>Below you can find an exemplary BTrace script that will be used to instrument the previously presented source code / cache access. Some of the information is provided in the comments to the script code. You can create and edit the BTrace script in your IDE &#8211; just be sure that you have <code>btrace-boot.jar</code> on your classpath to be able to use the annotations like <code>@OnMethod</code>, <code>@Property</code> and so on.</p>
<p>Beware that you are <strong>not allowed to</strong> use any non-BTrace methods nor to create new objects within the BTrace methods. The point is to guarantee that the script is read-only and as non-intrusive as possible, therefore you are not allowed to do e.g. String concatenations. You must use only methods from the <a href="http://btrace.kenai.com/javadoc/1.2/com/sun/btrace/BTraceUtils.html"><code>BTraceUtils</code></a> class that can provide you e.g. mentioned string concatenation, comparisons, aggregation, parsing methods, etc.</p>
<script>document.write('<link rel="stylesheet" href="https://gist.github.com/stylesheets/gist/embed.css"/>')

document.write('<div id=\"gist-2594661\" class=\"gist\">\n\n        <div class=\"gist-file\">\n          <div class=\"gist-data gist-syntax\">\n              <div class=\"gist-highlight\"><pre><div class=\'line\' id=\'LC1\'><span class=\"kn\">package<\/span> <span class=\"n\">com<\/span><span class=\"o\">.<\/span><span class=\"na\">piotrnowicki<\/span><span class=\"o\">.<\/span><span class=\"na\">btrace<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC2\'><br/><\/div><div class=\'line\' id=\'LC3\'><span class=\"kn\">import<\/span> <span class=\"nn\">static<\/span> <span class=\"n\">com<\/span><span class=\"o\">.<\/span><span class=\"na\">sun<\/span><span class=\"o\">.<\/span><span class=\"na\">btrace<\/span><span class=\"o\">.<\/span><span class=\"na\">BTraceUtils<\/span><span class=\"o\">.<\/span><span class=\"na\">printArray<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC4\'><span class=\"kn\">import<\/span> <span class=\"nn\">static<\/span> <span class=\"n\">com<\/span><span class=\"o\">.<\/span><span class=\"na\">sun<\/span><span class=\"o\">.<\/span><span class=\"na\">btrace<\/span><span class=\"o\">.<\/span><span class=\"na\">BTraceUtils<\/span><span class=\"o\">.<\/span><span class=\"na\">println<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC5\'><span class=\"kn\">import<\/span> <span class=\"nn\">static<\/span> <span class=\"n\">com<\/span><span class=\"o\">.<\/span><span class=\"na\">sun<\/span><span class=\"o\">.<\/span><span class=\"na\">btrace<\/span><span class=\"o\">.<\/span><span class=\"na\">BTraceUtils<\/span><span class=\"o\">.<\/span><span class=\"na\">strcat<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC6\'><br/><\/div><div class=\'line\' id=\'LC7\'><span class=\"kn\">import<\/span> <span class=\"nn\">java.lang.ref.WeakReference<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC8\'><br/><\/div><div class=\'line\' id=\'LC9\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.AnyType<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC10\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.BTraceUtils.Aggregations<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC11\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.BTraceUtils.Strings<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC12\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.aggregation.Aggregation<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC13\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.aggregation.AggregationFunction<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC14\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.BTrace<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC15\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.Duration<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC16\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.Export<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC17\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.Kind<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC18\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.Location<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC19\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.OnMethod<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC20\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.OnTimer<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC21\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.ProbeClassName<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC22\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.ProbeMethodName<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC23\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.Property<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC24\'><span class=\"kn\">import<\/span> <span class=\"nn\">com.sun.btrace.annotations.TargetMethodOrField<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC25\'><br/><\/div><div class=\'line\' id=\'LC26\'><span class=\"c1\">// @BTrace means that this class will be used to define probes <\/span><\/div><div class=\'line\' id=\'LC27\'><span class=\"c1\">// and actions. All fields and methods must be static. <\/span><\/div><div class=\'line\' id=\'LC28\'><span class=\"c1\">// You can use only BTraceUtils methods.<\/span><\/div><div class=\'line\' id=\'LC29\'><span class=\"nd\">@BTrace<\/span><\/div><div class=\'line\' id=\'LC30\'><span class=\"nd\">@SuppressWarnings<\/span><span class=\"o\">(<\/span><span class=\"s\">&quot;unused&quot;<\/span><span class=\"o\">)<\/span><\/div><div class=\'line\' id=\'LC31\'><span class=\"kd\">public<\/span> <span class=\"kd\">class<\/span> <span class=\"nc\">CacheMonitorBTrace<\/span> <span class=\"o\">{<\/span><\/div><div class=\'line\' id=\'LC32\'><br/><\/div><div class=\'line\' id=\'LC33\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"c1\">// This field will be exported as a JStat counter.<\/span><\/div><div class=\'line\' id=\'LC34\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@Export<\/span><\/div><div class=\'line\' id=\'LC35\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">long<\/span> <span class=\"n\">dataAccessed<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC36\'><br/><\/div><div class=\'line\' id=\'LC37\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"c1\">// This field will be exported to the MBean server.<\/span><\/div><div class=\'line\' id=\'LC38\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@Property<\/span><\/div><div class=\'line\' id=\'LC39\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">long<\/span> <span class=\"n\">dataCreated<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC40\'><br/><\/div><div class=\'line\' id=\'LC41\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@Property<\/span><\/div><div class=\'line\' id=\'LC42\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">long<\/span> <span class=\"n\">cacheChecked<\/span><span class=\"o\">;<\/span><\/div><div class=\'line\' id=\'LC43\'><br/><\/div><div class=\'line\' id=\'LC44\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"n\">Aggregation<\/span> <span class=\"n\">methodDuration<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Aggregations<\/span><\/div><div class=\'line\' id=\'LC45\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"o\">.<\/span><span class=\"na\">newAggregation<\/span><span class=\"o\">(<\/span><span class=\"n\">AggregationFunction<\/span><span class=\"o\">.<\/span><span class=\"na\">AVERAGE<\/span><span class=\"o\">);<\/span><\/div><div class=\'line\' id=\'LC46\'><br/><\/div><div class=\'line\' id=\'LC47\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"cm\">/**<\/span><\/div><div class=\'line\' id=\'LC48\'><span class=\"cm\">     * We want to measure how long does the DataAcccesor#getData(-)<\/span><\/div><div class=\'line\' id=\'LC49\'><span class=\"cm\">     * method execution take.<\/span><\/div><div class=\'line\' id=\'LC50\'><span class=\"cm\">     */<\/span><\/div><div class=\'line\' id=\'LC51\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@OnMethod<\/span><span class=\"o\">(<\/span><span class=\"n\">clazz<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;com.piotrnowicki.btrace.DataAccessor&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC52\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">method<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;getData&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC53\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">location<\/span> <span class=\"o\">=<\/span> <span class=\"nd\">@Location<\/span><span class=\"o\">(<\/span><span class=\"n\">Kind<\/span><span class=\"o\">.<\/span><span class=\"na\">RETURN<\/span><span class=\"o\">))<\/span><\/div><div class=\'line\' id=\'LC54\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">public<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">void<\/span> <span class=\"nf\">addMethodDuration<\/span><span class=\"o\">(<\/span><span class=\"nd\">@Duration<\/span> <span class=\"kt\">long<\/span> <span class=\"n\">duration<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span><\/div><div class=\'line\' id=\'LC55\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">Aggregations<\/span><span class=\"o\">.<\/span><span class=\"na\">addToAggregation<\/span><span class=\"o\">(<\/span><span class=\"n\">methodDuration<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC56\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">duration<\/span> <span class=\"o\">/<\/span> <span class=\"mi\">1000<\/span><span class=\"o\">);<\/span><\/div><div class=\'line\' id=\'LC57\'><br/><\/div><div class=\'line\' id=\'LC58\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">dataAccessed<\/span><span class=\"o\">++;<\/span><\/div><div class=\'line\' id=\'LC59\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"o\">}<\/span><\/div><div class=\'line\' id=\'LC60\'><br/><\/div><div class=\'line\' id=\'LC61\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"cm\">/**<\/span><\/div><div class=\'line\' id=\'LC62\'><span class=\"cm\">     * Invoked whenever WeakReference#get(-) is invoked from the <\/span><\/div><div class=\'line\' id=\'LC63\'><span class=\"cm\">     * DataAccessor#getData(-) method.<\/span><\/div><div class=\'line\' id=\'LC64\'><span class=\"cm\">     */<\/span><\/div><div class=\'line\' id=\'LC65\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@OnMethod<\/span><span class=\"o\">(<\/span><span class=\"n\">clazz<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;com.piotrnowicki.btrace.DataAccessor&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC66\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">method<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;getData&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC67\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">location<\/span> <span class=\"o\">=<\/span> <span class=\"nd\">@Location<\/span><span class=\"o\">(<\/span><span class=\"n\">value<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Kind<\/span><span class=\"o\">.<\/span><span class=\"na\">CALL<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC68\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">clazz<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;java.lang.ref.WeakReference&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC69\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">method<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;get&quot;<\/span><span class=\"o\">))<\/span><\/div><div class=\'line\' id=\'LC70\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">public<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">void<\/span> <span class=\"nf\">cacheChecked<\/span><span class=\"o\">(<\/span><\/div><div class=\'line\' id=\'LC71\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@TargetMethodOrField<\/span><span class=\"o\">(<\/span><span class=\"n\">fqn<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">true<\/span><span class=\"o\">)<\/span> <span class=\"n\">String<\/span> <span class=\"n\">method<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span><\/div><div class=\'line\' id=\'LC72\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">println<\/span><span class=\"o\">(<\/span><span class=\"n\">strcat<\/span><span class=\"o\">(<\/span><span class=\"s\">&quot;Cache check invoked; method: &quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">method<\/span><span class=\"o\">));<\/span><\/div><div class=\'line\' id=\'LC73\'><br/><\/div><div class=\'line\' id=\'LC74\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">cacheChecked<\/span><span class=\"o\">++;<\/span><\/div><div class=\'line\' id=\'LC75\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"o\">}<\/span><\/div><div class=\'line\' id=\'LC76\'><br/><\/div><div class=\'line\' id=\'LC77\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"cm\">/**<\/span><\/div><div class=\'line\' id=\'LC78\'><span class=\"cm\">     * Invoked when any method from DataAccessor class is entered.<\/span><\/div><div class=\'line\' id=\'LC79\'><span class=\"cm\">     */<\/span><\/div><div class=\'line\' id=\'LC80\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@OnMethod<\/span><span class=\"o\">(<\/span><span class=\"n\">clazz<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;com.piotrnowicki.btrace.DataAccessor&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC81\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">method<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;/.*/&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC82\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">location<\/span> <span class=\"o\">=<\/span> <span class=\"nd\">@Location<\/span><span class=\"o\">(<\/span><span class=\"n\">value<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Kind<\/span><span class=\"o\">.<\/span><span class=\"na\">ENTRY<\/span><span class=\"o\">))<\/span><\/div><div class=\'line\' id=\'LC83\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">public<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">void<\/span> <span class=\"nf\">dataAccessorMethodEntry<\/span><span class=\"o\">(<\/span><\/div><div class=\'line\' id=\'LC84\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@ProbeClassName<\/span> <span class=\"n\">String<\/span> <span class=\"n\">className<\/span><span class=\"o\">,<\/span><\/div><div class=\'line\' id=\'LC85\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@ProbeMethodName<\/span> <span class=\"n\">String<\/span> <span class=\"n\">probeMethod<\/span><span class=\"o\">,<\/span><\/div><div class=\'line\' id=\'LC86\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">AnyType<\/span><span class=\"o\">[]<\/span> <span class=\"n\">args<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span><\/div><div class=\'line\' id=\'LC87\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">println<\/span><span class=\"o\">(<\/span><span class=\"n\">Strings<\/span><span class=\"o\">.<\/span><span class=\"na\">strcat<\/span><span class=\"o\">(<\/span><span class=\"s\">&quot;Entered method: &quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">probeMethod<\/span><span class=\"o\">));<\/span><\/div><div class=\'line\' id=\'LC88\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">printArray<\/span><span class=\"o\">(<\/span><span class=\"n\">args<\/span><span class=\"o\">);<\/span><\/div><div class=\'line\' id=\'LC89\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"o\">}<\/span><\/div><div class=\'line\' id=\'LC90\'><br/><\/div><div class=\'line\' id=\'LC91\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"cm\">/**<\/span><\/div><div class=\'line\' id=\'LC92\'><span class=\"cm\">     * Invoked whenever new Data object is created from <\/span><\/div><div class=\'line\' id=\'LC93\'><span class=\"cm\">     * DataAccessor#getData(-) method.<\/span><\/div><div class=\'line\' id=\'LC94\'><span class=\"cm\">     */<\/span><\/div><div class=\'line\' id=\'LC95\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@OnMethod<\/span><span class=\"o\">(<\/span><span class=\"n\">clazz<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;com.piotrnowicki.btrace.DataAccessor&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC96\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">method<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;getData&quot;<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC97\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">location<\/span> <span class=\"o\">=<\/span> <span class=\"nd\">@Location<\/span><span class=\"o\">(<\/span><span class=\"n\">value<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Kind<\/span><span class=\"o\">.<\/span><span class=\"na\">NEW<\/span><span class=\"o\">,<\/span> <\/div><div class=\'line\' id=\'LC98\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">clazz<\/span> <span class=\"o\">=<\/span> <span class=\"s\">&quot;com.piotrnowicki.btrace.Data&quot;<\/span><span class=\"o\">))<\/span><\/div><div class=\'line\' id=\'LC99\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">public<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">void<\/span> <span class=\"nf\">dataCreated<\/span><span class=\"o\">()<\/span> <span class=\"o\">{<\/span><\/div><div class=\'line\' id=\'LC100\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">dataCreated<\/span><span class=\"o\">++;<\/span><\/div><div class=\'line\' id=\'LC101\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"o\">}<\/span><\/div><div class=\'line\' id=\'LC102\'><br/><\/div><div class=\'line\' id=\'LC103\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"cm\">/**<\/span><\/div><div class=\'line\' id=\'LC104\'><span class=\"cm\">     * Invoked every 10 seconds - not a real probe.<\/span><\/div><div class=\'line\' id=\'LC105\'><span class=\"cm\">     */<\/span><\/div><div class=\'line\' id=\'LC106\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"nd\">@OnTimer<\/span><span class=\"o\">(<\/span><span class=\"n\">value<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">10000<\/span><span class=\"o\">)<\/span><\/div><div class=\'line\' id=\'LC107\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"kd\">public<\/span> <span class=\"kd\">static<\/span> <span class=\"kt\">void<\/span> <span class=\"nf\">printAvgMethodDuration<\/span><span class=\"o\">()<\/span> <span class=\"o\">{<\/span><\/div><div class=\'line\' id=\'LC108\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"n\">Aggregations<\/span><span class=\"o\">.<\/span><span class=\"na\">printAggregation<\/span><span class=\"o\">(<\/span><\/div><div class=\'line\' id=\'LC109\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"s\">&quot;Average method duration (ms)&quot;<\/span><span class=\"o\">,<\/span> <span class=\"n\">methodDuration<\/span><span class=\"o\">);<\/span><\/div><div class=\'line\' id=\'LC110\'>&nbsp;&nbsp;&nbsp;&nbsp;<span class=\"o\">}<\/span><\/div><div class=\'line\' id=\'LC111\'><span class=\"o\">}<\/span><\/div><div class=\'line\' id=\'LC112\'><br/><\/div><div class=\'line\' id=\'LC113\'><br/><\/div><\/pre><\/div>\n          <\/div>\n\n          <div class=\"gist-meta\">\n            <a href=\"https://gist.github.com/raw/2594661/29f77fb572924616c360d9b1a9917d3e74222d80/CacheMonitorBTrace.java\" style=\"float:right;\">view raw<\/a>\n            <a href=\"https://gist.github.com/2594661#file_cache_monitor_b_trace.java\" style=\"float:right;margin-right:10px;color:#666\">CacheMonitorBTrace.java<\/a>\n            <a href=\"https://gist.github.com/2594661\">This Gist<\/a> brought to you by <a href=\"http://github.com\">GitHub<\/a>.\n          <\/div>\n        <\/div>\n<\/div>\n')
</script><div style='margin-bottom:1em;padding:0;'><noscript><code><pre style='overflow:auto;margin:0;padding:0;border:1px solid #DDD;'>package com.piotrnowicki.btrace;

import static com.sun.btrace.BTraceUtils.printArray;
import static com.sun.btrace.BTraceUtils.println;
import static com.sun.btrace.BTraceUtils.strcat;

import java.lang.ref.WeakReference;

import com.sun.btrace.AnyType;
import com.sun.btrace.BTraceUtils.Aggregations;
import com.sun.btrace.BTraceUtils.Strings;
import com.sun.btrace.aggregation.Aggregation;
import com.sun.btrace.aggregation.AggregationFunction;
import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Duration;
import com.sun.btrace.annotations.Export;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.OnTimer;
import com.sun.btrace.annotations.ProbeClassName;
import com.sun.btrace.annotations.ProbeMethodName;
import com.sun.btrace.annotations.Property;
import com.sun.btrace.annotations.TargetMethodOrField;

// @BTrace means that this class will be used to define probes 
// and actions. All fields and methods must be static. 
// You can use only BTraceUtils methods.
@BTrace
@SuppressWarnings(&quot;unused&quot;)
public class CacheMonitorBTrace {

    // This field will be exported as a JStat counter.
    @Export
    private static long dataAccessed;

    // This field will be exported to the MBean server.
    @Property
    private static long dataCreated;

    @Property
    private static long cacheChecked;

    private static Aggregation methodDuration = Aggregations
            .newAggregation(AggregationFunction.AVERAGE);

    /**
     * We want to measure how long does the DataAcccesor#getData(-)
     * method execution take.
     */
    @OnMethod(clazz = &quot;com.piotrnowicki.btrace.DataAccessor&quot;, 
            method = &quot;getData&quot;, 
            location = @Location(Kind.RETURN))
    public static void addMethodDuration(@Duration long duration) {
        Aggregations.addToAggregation(methodDuration, 
                                      duration / 1000);

        dataAccessed++;
    }

    /**
     * Invoked whenever WeakReference#get(-) is invoked from the 
     * DataAccessor#getData(-) method.
     */
    @OnMethod(clazz = &quot;com.piotrnowicki.btrace.DataAccessor&quot;, 
            method = &quot;getData&quot;, 
            location = @Location(value = Kind.CALL, 
                          clazz = &quot;java.lang.ref.WeakReference&quot;, 
                          method = &quot;get&quot;))
    public static void cacheChecked(
            @TargetMethodOrField(fqn = true) String method) {
        println(strcat(&quot;Cache check invoked; method: &quot;, method));

        cacheChecked++;
    }

    /**
     * Invoked when any method from DataAccessor class is entered.
     */
    @OnMethod(clazz = &quot;com.piotrnowicki.btrace.DataAccessor&quot;, 
            method = &quot;/.*/&quot;, 
            location = @Location(value = Kind.ENTRY))
    public static void dataAccessorMethodEntry(
                       @ProbeClassName String className,
                       @ProbeMethodName String probeMethod,
                       AnyType[] args) {
        println(Strings.strcat(&quot;Entered method: &quot;, probeMethod));
        printArray(args);
    }

    /**
     * Invoked whenever new Data object is created from 
     * DataAccessor#getData(-) method.
     */
    @OnMethod(clazz = &quot;com.piotrnowicki.btrace.DataAccessor&quot;, 
            method = &quot;getData&quot;, 
            location = @Location(value = Kind.NEW, 
                           clazz = &quot;com.piotrnowicki.btrace.Data&quot;))
    public static void dataCreated() {
        dataCreated++;
    }

    /**
     * Invoked every 10 seconds - not a real probe.
     */
    @OnTimer(value = 10000)
    public static void printAvgMethodDuration() {
        Aggregations.printAggregation(
                &quot;Average method duration (ms)&quot;, methodDuration);
    }
}

</pre></code></noscript></div>
<p>All information about different probes locations as well as the requirements for the BTrace script methods and fields can be found <a href="http://kenai.com/projects/btrace/pages/UserGuide">here</a>, so I won&#8217;t duplicate it.</p>
<p>However, I&#8217;ll try to explain what does the <code>@OnMethod</code> really do as it was quite unclear for me when I was writing the script.</p>
<p>Basically, all <code>@OnMethod</code> annotations define places where probes should be applied to the source code. The <code>@Location</code> allows you to further narrow the probe location. So:</p>
<pre><code>@OnMethod(clazz = "com.piotrnowicki.btrace.DataAccessor",
          method = "getData",
          location = @Location(Kind.RETURN))
public static void addMethodDuration(@Duration long duration) {...}
</code></pre>
<p>means that when the control will return from the <code>DataAccessor#getData(-)</code> method&#8217;s body, the probe will be activated (body of the <code>addMethodDuration</code> method will be invoked.)<br />
The <code>Kind.Return</code> is required when you want to use <code>@Duration</code> annotated argument. It&#8217;s quite reasonable &#8211; if you want to know how long did the method body take, you need to probe just before the return statement.</p>
<hr />
<pre><code>@OnMethod(clazz = "com.piotrnowicki.btrace.DataAccessor",
          method = "getData",
          location = @Location(value = Kind.CALL,
                               clazz = "java.lang.ref.WeakReference",
                               method = "get"))
public static void cacheCheckHit(
                @TargetMethodOrField(fqn = true) String method) {...}
</code></pre>
<p>means that we want to set a probe in <code>DataAccessor#getData(-)</code> method (<code>clazz</code> and <code>method</code> attributes) but we&#8217;re interested only in calls to the <code>WeakReference#get(-)</code> from within the <code>DataAccessor#getData(-)</code> method (<code>location</code> attribute). Only when such call is made, the probe will be activated.</p>
<hr />
<pre><code>@OnMethod(clazz = "com.piotrnowicki.btrace.DataAccessor",
          method = "/.*/",
          location = @Location(value = Kind.ENTRY))
public static void dataAccessorMethodEntry(
                             @ProbeClassName String className,
                             @ProbeMethodName String probeMethod,
                             AnyType[] args) {...}
</code></pre>
<p>means that we want to set a probe in any method within the <code>DataAccessor</code> class (<code>clazz</code> and <code>method</code> attributes) but we&#8217;re interested only in dependent methods entry events (<code>location</code>.)</p>
<hr />
<pre><code>@OnMethod(clazz = "com.piotrnowicki.btrace.DataAccessor",
          method = "getData",
          location = @Location(value = Kind.NEW,
                             clazz = "com.piotrnowicki.btrace.Data"))
public static void dataCreated() {...}
</code></pre>
<p>means that we want to set a probe in <code>DataAccessor#getData(-)</code> method (<code>clazz</code> and <code>method</code> attributes) but the probe will be activated only upon instantiation of the <code>Data</code> objects within this method (<code>location</code>.)</p>
<h3 id="toc-ways-of-getting-the-results">Ways of Getting the Results</h3>
<p>There are a couple of ways to get the results back from your probes. You can either:</p>
<ol>
<li>
<p>print it to the output using <code>print(-)</code> methods: println(Strings.strcat(&#8220;Entered method: &#8220;, probeMethod));</p>
</li>
<li>
<p>export the value to the <code>jstat</code> counter using <code>@Export</code> annotation on the field level: @Export private static long dataAccessed</p>
</li>
<li>
<p>export it to the MBeans server using <code>@Property</code> on the field level: @Property private static long dataCreated;</p>
</li>
</ol>
<p>I personally like the third option the most because it allows me to easily view the value of the variable from the VisualVM as well as <strong>show plotted historical values of it</strong>.<br />
The first option, however, is the fastest as you can see the results on your screen just after you hit the &#8220;Start&#8221; button.</p>
<h3 id="toc-invoking-the-script">Invoking the Script</h3>
<p>If the application you will instrument is already running, you can run the VisualVM (<code>$JAVA_HOME/bin/jvisualvm</code> on the linux boxes) and find your application on the left hand side list. Double click it to inspect it (if you have never used the VisualVM &#8211; it&#8217;s a good time to see what information about running processes it provides.)<br />
At this moment, the BTrace tab might not be visible as you probably need to install the appropriate plugin. Just go to <code>Tools-&gt;Plugins-&gt;Available Plugins</code> and install the BTrace one.</p>
<p>Now if you once again open your application in VisualVM, the BTrace tab <strong>might still not be visible</strong>. If so, then you need to RMB click the application on the left hand side list and select &#8220;<strong>Trace application&#8230;</strong>&#8221; option as shown below:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_TraceAppVisualVM.png"><img src="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_TraceAppVisualVM.png" alt="BTrace - Start Tracing" title="BTrace - Start Tracing" width="300" height="162" class="aligncenter size-medium wp-image-996" /></a></p>
<p>The BTrace tab should be shown &#8211; choose it and you can type your BTrace script directly on the shown form. Just hit &#8220;Start&#8221; and your script will be weaved into the selected application.<br />
Personally, I&#8217;d advise you to use the <code>Open...</code> button and select the BTrace script on your disk. In this way, every time you&#8217;ll edit the script source file, click &#8220;Trace application&#8230;&#8221; and proceed to the BTrace tab, the actual version of your script will be loaded.</p>
<p>If you&#8217;ve selected my exemplary application to be instrument and the provided BTrace script provided, just hit the &#8220;Start&#8221; button and the monitoring will start. You should see a bunch of information in the output window (&#8220;entry points&#8221; and &#8220;cache hits&#8221; messages) as shown in the below screenshot:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_ShowOutput.png"><img src="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_ShowOutput-300x164.png" alt="BTrace - Show Output" title="BTrace - Show Output" width="300" height="164" class="aligncenter size-medium wp-image-997" /></a></p>
<p>Note that one of the probe actions gathers the duration of the method execution and aggregates it using <a href="http://btrace.kenai.com/javadoc/1.2/com/sun/btrace/aggregation/Aggregation.html">Aggregation</a> class. I&#8217;m using the aggregated values in a <a href="http://btrace.kenai.com/javadoc/1.2/com/sun/btrace/aggregation/AggregationFunction.html#AVERAGE">AVERAGE</a> mode, so every 10 seconds, it&#8217;s printing the average method duration on the screen.</p>
<h3 id="toc-jstat-counter-access">JStat Counter Access</h3>
<p>Besides the console output, you can observe the probe results of three other variables. One of them, <code>dataAccessed</code>, is exported as a <code>jstat</code> counter and can be accessed from a command line. For the provided example, type <code>jps</code> and locate your monitored application PID. Then type:</p>
<pre><code>jstat -J-Djstat.showUnsupported=true \
   -name btrace.com.piotrnowicki.btrace.MyClass.dataAccessed 14207
</code></pre>
<p>Of course <strong>replacing the <code>14207</code> with the PID you&#8217;ve read from the previous command</strong>. The <code>-Djstat.showUnsupported=true</code> is required to show your own defined counters.<br />
<strong>Note</strong> that the name of the counter is <strong>not</strong> just the fully qualified name of the field &#8211; <strong>it&#8217;s prefixed with the <code>btrace.</code></strong></p>
<p>There is another way you can access the counter:</p>
<pre><code>jstat -J-Djstat.showUnsupported=true -snap 1420
</code></pre>
<p>which will show you all counters for a given PID. You can further narrow the results using regular shell commands, e.g.:</p>
<pre><code>jstat -J-Djstat.showUnsupported=true -snap 14207|grep dataAccessed
</code></pre>
<p>the result should recall something like this:</p>
<pre><code>btrace.com.piotrnowicki.btrace.MyClass.dataAccessed=189
</code></pre>
<h3 id="toc-mbeans-access">MBeans Access</h3>
<p>There are also two fields that are accessible through the MBeans server. Simply click on the <code>MBeans</code> tab in the VisualVM and expand the <code>com.piotrnowicki.btrace.MyClass</code>. You should see two properties: <code>dataCreated</code> and <code>cacheChecked</code>. After double-clicking on the value you can see a timeline &#8211; a historical values of the counter value plotted on the graph.<br />
If you&#8217;ve executed my source code and BTrace script, try to inspect the <code>dataCreated</code> value. You should see something like on the screen below:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_TimelineValues.png"><img src="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_TimelineValues-300x162.png" alt="BTrace - Show Historical Values" title="BTrace - Show Historical Values" width="300" height="162" class="aligncenter size-medium wp-image-1000" /></a></p>
<h3 id="toc-weak-references-and-garbage-collection">Weak References and Garbage Collection</h3>
<p>The above results actually depends on your JVM settings, but the point is: we create a random integer number from the range &lt;0, 100) as a key for our cached data.<br />
If this key <strong>exists</strong> in the cache, we retrieve the data it holds and return.<br />
If this key <strong>doesn&#8217;t exist</strong> in the cache, we <strong>create the data</strong>, save it in cache and return it.</p>
<p>So, basically, the above counter is not measuring cache hits but <strong>cache misses</strong> (every cache miss is followed by instantiation of the <code>Data</code> object and its insertion to the cache.)<br />
After some time, we should have more and more hits to the cache, therefore less data should be created. You might expect that the Y axis value will finally get to the 100 and stay there till the application ends.</p>
<p>It&#8217;s true, but only if we&#8217;d use <strong>strong references</strong>. In the exemplary code I&#8217;ve used <code>WeakReferences</code> as discussed before. This means that we can observe more than 100 objects created, because after some time, the GC decides to move in and clear some of all our <code>Data</code> instances. It happens because they&#8217;re referenced only from the single point of the process and this only reference is weak.<br />
This is what you can observe on the following screenshot:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_WeakReferences.png"><img src="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_WeakReferences-280x300.png" alt="BTrace - Weak References GC" title="BTrace - Weak References GC" width="280" height="300" class="aligncenter size-medium wp-image-1005" /></a></p>
<p>Notice the point where the value of <code>dataCreated</code> is fairly constant; it means that almost no new <code>Data</code> is created, so we have many cache hits. Take a look at the memory consumption at the same point of time.</p>
<p>When the GC is cleaning up the memory, <code>Data</code> instances are garbage collected and we need to refill our cache (so we need to create a new <code>Data</code> objects). At the same point of time, we&#8217;ve got huge increase of <code>dataCreated</code> value.<br />
You don&#8217;t have to wait for automatic GC but you can try hitting the &#8220;Perform GC&#8221; button in the &#8220;Monitor&#8221; tab to send a request for GC to be executed.</p>
<h3 id="toc-strong-references-and-garbage-collection">Strong References and Garbage Collection</h3>
<p>Now, if we try to change the <code>WeakReference</code> to the strong reference and adjust the code so it works on <code>Data</code> instead of <code>WeakReference&lt;data&gt;</code> the results will look like this:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_StrongReferences.png"><img src="http://piotrnowicki.com/website/wp-content/media/2012/05/BTrace_StrongReferences-280x300.png" alt="BTrace - Strong References GC" title="BTrace - Strong References GC" width="280" height="300" class="aligncenter size-medium wp-image-1006" /></a></p>
<p>Note that we&#8217;re trying to reach a 100 created <code>Data</code> objects and we&#8217;re not going any further than this number. We&#8217;ve got many cache hits and this time, we&#8217;re not affected by the Garbage Collector actions (but they do occur as you can see in the graph.)<br />
Don&#8217;t take the <code>cacheChecked</code> value under consideration at this point. This property is probed only when weak references are used.</p>
<h3 id="toc-overhead">Overhead</h3>
<p>The overhead of BTrace script should be minimal and that is one of the most important part of the project. It should be as non-intrusive and safe as possible. However, if you&#8217;re using e.g. the <code>@Property</code> annotation, you need to access the MBeans server so this is some additional overhead.</p>
<p>If you use massive print statements, string concatenations, aggregations in your probe actions &#8211; it also doesn&#8217;t come without a cost. Notice that there is also an &#8220;Unsafe&#8221; checkbox in the BTrace tab. If you check it, you&#8217;re all by yourself and <strong>there are many ways you can harm the performance and yourself</strong>.</p>
<h3 id="toc-summary">Summary</h3>
<p>The BTrace seems to be nice, fast and easy way to access and instrument your running Java application. It doesn&#8217;t require you to use any special tools &#8212; you can monitor every process on the JVM and thanks to the VisualVM plugin &#8211; you can change the script on-the-fly.<br />
It&#8217;s not the ultimate tool for Java monitoring. You might as well use other solutions already built in in your servlet container (like <a href="http://code.google.com/p/psi-probe/">psi-probe</a>) or application server (like <a href="http://www.youtube.com/watch?v=nBqSh7nVNzc">SpringSource Insight</a>).<br />
Nevertheless, it&#8217;s a nice, low-level solution for monitoring <strong>any</strong> running Java application and it doesn&#8217;t require your source code to be executed in any specialized environment.</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/05/btrace-a-simple-way-to-instrument-running-java-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>One Servlet Instance to Rule Them All&#8230;</title>
		<link>http://piotrnowicki.com/2012/04/one-servlet-instance-to-rule-them-all/</link>
		<comments>http://piotrnowicki.com/2012/04/one-servlet-instance-to-rule-them-all/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 09:53:21 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[instance]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[servlets]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=897</guid>
		<description><![CDATA[I see a lot of people saying that: &#8220;there is only one instance of servlet per application&#8221;. Surely it gives you some information and knowing this will save you from a lot of strange, unexpected errors. However, the above statement is not very accurate and precise. It&#8217;s useful to know what is the actual contract [...]]]></description>
			<content:encoded><![CDATA[<p>I see a lot of people saying that:</p>
<blockquote>
<p><strong>&#8220;there is only one instance of servlet per application&#8221;</strong>.</p>
</blockquote>
<p>Surely it gives you some information and knowing this will save you from a lot of strange, unexpected errors.  However, the above statement is not very accurate and precise. It&#8217;s useful to know what is the actual contract between the web container and developer.<br />
Moreover, a lot of questions arise because of the multi-threading issues, so let me sum this up backing my words with Servlet 3.0 Maintenance Release specification:</p>
<p>Assuming we&#8217;re working in a non-distributed environment, there is only <strong>one servlet instance</strong> per <strong>definition</strong>:</p>
<p><strong>2.2 Number of Instances</strong></p>
<blockquote>
<p>For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration.</p>
</blockquote>
<p>So, it&#8217;s <strong>not allowed</strong> for the container to <strong>pool</strong> servlet instances. There is a strict requirement that there is only <strong>one</strong> instance per <strong>definition</strong>. This <em>per definition</em> part is also important because if you define two servlets with different names but referring to the same class, you&#8217;ll end with <strong>different instances</strong> of this servlet:</p>
<pre>
&lt;servlet&gt;
    &lt;servlet-name&gt;servlet1&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.myservlet.MyServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet&gt;
    &lt;servlet-name&gt;servlet2&lt;/servlet-namesss&gt;
    &lt;servlet-class&gt;com.myservlet.MyServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
</pre>
<p>However, <strong>the number of servlet instances can also be affected by implementing deprecated <code>SingleThreadModel</code></strong>. This interface is supposed to ensure that only one <code>Thread</code> can access the Servlet at a given time. Therefore, it might do so by serializing requests or by <strong>pooling</strong> multiple servlet instances:</p>
<p><strong>2.2 Number of Instances</strong></p>
<blockquote>
<p>However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.</p>
</blockquote>
<p>Finally, if you mark your web application as a distributed application (<code>&lt;distributable /&gt;</code> sub-element of the <code>&lt;web-app&gt;</code> in <code>web.xml</code>) <strong>and</strong> you will implement depreciated <code>SingleThreadModel</code> than you can end with <strong>a pool of servlet instances per definition in each of the JVM</strong> of your distributed environment:</p>
<p><strong>2.2 Number of Instances</strong></p>
<blockquote>
<p>However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each JVM of the container.</p>
</blockquote>
<p>As you can see the answer <em>&#8220;there is only one servlet instance&#8221;</em> is not very precise. It gives you an important information regarding multi-threading, but it&#8217;s not 100% complete and precise.</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/04/one-servlet-instance-to-rule-them-all/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Odd Colors in Ubuntu&#8217;s Flash Player</title>
		<link>http://piotrnowicki.com/2012/04/odd-colors-in-ubuntus-flash-player/</link>
		<comments>http://piotrnowicki.com/2012/04/odd-colors-in-ubuntus-flash-player/#comments</comments>
		<pubDate>Sat, 28 Apr 2012 09:52:13 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[colors]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=899</guid>
		<description><![CDATA[After one of the Ubuntu 11.10 updates I was affected by some really weird colors in the embedded flash player. Basically, every movie looked similar to the one below (notice the dominance of the bluish color): The solution is to disable hardware acceleration in Flash Player settings (RMB -&#62; Settings) just as shown here: After [...]]]></description>
			<content:encoded><![CDATA[<p>After one of the Ubuntu 11.10 updates I was affected by some really weird colors in the embedded flash player. Basically, every movie looked similar to the one below (notice the dominance of the bluish color):</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/04/before.jpg"><img src="http://piotrnowicki.com/website/wp-content/media/2012/04/before-300x230.jpg" alt="" title="Odd Colors in Flash Player" width="300" height="230" class="aligncenter size-medium wp-image-902" /></a></p>
<p>The solution is to disable hardware acceleration in Flash Player settings (<code>RMB -&gt; Settings</code>) just as shown here:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/04/setting.jpg"><img src="http://piotrnowicki.com/website/wp-content/media/2012/04/setting-300x232.jpg" alt="" title="Odd Colors in Flash Player (changing settings)" width="300" height="232" class="aligncenter size-medium wp-image-900" /></a></p>
<p>After unchecking this option and refreshing the page all videos were back to normal:</p>
<p><a href="http://piotrnowicki.com/website/wp-content/media/2012/04/after.jpg"><img src="http://piotrnowicki.com/website/wp-content/media/2012/04/after-300x235.jpg" alt="" title="Odd Colors in Flash Player (after)" width="300" height="235" class="aligncenter size-medium wp-image-901" /></a></p>
<p>I&#8217;m not sure if I even want to know why one update could mess up so bad with the Flash Player. In fact, I&#8217;m pretty sure that the Flash Player is <strong>one of the best way to crash your Ubuntu box</strong>. In fact on my Dell Vostro 3555 it randomly restarts the X Window Server&#8230; <em>sigh</em>.</p>
<p>Nevertheless, <em>the world has been saved one more time.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/04/odd-colors-in-ubuntus-flash-player/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>To FEST or not to FEST?</title>
		<link>http://piotrnowicki.com/2012/04/to-fest-or-not-to-fest/</link>
		<comments>http://piotrnowicki.com/2012/04/to-fest-or-not-to-fest/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 09:58:09 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[assertion]]></category>
		<category><![CDATA[fest]]></category>
		<category><![CDATA[hamcrest]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=889</guid>
		<description><![CDATA[When you write your unit tests you must use some kind of assertions. I think that most of you will agree with me on that the asserts that comes with the JUnit aren&#8217;t the easiest and most readable ones. So, some time ago I started to use a Hamcrest matcher library. It was a great [...]]]></description>
			<content:encoded><![CDATA[<p>When you write your unit tests you must use some kind of assertions. I think that most of you will agree with me on that the asserts that comes with the <em>JUnit</em> aren&#8217;t the easiest and most readable ones.</p>
<p>So, some time ago I started to use a <a href="http://code.google.com/p/*Hamcrest*/"><em>Hamcrest</em></a> matcher library. It was a great progress, as I was able to move away from JUnit&#8217;s unintuitive: <code>assertEquals(11.0, actual)</code>. I mean, if you try to read it out loud it doesn&#8217;t seem very logical:<br />
  <em>&#8220;assert equals 11 is <code>actual</code>&#8220;</em>,<br />
  <em>&#8220;assert equals 11 as <code>actual</code>&#8220;</em>?.</p>
<p>Moreover, the <code>expected</code> value is the first argument and the <code>actual</code> one is the latter which also makes it harder to understand.</p>
<p>And here comes the <code>*Hamcrest*</code> matcher which brings a fluent API consisting of a lot of useful methods. So, right now you can write: <code>assertThat(actual, is(11.0))</code>. This is much more readable as it stands for:<br />
  &#8220;Assert that <code>actual</code> is 11.0&#8243;.<br />
No magic here, everything is understandable and you don&#8217;t have to think which parameter is the <code>expected</code> and which is the <code>actual</code> one.</p>
<p><a href="http://code.google.com/p/fest/"><em>FEST Fluent Assertions</em></a> brings very similar features to the table but it takes quite different approach.<br />
In <em>Hamcrest</em> you usually use the one-line per one assert approach. It means that if you want to check if <code>myVal</code> is in range between 4 and 6, you would need to write two assertions (sure, you can always write your own matcher that will do it in one line, but that&#8217;s not the point in this case):</p>
<pre><code>assertThat(myVal, is(greaterThan(4));
assertThat(myVal, is(lessThan(6));
</code></pre>
<p><em>FEST Fluent Assertions</em> uses the chain method invocation to do the same thing, so in FEST-like approach you&#8217;d rather write:</p>
<pre><code>assertThat(myVal).isGreaterThan(4).isLessThan(6);
</code></pre>
<p>You can still read it very naturally and it saved some writing.</p>
<p>There are some more differences between <em>Hamcrest</em> and <em>FEST Fluent Assertions</em>. Some of them are more important, like differences in writing your own matchers and/or conditions.<br />
Others are less important, like the number of static imports: lots in <em>Hamcrest</em>, only one in <em>FEST Fluent Assertions</em>. However, this <em>Hamcrest</em>&#8216;s disadvantage, can be easily solved using type import static or using the Eclipse support as described in <a href="http://piotrnowicki.com/2012/04/content-assist-with-static-imports-in-eclipse/">my previous post</a></p>
<p>There is no, obvious choice between <em>Hamcrest</em> and <em>FEST Fluent Assertions</em>. Both of them give you a very nice and elastic fluent assertions mechanism and which one you choose depends on team, your programming habits or some particular requirements. Either it will be <em>Hamcrest</em> or <em>FEST Fluent Assertions</em>, <strong>it will definitely be better than the assertions that come out-of-the-box with JUnit</strong>.</p>
<p>I think that the most important fact here is that <strong>you really should use easy to read matchers library</strong>. It makes not only the code more obvious for your team, easier to maintain (it&#8217;s worth emphasizing that your test code is also a part of your project &#8211; <strong>it needs to be maintained</strong>!) but in some situations it even allows you to show some test cases to the business people with the domain knowledge you need. It allows to reduce domain understanding problems.<br />
Moving even further, if you plan to use Scala (or any other JVM language which allows you to omit spaces or parentheses in method invocations), your code can be much more like a DSL (Domain Specific Language): <code>assertThat actual isEqualTo 11.0</code>. <strong>It&#8217;s really worth trying it out</strong>.</p>
<p>You can read about differences between <em>Hamcrest</em> and <em>FEST Fluent Assertions</em> in more details on <a href="http://www.samlewis.me/fluent-assertions-fest/">Sam Lewis&#8217; blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/04/to-fest-or-not-to-fest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Content Assist With Static Imports in Eclipse</title>
		<link>http://piotrnowicki.com/2012/04/content-assist-with-static-imports-in-eclipse/</link>
		<comments>http://piotrnowicki.com/2012/04/content-assist-with-static-imports-in-eclipse/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 15:58:13 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[hamcrest]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[static]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=870</guid>
		<description><![CDATA[If you&#8217;re using Eclipse and working with a class with a lot of static members, you might be affected by the problem of lack of content assist and automatic import for such members. Let&#8217;s say you&#8217;re using a Hamcrest matchers; you need a is(), notNullValue(), hasEntry() and so on (there are plenty of those). You [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re using Eclipse and working with a class with a lot of static members, you might be affected by the problem of lack of content assist and automatic import for such members. Let&#8217;s say you&#8217;re using a <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> matchers; you need a <code>is()</code>, <code>notNullValue()</code>, <code>hasEntry()</code> and so on (there are <a href="http://hamcrest.googlecode.com/svn/trunk/hamcrest-java/matchers.xml">plenty of those</a>). You don&#8217;t want to type <code>Matchers.hasEntry()</code> every time you use it in your code. Hey, that&#8217;s not why the fluent API was invented in the first place!</p>
<p>So, instead you do a <code>static import</code> which is available since Java 5:</p>
<pre><code>import static org.hamcrest.Matchers.*;
</code></pre>
<p>Ok, you needed to type it by yourself, but still, now you can use just <code>hasEntry()</code> and everything works smoothly! But then, after some time, you do the <code>Organize import</code> magic (<code>ctrl + shift + o</code>) which automatically replaces your wildcard import static with concrete import static members, so you end up with:</p>
<pre><code>import static org.hamcrest.Matchers.hasEntry;
</code></pre>
<p>Later on, if you want to use another matcher, e.g. <code>notNullValue()</code> you need once again type the import statement by yourself. That&#8217;s ugly, time waste manufacture which we should get rid off!</p>
<p>Luckily, there is an Eclipse setting which allows you to add some specific static members or whole types into the regular content assist (<code>ctrl + space</code>) without writing any import statement by yourself.<br />
To set this, just go to: <code>Window -&gt; Preferences</code> and then under <code>Java -&gt; Editor -&gt; Content Assist -&gt; Favorites</code> add a <strong>Type</strong> (all static members within the given type will be added) or <strong>Member</strong> (just the particular static will be added):</p>
<p><a href="http://piotrnowicki.com/2012/04/content-assist-with-static-imports-in-eclipse/screenshot-at-2012-04-26-154833/" rel="attachment wp-att-871"><img src="http://piotrnowicki.com/website/wp-content/media/2012/04/Screenshot-at-2012-04-26-154833-300x272.png" alt="" title="Eclipse - Import Favorite Statics" width="300" height="272" class="aligncenter size-medium wp-image-871" /></a></p>
<p>From now on, all defined members and types will be available when you hit the <code>ctrl + space</code>. <em>Organize imports</em> will never again be your enemy! ;-)</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/04/content-assist-with-static-imports-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Another move towards Git</title>
		<link>http://piotrnowicki.com/2012/04/another-move-towards-git/</link>
		<comments>http://piotrnowicki.com/2012/04/another-move-towards-git/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 08:59:09 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=844</guid>
		<description><![CDATA[If you&#8217;re interested in getting some basic information about Git, surely you already know about the Git Community Book &#8211; it&#8217;s undoubtedly a source of great knowledge. However, if you prefer the visual presentation and want to listen about the Git, I will highly recommend Scott Chacon&#8217;s &#8220;Introduction to Git&#8221;. It is great, compact and [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re interested in getting some basic information about Git, surely you already know about the <a href="http://book.git-scm.com/">Git Community Book</a> &#8211; it&#8217;s undoubtedly a source of great knowledge. However, if you prefer the visual presentation and want to listen about the Git, I will highly recommend <a href="http://www.youtube.com/watch?v=ZDR433b0HJY">Scott Chacon&#8217;s &#8220;Introduction to Git&#8221;</a>. It is great, compact and fast-paced talk about the basics of Git.</p>
<p>So, either you know nothing about Git or you already know something and just want to summarize your knowledge &#8211; I would highly recommend you to spend this 1,5 h on watching this video.</p>
<p>By the way, in this video Scott showed pretty nice feature of aliasing. Despite that sometimes it might be confusing for others what magic is your alias doing, it can be very helpful in some cases (e.g. to save you some time typing long commands):</p>
<pre><code>git config --global alias.lol "log --oneline --graph --decorate"
</code></pre>
<p>This command creates a <code>lol</code> alias for git, so invoking <code>git lol</code> will invoke the above <code>log ...</code> command.</p>
<p>The Git learning curve is steep, but after working with it for just a few days &#8211; I already like it :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/04/another-move-towards-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Git and empty directories</title>
		<link>http://piotrnowicki.com/2012/04/git-and-empty-directories/</link>
		<comments>http://piotrnowicki.com/2012/04/git-and-empty-directories/#comments</comments>
		<pubDate>Sat, 21 Apr 2012 13:38:17 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[gerrit]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://piotrnowicki.com/?p=846</guid>
		<description><![CDATA[I&#8217;m currently under the process of moving all my workplace repositories from SVN to Git (configured to work with Gerrit). As a side not, I already found it to be a great tool for code review, line-precise commenting of the artifacts and for reviewing new employees code before pushing the changes to the repository. But, [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently under the process of moving all my workplace repositories from SVN to Git (configured to work with Gerrit). As a side not, I already found it to be a great tool for code review, line-precise commenting of the artifacts and for reviewing new employees code before pushing the changes to the repository.</p>
<p>But, back to my point. Recently I&#8217;ve stumbled upon a problem with <a href="https://git.wiki.kernel.org/articles/g/i/t/GitFaq_ebc3.html#Can_I_add_empty_directories.3F&quot;">commiting an empty directory in Git</a>. If the directory consists of some files and you stage those files, the directory will be commited automatically. However, if the directory is empty, you <strong>cannot</strong> commit it.</p>
<p>It&#8217;s very reasonable way of thinking, but it also creates a few problems e.g. with Eclipse which requires you to use some Maven defined directories (<code>src/test</code>, <code>src/java</code>, etc.). More precisely, if you don&#8217;t have e.g. <code>src/test/resources</code> directory, it will throw an ugly project-wide error at your face.</p>
<p>The solution, can be found on <a href="http://stackoverflow.com/a/932982/920607">StackOverflow</a>, so basically all you need to do is provide a <code>.gitignore</code> file which forbids content other than the <code>.gitignore</code> file itself. However, in my case I ended up with putting a README file which describes why it&#8217;s there and that it should be removed as first real resource will be uploaded.<br />
I found it more informative for other team members than an empty <code>.gitignore</code> file.</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/04/git-and-empty-directories/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>@Override differences in Java 5 and Java 6</title>
		<link>http://piotrnowicki.com/2012/02/override-differences-in-java-5-and-java-6/</link>
		<comments>http://piotrnowicki.com/2012/02/override-differences-in-java-5-and-java-6/#comments</comments>
		<pubDate>Tue, 28 Feb 2012 13:50:05 +0000</pubDate>
		<dc:creator>Piotr</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jdk5]]></category>
		<category><![CDATA[jdk6]]></category>
		<category><![CDATA[override]]></category>

		<guid isPermaLink="false">http://nullhaus.com/?p=558</guid>
		<description><![CDATA[Sometimes you might be struggling with such error shown, e.g. in Eclipse: The method &#8230;&#8230; must override a superclass method. If this error is shown in the line when you have your interface method implementation with @Override annotation, it most probably means that you&#8217;re using JDK 5 instead of JDK 6. In Java 5, the [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you might be struggling with such error shown, e.g. in Eclipse:</p>
<blockquote>
<p>The method &#8230;&#8230; must override a superclass method.</p>
</blockquote>
<p>If this error is shown in the line when you have your interface method implementation with <code>@Override</code> annotation, it most probably means that you&#8217;re using JDK 5 instead of JDK 6.</p>
<p>In Java 5, the <code>@Override</code> annotation might be applied only to the methods overriding superclass ones. Since Java 6 you can use the <code>@Override</code> annotation also with the methods that implements the interface ones.</p>
<p>Therefore, if you see such error, either change the JDK to JDK 6 (i.e. check your Eclipse workspace or project preferences) or, if you need to be compatible with JDK 5, remove the <code>@Override</code> annotations from interface implementation methods.</p>
<p>Simple thing but it might make you swear ;-)</p>
]]></content:encoded>
			<wfw:commentRss>http://piotrnowicki.com/2012/02/override-differences-in-java-5-and-java-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

