<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title>out.println</title>
	<subtitle>Standard output of work-related thoughts</subtitle>
	<link href="http://out-println.appspot.com/feed" rel="self" />
	<link href="http://out-println.appspot.com/" />
	<id>http://out-println.appspot.com/</id>
		<updated>2011-06-10T21:18:47+00:00</updated>
	<author>
		<name>Olivier</name>
	</author>

		<entry>
		<title>Java collections class diagram</title>
		<link href="http://out-println.appspot.com/posts/java_collections_class_diagram" />
		<id>http://out-println.appspot.com/posts/java_collections_class_diagram</id>
		<updated>2011-06-10T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;Here&apos;s a quick reference diagram of the JDK collection classes.&lt;/p&gt;

&lt;p&gt;I wanted something concise (just showing what&apos;s available, for more details there&apos;s the javadoc), user-oriented (the abstract implementations are not represented), and that could be printed on an A4 or US-letter paper sheet.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://olim7t.github.com/java_collections/java_collections.svg&quot;&gt;
   &lt;img src=&quot;http://olim7t.github.com/java_collections/java_collections_preview.png&quot; alt=&quot;preview&quot; /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I&apos;ve used &lt;a href=&quot;http://www.yworks.com/en/products_yed_about.html&quot;&gt;yEd&lt;/a&gt;. If you want to tweak the diagram or export it to another format, the source is available &lt;a href=&quot;https://github.com/olim7t/java_collections&quot;&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>An offline webapp example with Play! and JQuery</title>
		<link href="http://out-println.appspot.com/posts/offline_example" />
		<id>http://out-println.appspot.com/posts/offline_example</id>
		<updated>2011-05-22T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;I&apos;ve &lt;a href=&quot;https://github.com/olim7t/ubernote&quot;&gt;published&lt;/a&gt; a small prototype written to experiment with HTML5&apos;s &lt;a href=&quot;http://diveintohtml5.org/offline.html&quot;&gt;offline webapp&lt;/a&gt; and &lt;a href=&quot;http://diveintohtml5.org/storage.html&quot;&gt;local storage&lt;/a&gt; features. It&apos;s a simplistic note-taking application, with two list and detail pages:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://sites.google.com/site/outprinltn/ubernote.png&quot; alt=&quot;screenshots&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Notes can be browsed, created, modified and deleted offline; they are stored locally and synchronized when the application goes back online. To keep the example reasonably short, I&apos;ve simplified a few features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;conflict resolution is optimistic: when both a local and a server version of a note exist, the next synchronization will keep the most recent version;&lt;/li&gt;
&lt;li&gt;removal is &quot;soft&quot;: the note stays in the database, but gets flagged as &quot;archived&quot; so that future search requests ignore it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the technical side, the backend relies on &lt;a href=&quot;http://www.playframework.org/&quot;&gt;Play!&lt;/a&gt; and JPA, and the frontend uses JQuery.&lt;/p&gt;

&lt;p&gt;Here are a few thoughts gathered during development:&lt;/p&gt;

&lt;h1&gt;Writing the manifest&lt;/h1&gt;

&lt;h2&gt;Making the list page cacheable&lt;/h2&gt;

&lt;p&gt;There is something counterintuitive about offline pages in a dynamic website. When I first learnt about the cache manifest and the fallback section, I thought my list page would use a &quot;normal&quot;, server-generated version in online mode (query the database, feed the results to a Play! template that generates the HTML response), and would somehow fallback to a different, local-storage-enabled version in offline mode.&lt;/p&gt;

&lt;p&gt;This is not how it works. The key point here is this sentence from the &lt;a href=&quot;http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html&quot;&gt;specification&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;in practice the page that referenced the manifest is automatically cached even if it isn&apos;t explicitly mentioned.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let&apos;s suppose that I navigate to &lt;code&gt;/&lt;/code&gt; (the URI of my list page) while online; my server-side components generate the HTML response and send it back to my browser. Since this document declares a manifest, the browser stores it in its offline cache (along with any resource declared in the manifest), and uses this cached version for any subsequent request, be it online or offline. Which means that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;refreshing the page won&apos;t send a new request to the server. If the database changes, I will keep getting a stale version of the list;&lt;/li&gt;
&lt;li&gt;when the application goes offline, I have no way to switch to my alternate version of the page. What gets served is the cached version of an earlier online request.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The bottom line is that there must be a single version of my list page, which works in both modes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;when online, it fetches data from the server using background Ajax requests;&lt;/li&gt;
&lt;li&gt;when offline, it defaults to local storage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This moves the solution towards a &quot;single page&quot;-style interface, where most of the application logic (fetching data, populating the list, pagination) is handled via client-side Javascript.&lt;/p&gt;

&lt;h2&gt;Keeping the detail page addressable&lt;/h2&gt;

&lt;p&gt;One thing we lose with client-side navigation is addressable URIs. I wanted to keep a RESTful-style URI for each note (&lt;code&gt;/notes/7&lt;/code&gt; in the second screenshot above).&lt;/p&gt;

&lt;p&gt;I did that by keeping the detail page as a different resource. However, there is again a problem with the offline cache: each note URI is interpreted as a separate resource. Since IDs are assigned dynamically, I can&apos;t  list each and every &lt;code&gt;/notes/&amp;lt;id&amp;gt;&lt;/code&gt; URI in my cache manifest in advance. So, if I&apos;m offline and try to access a note I&apos;ve never opened before, the browser won&apos;t find it because it&apos;s not in the cache. I should be able to restore this page from the data I&apos;ve synchronized in my local storage.&lt;/p&gt;

&lt;p&gt;To address this problem, I&apos;ve used the fallback section. All dynamic note URIs fallback to a static page:&lt;/p&gt;

&lt;pre class=&quot;brush: plain&quot;&gt;
NETWORK:
/notes/*

FALLBACK:
/notes/ /offline/detail
&lt;/pre&gt;

&lt;p&gt;The fallback page uses Javascript to parse the URL and load the note (again, either with a background Ajax call or from the local storage, depending on network availability).&lt;/p&gt;

&lt;h1&gt;Testing&lt;/h1&gt;

&lt;p&gt;I&apos;ve used Play&apos;s out-of-the box Selenium support.&lt;/p&gt;

&lt;p&gt;The first question was: how to simulate loss of connectivity? Since Play&apos;s test runner is launched from the developement server, I couldn&apos;t just shut it down. The answer turned out to be quite simple: the way my client code detects offline mode is by the fact that Ajax requests fail. So I added a &quot;hook&quot; URI that makes all Ajax requests 404 (this is handled by setting a flag on the server). The Selenium tests just need to invoke that URI, and the application behaves as if it was offline.&lt;/p&gt;

&lt;p&gt;Similarly, I&apos;ve added other hook URIs to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;clear the local storage (by loading a page that runs a Javascript snippet);&lt;/li&gt;
&lt;li&gt;touch the cache manifest, to force an offline cache update;&lt;/li&gt;
&lt;li&gt;check the state of a note on the server without going through the normal UI (this is useful to check that the server is not updated when the client is supposed to be disconnected);&lt;/li&gt;
&lt;li&gt;touch a server note (to test update conflicts).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Naturally, these URIs are only accessible when the server runs in development mode. &lt;/p&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;In my experience, taking a dynamic (as in database-driven) webapp offline naturally lead me to a single-page design. I&apos;ve kept the list and detail page separate, but there is probably a way to keep everything in one page and still preserve addressability.&lt;/p&gt;

&lt;p&gt;Things get complicated quickly. I&apos;ve spent more time on this tiny example than I had originally anticipated. In particular, keeping the local and server databases synchronized introduces new corner cases.&lt;/p&gt;

&lt;p&gt;Testing can be painful (now I understand why &lt;a href=&quot;http://diveintohtml5.org&quot;&gt;Dive into HTML5&lt;/a&gt; has a section named &quot;The fine art of debugging, A.K.A. Kill me! Kill me now!&quot;). Locate your browser&apos;s &quot;clear local data&quot; and &quot;clear cache&quot; buttons, you&apos;re going to need them often.&lt;/p&gt;

&lt;p&gt;Running the Selenium tests from the browser is probably not the best choice. Standalone tests (for instance, JUnit tests using Selenium&apos;s Java API) would have made it easier to simulate offline mode, simply by shutting down and restarting the development server.&lt;/p&gt;

&lt;p&gt;With Firefox, I&apos;ve sometimes observed erratic offline cache behavior: it would stop updating and I would have to clear it manually and restart the browser. It&apos;s not clear to me whether this is a Firefox bug or a problem with my configuration.&lt;/p&gt;

&lt;p&gt;Feel free to comment or fork the &lt;a href=&quot;https://github.com/olim7t/ubernote&quot;&gt;GitHub project&lt;/a&gt;.&lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>Moving feed to FeedBurner</title>
		<link href="http://out-println.appspot.com/posts/moving_to_feedburner" />
		<id>http://out-println.appspot.com/posts/moving_to_feedburner</id>
		<updated>2011-05-05T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;I&apos;ve published my feed on FeedBurner.&lt;/p&gt;

&lt;p&gt;If you had suscribed to the former URL (which will still work), I&apos;d appreciate if you took a few seconds to change to &lt;a href=&quot;http://feeds.feedburner.com/out-println&quot;&gt;http://feeds.feedburner.com/out-println&lt;/a&gt;. This will provide me with stats and take a little bit of load off my server.&lt;/p&gt;

&lt;p&gt;More technical posts are coming :-)&lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>The TOCTTOU attack</title>
		<link href="http://out-println.appspot.com/posts/tocttou" />
		<id>http://out-println.appspot.com/posts/tocttou</id>
		<updated>2011-03-25T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;The following class has a security flaw, can you spot it?&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
import java.util.Date;

/** An immutable class representing a time interval. */
public final class Interval {

  private final Date min;
  private final Date max;

  public Interval(Date min, Date max) {
    if (min.after(max)) throw new IllegalArgumentException();
    this.min = (Date) min.clone();
    this.max = (Date) max.clone();
  }

  public Date min() { return (Date) min.clone(); }
  public Date max() { return (Date) max.clone(); }
}
&lt;/pre&gt;

&lt;p&gt;The class fulfills the prerequisites for immutability:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;all of its fields are final,&lt;/li&gt;
&lt;li&gt;the reference to &lt;code&gt;this&lt;/code&gt; does not escape during construction,&lt;/li&gt;
&lt;li&gt;there is no way to modify its state afterwards: &lt;code&gt;Date&lt;/code&gt; is mutable, but we were careful enough to use private fields and make defensive copies whenever we exchange data with the outside world. The constructor checks that its parameters respect the class&apos;s invariant, and immediately throws an exception if they don&apos;t.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, there is still a way to build an &lt;code&gt;Interval&lt;/code&gt; where &lt;code&gt;min&lt;/code&gt; &gt; &lt;code&gt;max&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;To explain the approach, here is an analogy: suppose I have just performed poorly at an important written exam. Afterwards, I go to my textbooks and find all the right answers, but it&apos;s too late: the teacher already has my paper. Unless... assuming the teacher won&apos;t grade the exam until tomorrow, I can write a fake paper, break into his house during the night, and swap the two copies!&lt;/p&gt;

&lt;p&gt;This (very unethical) trick is made possible by a window of opportunity between the time I handed out my paper and the time my teacher actually reads it. &lt;code&gt;Interval&lt;/code&gt; displays the same kind of weakness: the invariant check (line 10) is made &lt;em&gt;before&lt;/em&gt; the defensive copies (lines 11 &amp;amp; 12). With appropriate timing, a malicious client can mutate a date after the check, but before the copy.&lt;/p&gt;

&lt;p&gt;Here is the attacker class:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public class Attacker {
  volatile Date max = new Date();

  final Thread burglar = new Thread() {
    @Override public void run() {
      max.setTime(0);
    }
  };

  public Interval attack() {
    Date min = new Date();
    max.setTime(min.getTime());
    burglar.start();
    try {
      Interval i = new Interval(min, max);
      if (i.min().after(i.max())) {
        System.out.println(&quot;Success!&quot;);
        return i;
      } else System.out.println(&quot;Too late&quot;);
    }
    catch (final IllegalArgumentException e) {
      System.out.println(&quot;Too soon&quot;);
    }
    return null;
  }
}
&lt;/pre&gt;

&lt;p&gt;We begin with both arguments to the current date (lines 11 &amp;amp; 12) but, before calling the constructor, we start a thread that will set the max in the past. I expected to have to tweak a wait time at the beginning of &lt;code&gt;run()&lt;/code&gt;, but in fact that&apos;s not even necessary.&lt;/p&gt;

&lt;p&gt;Since the attack depends on lucky timing, it won&apos;t work every time; we run it in a loop:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
Interval corrupted;
long start = System.currentTimeMillis();
int count = 0;
while ((corrupted = (new Attacker()).attack()) == null) count += 1;

System.out.println(&quot;In &quot; + (System.currentTimeMillis() - start) + &quot; ms and &quot; +
  count + &quot; attacks, I have created a corrupt interval with min=&quot; +
  corrupted.min() + &quot; and max=&quot; + corrupted.max());
&lt;/pre&gt;

&lt;p&gt;On my machine, this generally succeeds in about 500 ms and 2500 attacks. My &quot;worst&quot; case was 2509 ms and 14393 attacks, and my &quot;best&quot; 14 ms and 26 attacks.&lt;/p&gt;

&lt;p&gt;This attack is known as &lt;a href=&quot;http://en.wikipedia.org/wiki/TOCTTOU&quot;&gt;TOCTTOU&lt;/a&gt;, which stands for &lt;em&gt;Time Of Check&lt;/em&gt; (collect the papers / check the invariant) To &lt;em&gt;Time Of Use&lt;/em&gt; (grade the papers / make the defensive copy). If you work with untrusted client code and expose this kind of vulnerability, a malicious client can destroy your internal invariants (which generally sucks).&lt;/p&gt;

&lt;p&gt;The fix is explained in Josh Bloch&apos;s excellent &lt;a href=&quot;http://java.sun.com/docs/books/effective/&quot;&gt;Effective Java, 2nd edition&lt;/a&gt;, item 39:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;make the defensive copies first, and check the invariant on the copies, or better yet:&lt;/li&gt;
&lt;li&gt;use immutable arguments (for dates, &lt;a href=&quot;http://joda-time.sourceforge.net/&quot;&gt;Joda Time&lt;/a&gt; or the upcoming &lt;a href=&quot;http://sourceforge.net/apps/mediawiki/threeten/index.php?title=ThreeTen&quot;&gt;JSR 310&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here&apos;s the implementation of the first solution:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public Interval(Date min, Date max) {
  this.min = (Date) min.clone();
  this.max = (Date) max.clone();
  if (this.min.after(this.max)) throw new IllegalArgumentException();
}
&lt;/pre&gt;

&lt;p&gt;The complete example is available &lt;a href=&quot;https://gist.github.com/887802&quot;&gt;on github&lt;/a&gt;.&lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>Simplified varargs 101</title>
		<link href="http://out-println.appspot.com/posts/simplified_varargs_101" />
		<id>http://out-println.appspot.com/posts/simplified_varargs_101</id>
		<updated>2011-01-04T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;Simplified varargs is probably the most obscure of the &lt;a href=&quot;http://openjdk.java.net/projects/coin/&quot;&gt;small changes&lt;/a&gt; coming in Java 7 (maybe because it won&apos;t be that relevant for end developers). Here are a couple of examples I wrote to make sure I grokked what it was all about.&lt;/p&gt;

&lt;h1&gt;Reminder: arrays and generic types don&apos;t mix well&lt;/h1&gt;

&lt;h2&gt;You can&apos;t create an array of a generic type&lt;/h2&gt;

&lt;p&gt;The compiler won&apos;t let you write:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
AtomicReference&amp;lt;Integer&gt;[] ris = { new AtomicReference&amp;lt;Integer&gt;() }; // Compile error
&lt;/pre&gt;

&lt;p&gt;If it did, that would lead to the following problem:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
Object[] os = ris;
os[0] = new AtomicReference&amp;lt;String&gt;(&quot;foo&quot;);
Integer i = ris[0].get(); // ClassCastException: String cannot be cast to Integer
&lt;/pre&gt;

&lt;p&gt;With non-generic types, the runtime checks type safety at line 2 (throwing an &lt;code&gt;ArrayStoreException&lt;/code&gt; if there is an inconsistency). This is not possible for generic types, because of type erasure: at runtime, both sides of the assignment are a raw &lt;code&gt;AtomicReference&lt;/code&gt;. Therefore, if the compiler let us get this far, the runtime would only detect the error at the third line, which could be in a completely unrelated part of the code (imagine the debug headache).&lt;/p&gt;

&lt;h2&gt;But an array is created for a vararg argument&lt;/h2&gt;

&lt;p&gt;What the compiler &lt;em&gt;will&lt;/em&gt; let you write is this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
static &amp;lt;T&gt; T doEvilStuff(final T... ts) {
  Object[] os = ts;
  os[0] = new AtomicReference&amp;lt;String&gt;(&quot;foo&quot;);
  return ts[0];
}
...
AtomicReference&amp;lt;Integer&gt; ri = doEvilStuff(new AtomicReference&amp;lt;Integer&gt;(0));
Integer i = ri.get(); // ClassCastException: String cannot be cast to Integer
&lt;/pre&gt;

&lt;p&gt;This is known as heap pollution. The only thing the compiler does is raise a warning at line 7:&lt;/p&gt;

&lt;pre class=&quot;brush: plain&quot;&gt;
Type safety : A generic array of AtomicReference is created for a varargs parameter
&lt;/pre&gt;

&lt;p&gt;Why just a warning? Because:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;life would suck without generic varargs ;-)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;in 99% of the cases, the method will just read the vararg elements&lt;/strong&gt; (which is safe), not mutate them as in this convoluted example.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;Java 6: why the current situation is not satisfying&lt;/h1&gt;

&lt;p&gt;The problem is that the warning is emitted at the call site, not at the declaration site.&lt;/p&gt;

&lt;p&gt;There are examples in the JDK (for instance &lt;code&gt;Arrays.asList&lt;/code&gt;), but, for the sake of originality, let&apos;s consider a custom example: an assertion method (&#224; la JUnit) to verify that a map contains a set of entries.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;
...
static &amp;lt;K, V&gt; void assertContains(final Map&amp;lt;K, V&gt; m, final Entry&amp;lt;K, V&gt;... entries) {
  for (Entry&amp;lt;K, V&gt; e : entries) {
    K key = e.getKey();
    assert m.containsKey(key);
    V expected = e.getValue(), actual = m.get(key);
    assert expected == null ? actual == null : expected.equals(actual);
  }
}
// Just a helper method to write entries more concisely
static &amp;lt;K, V&gt; Entry&amp;lt;K, V&gt; entry(final K key, final V value) {
  return new SimpleEntry&amp;lt;K, V&gt;(key, value);
}
...
// From the client code:
assertContains(someMap, entry(&quot;foo&quot;, 1), entry(&quot;bar&quot;, 2)); // Warning raised here
&lt;/pre&gt;

&lt;p&gt;Now, imagine I provide &lt;code&gt;assertContains&lt;/code&gt; as part of a library. Each and every time some client code invokes that method, it will get a warning, and &lt;em&gt;I can&apos;t do anything about it&lt;/em&gt;, even though I know perfectly well that the method is safe.&lt;/p&gt;

&lt;h1&gt;Java 7: simplified varargs&lt;/h1&gt;

&lt;p&gt;As a library designer, I&apos;d like a way to tell the compiler: &quot;I take responsibility for the good behavior of &lt;code&gt;assertContains&lt;/code&gt;. Leave my clients alone&quot;.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;http://blogs.sun.com/darcy/entry/project_coin_safe_varargs&quot;&gt;@SafeVarargs&lt;/a&gt; annotation does just that. When applied to a method or constructor, it will suppress the warning at all call sites:&lt;/p&gt;

&lt;pre class=&quot;brush:java&quot;&gt;
@SafeVarargs
static &amp;lt;K, V&gt; void assertContains(final Map&amp;lt;K, V&gt; m, final Entry&amp;lt;K, V&gt;... entries)
&lt;/pre&gt;

&lt;p&gt;You can download &lt;a href=&quot;http://download.java.net/jdk7/changes/jdk7-b123.html&quot;&gt;build b123&lt;/a&gt; to try it yourself. Without the annotation, warnings are emitted at call and declaration sites:&lt;/p&gt;

&lt;pre class=&quot;brush: plain&quot;&gt;
&gt;%JAVA_HOME%\bin\javac src\Test.java -d bin -Xlint:unchecked
src\Test.java:13: warning: [unchecked] Possible heap pollution from parameterized vararg type Entry&amp;lt;K,V&gt;
  static &amp;lt;K, V&gt; void assertContains(final Map&amp;lt;K, V&gt; m, final Entry&amp;lt;K, V&gt;... entries) {
                                                    ^
  where K,V are type-variables:
    K extends Object declared in method &amp;lt;K,V&gt;assertContains(Map&amp;lt;K,V&gt;,Entry&amp;lt;K,V&gt;...)
    V extends Object declared in method &amp;lt;K,V&gt;assertContains(Map&amp;lt;K,V&gt;,Entry&amp;lt;K,V&gt;...)
src\Test.java:24: warning: [unchecked] unchecked generic array creation for varargs parameter of type Entry&amp;lt;String,Integer&gt;[]
    assertContains(someMap, entry(&quot;foo&quot;, 1), entry(&quot;bar&quot;, 2));
                  ^
2 warnings
&lt;/pre&gt;

&lt;p&gt;With the annotation, both warnings go away.&lt;/p&gt;

&lt;p&gt;The specification also mentions that:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Compilers are encouraged to issue warnings when this annotation type is applied to a method or constructor declaration where:&lt;/p&gt;
  
  &lt;ul&gt;
  &lt;li&gt;The variable-arity parameter has a reifiable element type, which includes primitive types, Object, and String. (The unchecked warnings this annotation type suppresses already do not occur for a reifiable element type.) &lt;em&gt;[for instance, unnecessarily annotating &lt;code&gt;static void doStuff(int... is)&lt;/code&gt;]&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;The body of the method or constructor declaration performs potentially unsafe operations, such as an assignment to an element of the variable-arity parameter&apos;s array that generates an unchecked warning.&lt;em&gt;[this is the case of our &lt;code&gt;doEvilStuff&lt;/code&gt; method]&lt;/em&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;I&apos;ve tried both cases, but they don&apos;t seem to be implemented yet in b123: the compiler silently let me apply the annotation.&lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>Breakpoint dependencies in Eclipse</title>
		<link href="http://out-println.appspot.com/posts/breakpoint_deps_eclipse" />
		<id>http://out-println.appspot.com/posts/breakpoint_deps_eclipse</id>
		<updated>2010-12-16T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;This post describes a hack to achieve the following behavior in the Eclipse debugger: &lt;strong&gt;stop at a given breakpoint only if another breakpoint has been reached before&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;I&apos;m not aware of an existing solution to do that (although IDEA &lt;a href=&quot;http://stackoverflow.com/questions/2674582&quot;&gt;seems to have&lt;/a&gt; that functionality) &amp;mdash; and if I&apos;m wrong, I&apos;ve just lost a couple of hours of my life :-)&lt;/p&gt;

&lt;h1&gt;The problem&lt;/h1&gt;

&lt;p&gt;Suppose I&apos;m debugging a unit test that runs the same assertion over and over with different parameters (I know unit tests should have few assertions, but sometimes this pattern is just more practical):&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
assertEquals(43, SomeClass.someMethod(1));
assertEquals(44, SomeClass.someMethod(2));
assertEquals(45, SomeClass.someMethod(3));
assertEquals(50, SomeClass.someMethod(4));
&lt;/pre&gt;

&lt;p&gt;Suppose the last assertion is failing. I want to debug it, and I&apos;m particularly interested in an internal method called indirectly by &lt;code&gt;someMethod&lt;/code&gt;, deep down the call stack:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
private static int internalMethod(int p) {
  return p + 42;
}
&lt;/pre&gt;

&lt;p&gt;Basically, I have three options:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;set a breakpoint on &lt;code&gt;internalMethod&lt;/code&gt;. But the debugger will suspend every time the method is reached, including in the first N-1 calls to &lt;code&gt;someMethod&lt;/code&gt; that I&apos;m not interested in.&lt;/li&gt;
&lt;li&gt;set the breakpoint on the assertion that fails. But when the debugger suspends, I still have to go down the call stack to reach &lt;code&gt;internalMethod&lt;/code&gt;. This involves using &lt;em&gt;Go into&lt;/em&gt; repeatedly, which may go into a lot of auxiliary code I&apos;m not interested in (any method invoked to build parameters, class loads, etc.).&lt;/li&gt;
&lt;li&gt;set the breakpoint on the outer method, and when it suspends, set the breakpoint on the inner method manually, and hit &lt;em&gt;Continue&lt;/em&gt; to reach it directly. That&apos;s a bit better, but still involves manual work (to be undone and redone everytime I rerun the test).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Wouldn&apos;t it be nice to set both breakpoints, and configure the second one to &quot;activate&quot; only after the first one has been reached? Well that&apos;s possible: breakpoints can be conditioned by Java code, and that code can have side effects.&lt;/p&gt;

&lt;h1&gt;The solution&lt;/h1&gt;

&lt;p&gt;I drop a class named &lt;code&gt;Breaks&lt;/code&gt; in my test folder (the source code of the class is available &lt;a href=&quot;https://gist.github.com/743887&quot;&gt;here&lt;/a&gt;). On the outer breakpoint, I add the following condition:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://8392209901035651731-a-1802744773732722657-s-sites.googlegroups.com/site/outprinltn/breakpoint_props1.png&quot; alt=&quot;screenshot 1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This sets a &quot;marker&quot; that is accessible from other breakpoints. The &lt;code&gt;set&lt;/code&gt; method returns &lt;code&gt;false&lt;/code&gt;, so the debugger will never suspend on that breakpoint (if I want it to, there is an equivalent &lt;code&gt;setAndBreak&lt;/code&gt; method).&lt;/p&gt;

&lt;p&gt;On the second breakpoint, the condition invokes a method that returns &lt;code&gt;true&lt;/code&gt; only if the marker is set (alternatively, &lt;code&gt;testAndClear&lt;/code&gt; also deletes the marker):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://8392209901035651731-a-1802744773732722657-s-sites.googlegroups.com/site/outprinltn/breakpoint_props2.png&quot; alt=&quot;screenshot 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Voil&#224;. As long as the outer breakpoint hasn&apos;t been reached, the inner breakpoint will not suspend.&lt;/p&gt;

&lt;p&gt;This is portable to any debugger that supports conditions, and more elaborate strategies are possible (for instance, associating counters to the markers, instead of simple on / off state).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Update 2010/12/18:&lt;/em&gt; you will run into compile errors if &lt;code&gt;Breaks&lt;/code&gt; and the debugged classes reside in different packages. To avoid this, put &lt;code&gt;Breaks&lt;/code&gt; in a package with a short name, and use the fully qualified name in the breakpoint conditions (putting it in the default package doesn&apos;t seem to work, and import statements are not allowed in breakpoint conditions).&lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>Remove boilerplate with Guava</title>
		<link href="http://out-println.appspot.com/posts/remove_boilerplate_with_guava" />
		<id>http://out-println.appspot.com/posts/remove_boilerplate_with_guava</id>
		<updated>2010-06-20T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;&lt;a href=&quot;http://code.google.com/p/guava-libraries/&quot;&gt;Guava&lt;/a&gt; is Google&apos;s core Libraries for Java 1.5+. It is a superset of the Google Collections framework, along with other utilities, released as an open-source project under the Apache 2.0 license.&lt;/p&gt;

&lt;p&gt;This post won&apos;t cover Guava&apos;s major features, but rather some simple &quot;shortcut&quot; methods (each factoring a common Java idiom) that can make a developer&apos;s life easier.&lt;/p&gt;

&lt;p&gt;To illustrate this, let&apos;s consider this simple method, that writes a character string to a file:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public void save(final String info, final File file) throws IOException {
  if (file == null) throw new NullPointerException(&quot;file should not be null&quot;);
  Writer writer = null;
  boolean threw = true;
  try {
    writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(file), Charset.forName(&quot;UTF-8&quot;)));
    String data = info == null ? &quot;Nothing&quot; : info;
    writer.write(data);
    threw = false;
  } finally {
    if (writer != null)
      try {
        writer.close();
      } catch (IOException e) {
        // Do not swallow original exception
        if (!threw) throw e;
      }
  }
}
&lt;/pre&gt;

&lt;p&gt;Here is a version with the corresponding Guava methods:&lt;/p&gt;

&lt;pre class=&quot;brush: java; highlight: [8,12,13,16]&quot;&gt;
import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.io.Closeables;
import com.google.common.io.Files;

public void save(final String info, final File file) throws IOException {
  Preconditions.checkNotNull(file, &quot;file should not be null&quot;);
  Writer writer = null;
  boolean threw = true;
  try {
    writer = Files.newWriter(file, Charsets.UTF_8);
    writer.write(Objects.firstNonNull(info, &quot;Nothing&quot;));
    threw = false;
  } finally {
    Closeables.close(writer, threw);
  }
}
&lt;/pre&gt;

&lt;p&gt;Actually, there is even simpler, since we are only writing one string to the file:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public void save(final String info, final File file) throws IOException {
  Preconditions.checkNotNull(file, &quot;file should not be null&quot;);
  Files.write(Objects.firstNonNull(info, &quot;Nothing&quot;), file, Charsets.UTF_8);
}
&lt;/pre&gt;

&lt;p&gt;Optionally, you can also statically import everything (which increases readability but makes the origin of the methods less obvious &#8212; the choice is a matter of personal taste):&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public void save(final String info, final File file) throws IOException {
  checkNotNull(file, &quot;file should not be null&quot;);
  write(firstNonNull(info, &quot;Nothing&quot;), file, UTF_8);
}
&lt;/pre&gt;

&lt;p&gt;That&apos;s it. Nothing groundbreaking really, but I like how this makes the code more expressive, focusing on what you do rather than how you do it. Guava has a myriad of these utilities (look for static methods in the classes that have a plural name: &lt;a href=&quot;http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Lists.html&quot;&gt;&lt;code&gt;Lists&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Strings.html&quot;&gt;&lt;code&gt;Strings&lt;/code&gt;&lt;/a&gt;, &lt;a href=&quot;http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Resources.html&quot;&gt;&lt;code&gt;Resources&lt;/code&gt;&lt;/a&gt;...). &lt;/p&gt;
</content>
	</entry>
		<entry>
		<title>Piggybacking on synchronization</title>
		<link href="http://out-println.appspot.com/posts/piggybacking_on_synchronization" />
		<id>http://out-println.appspot.com/posts/piggybacking_on_synchronization</id>
		<updated>2010-06-09T00:00:00+00:00</updated>
		<content type="html">&lt;p&gt;Sometimes you can take advantage of an existing synchronization to guarantee the visibility of the changes made to an object. In &lt;a href=&quot;http://jcip.net/&quot;&gt;Java Concurrency In Practice&lt;/a&gt;, Brian Goetz calls this &quot;piggybacking on synchronization&quot;.&lt;/p&gt;

&lt;p&gt;A typical example is the publication of read-only resources that will be shared by all tasks in a thread pool: one of my projects at work parses and processes XML files in parallel. I use &lt;a href=&quot;http://xstream.codehaus.org/&quot;&gt;XStream&lt;/a&gt; for the parsing. The &lt;a href=&quot;http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/XStream.html&quot;&gt;javadoc&lt;/a&gt; of &lt;code&gt;XStream&lt;/code&gt; &amp;mdash; the base class that lets you configure the framework and [de]serialize objects &amp;mdash; states that it is safe to use by multiple threads once it has been configured. So it makes sense to share a single instance between various threads:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public class GoodPiggy {
  private ExecutorService executor;
  private XStream xstream;

  public void init() {
    executor = Executors.newFixedThreadPool(someSize);    
    final XStream xstream = new XStream();
    // configure xstream...
  }
  private class Task implements Runnable {
    public void run() {
      // do something with xstream... (threadsafe)
    }
  }
  public void submit() {
    executor.submit(new Task());
  }
}
&lt;/pre&gt;

&lt;p&gt;But are the changes to &lt;code&gt;xstream&lt;/code&gt; safely published? Do the worker threads running the tasks &quot;see&quot; the configuration performed in &lt;code&gt;init()&lt;/code&gt;? This is where piggybacking comes into play: submitting a task to an executor &lt;a href=&quot;http://en.wikipedia.org/wiki/Happened-before&quot;&gt;happens-before&lt;/a&gt; the task begins execution, so the code using &lt;code&gt;xstream&lt;/code&gt; in &lt;code&gt;run()&lt;/code&gt; is guaranteed to see it in a consistent state (assuming of course that &lt;code&gt;init()&lt;/code&gt; and &lt;code&gt;submit()&lt;/code&gt; are run by the same thread).&lt;/p&gt;

&lt;p&gt;JCIP warns that piggybacking on synchronization is a fragile construct, but I think this case is a reasonable use.&lt;/p&gt;

&lt;p&gt;Of course, things don&apos;t work so well if the tasks modify the shared state. Here is a counter-example (adapted from item 66 of &lt;a href=&quot;http://java.sun.com/docs/books/effective/&quot;&gt;Effective Java&lt;/a&gt;):&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;
public class BadPiggy { // DOESN&apos;T WORK
  private static boolean stop;

  public static void main(final String[] args) throws InterruptedException {
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    Runnable looping = new Runnable() {
      public void run() {
        int i = 0;
        while (!stop) i++;
      }
    };
    executor.submit(looping);
    Runnable stopper = new Runnable() {
      public void run() { stop = true; }
    };
    executor.submit(stopper);
    executor.shutdown();
  }
}
&lt;/pre&gt;

&lt;p&gt;Here, the modification of &lt;code&gt;stop&lt;/code&gt; is not safely published, because there is no happens-before relationship between the moment &lt;code&gt;stopper&lt;/code&gt; sets it, and the moment &lt;code&gt;looping&lt;/code&gt; is expected to see the change. I can get this example to loop forever on my machine (windows, Java 6u16 VM with &lt;code&gt;-server&lt;/code&gt; option).&lt;/p&gt;

&lt;p&gt;The solution here is to make the field &lt;code&gt;volatile&lt;/code&gt;, which guarantees visibility of the changes. If we needed mutual exclusion as well (for instance, if the shared state was an incrementing counter), we would need synchronization, either explicitly, or through a higher-level construct (like an &lt;code&gt;AtomicInteger&lt;/code&gt;). &lt;/p&gt;
</content>
	</entry>
	</feed>
