    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Even More Java Exceptions</title>
        <link>https://members.accu.org/index.php/journals/387</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #50 - Aug 2002 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c195/">50</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c195-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c195+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Even More Java Exceptions</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 August 2002 22:58:28 +01:00 or Fri, 02 August 2002 22:58:28 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a>A recap</h2>
</div>
<p>In Overload 49 Alan Griffiths continued his exploration of the
exception safety landscape in the wilds of Java and looked at a
problem introduced by Tom Cargill; namely how to make a copy of a
<span class="emphasis"><em>whole</em></span> object holding
multiple parts in an exception safe manner. In his article Alan
ensured that if construction of the whole object failed, the
resources of all fully constructed parts were released. He achieved
this by careful use of try/finally blocks and statement ordering -
essentially, like this:</p>
<pre class="programlisting">
public class Part implements Cloneable {
  ...
  public void dispose();
}

public class Whole {   
  ...
  public void copy(Whole other) {
    Part t1 = (Part)other.p1.clone();
    if (t1 != null) {
      try {
        Part t2 = (Part)other.p2.clone();
        if (t2 != null) {
          t1.setParent(this);
          t2.setParent(this);

          // pivot point

          Part swap1 = t1;
          t1 = p1;
          p1 = swap1;

          Part swap2 = t2;
          t2 = p2;
          p2 = swap2;
        }
      }
      finally {
        t2.dispose();
      }
    }
    finally {
      t1.dispose();
    }
  }

  private Part p1, p2; // never null
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e28" id="d0e28"></a>A detailed
look</h2>
</div>
<p><tt class="methodname">Copy</tt> succeeds atomically (and
returns) if nothing before the pivot point throws an exception:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The cloned parts are held in local variables <tt class=
"varname">t1</tt> and <tt class="varname">t2</tt>. The cloned parts
are <span class="emphasis"><em>not</em></span> used to set the
<tt class="varname">p1</tt> and <tt class="varname">p2</tt> fields
directly.</p>
</li>
<li>
<p>The local variables are swapped with the fields <span class=
"emphasis"><em>only</em></span> if they are not <tt class=
"literal">null</tt>. This maintains the invariant that <tt class=
"varname">p1</tt> and <tt class="varname">p2</tt> are never
<tt class="literal">null</tt> (the calls to <tt class=
"literal">other.p1.clone()</tt> and <tt class=
"literal">other.p2.clone()</tt> do not check <tt class=
"literal">other.p1 != null</tt> or <tt class="literal">other.p2 !=
null</tt>).</p>
</li>
</ul>
</div>
<p><tt class="methodname">Copy</tt> fails atomically (with an
exception) if any of the methods before the pivot point throw an
exception:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The <tt class="literal">finally</tt> blocks will dispose of any
cloned parts.</p>
</li>
<li>
<p>The exception will signal that the copy failed.</p>
</li>
<li>
<p>The target of the copy will be unchanged.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e101" id="d0e101"></a>A potential
problem or two</h2>
</div>
<p>One potential problem with copy as it stands is that if a
<tt class="methodname">clone()</tt> call returns null there will be
no exception, <tt class="methodname">copy</tt> will return, and the
target of the copy will remain <span class=
"emphasis"><em>unchanged</em></span>. This means you don't know the
state of the object if the call to <tt class="methodname">copy</tt>
returns (rather than throwing an exception). There are at least two
solutions to this problem:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>You could make <tt class="methodname">copy</tt> return a boolean
and return false if any call to <tt class="methodname">clone()</tt>
returns <tt class="literal">null</tt>. (The <tt class=
"literal">finally</tt> blocks will still dispose of any
successfully cloned parts.)</p>
</li>
<li>
<p>You could throw an exception if a call to <tt class=
"methodname">clone()</tt> returns <tt class=
"literal">false</tt>.</p>
</li>
</ul>
</div>
<p>I prefer the latter option, partly because it fits with the
exception-for- failure model, but mostly because it just seems
right. We've already established that <tt class=
"literal">other.p1</tt> and <tt class="literal">other.p2</tt> are
never <tt class="literal">null</tt> and <tt class=
"literal">null</tt> simply isn't a clone of something that's not
<tt class="literal">null</tt>.</p>
<p>There's another copy subtlety worth mentioning. It concerns the
calls to <tt class="methodname">setParent</tt>. These calls nicely
illustrate that a whole-part relationship is, in general, a two-way
relationship. If you follow the code through carefully, you'll see
that once the swaps have taken place, the cloned parts (now
referred to by the <tt class="varname">p1</tt> and <tt class=
"varname">p2</tt> fields) see the target of the copy (<tt class=
"literal">this</tt>) as their parent (which is fine), but that the
old parts (now in <tt class="varname">t1</tt> and <tt class=
"varname">t2</tt>) <span class="emphasis"><em>also</em></span> see
the target of the copy (<tt class="literal">this</tt>) as their
parent. In other words, if a Whole holds N parts then N*2 parts
will simultaneously think they're in the same Whole. In reality,
this probably won't be a problem because half of the parts are
about to be disposed of.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e186" id="d0e186"></a>An interface:
Disposable resource</h2>
</div>
<p>The strategy I used in my attempt to progress through the jungle
is an interface. The <tt class="classname">Disposable</tt>
interface embodies the Disposal Method pattern - it creates a
method you can explicitly call to dispose of a resource at a
<span class="emphasis"><em>known</em></span> point in the code
(this interface is noticeable by its absence from the Java
SDK).</p>
<pre class="programlisting">
public interface Disposable {
  void dispose();
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e199" id="d0e199"></a>A
specification: Stack of Disposable resources</h2>
</div>
<p>The next step is to create something that holds a stack of
<tt class="classname">Disposable</tt> objects. The purpose of this
class will be to hold a number of resources. I call it a stack
because it effectively plays the part of the control flow stack in
C++. That is, a stack in the sense of the opposite of a heap; the
stack that, in C++, holds local objects and calls their destructors
when they go out of scope. <tt class=
"classname">DisposableStack</tt> is an example of the Composite
pattern (although I don't actually require the composite in this
article).</p>
<pre class="programlisting">
public final class DisposableStack implements Disposable {
  public DisposableArray(int fixedCapacity);
  public void push(Disposable resource);
  public void clear();
  public void dispose();
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e212" id="d0e212"></a>A
beginning</h2>
</div>
<p>Now consider what would happen if <tt class=
"classname">Part</tt> implemented <tt class=
"classname">Cloneable</tt> and <tt class=
"classname">Disposable</tt> (I will remove this assumption
later):</p>
<pre class="programlisting">
public class Part implements Cloneable, Disposable {
  ...
}
</pre>
<p>With these pieces of the puzzle in place you can collapse the
multiple nested <tt class="literal">try</tt>/<tt class=
"literal">finally</tt> blocks in <tt class=
"methodname">Whole.copy</tt> (one per part) down to just a single
<tt class="literal">try</tt>/<tt class="literal">finally</tt>
block. Notice that each resource is held twice, once in a local
variable (eg <tt class="varname">t1</tt>, <tt class=
"varname">t2</tt>) and once inside the <tt class=
"classname">DisposableStack</tt> (<tt class=
"varname">resources</tt>). The trickiest part is the last three
statements before the <tt class="literal">finally</tt> block. These
statements ensure that a successful copy (one that passes the pivot
point) disposes of the old <tt class="classname">Part</tt>
resources just swapped from <tt class="varname">p1</tt>, <tt class=
"varname">p2</tt> into <tt class="varname">t1</tt>, <tt class=
"varname">t2</tt>:</p>
<pre class="programlisting">
public class Whole {
  ...
  public void copy(Whole other) {
    DisposableStack resources =
                new DisposableStack(2);
    try {
      Part t1 = (Part)other.p1.clone();
      push(resources, t1);
      Part t2 = (Part)other.p2.clone();
      push(resources, t2);
      t1.setParent(this);
      t2.setParent(this);
      Part swap1 = t1;
      t1 = p1;
      p1 = swap1;
      Part swap2 = t2;
      t2 = p2;
      p2 = swap2;
      resources.clear();
      resources.push(t1);
      resources.push(t2);
    }
    finally {
      resources.dispose();
    }
  }
  private static void push( DisposableStack
                resources, Part resource) {
    if (resource == null) {
      throw ...
    }
    resources.push(resource);
  }
  private Part p1, p2; // never null
}
</pre>
<p>If a call to <tt class="methodname">clone()</tt> returns
<tt class="literal">null</tt>, the attempt to add it to the
<tt class="varname">resources</tt> collection must throw an
exception. We'll handle this in a <tt class="classname">Whole</tt>
helper method rather than in <tt class=
"classname">DisposableStack</tt> so that <tt class=
"classname">DisposableStack</tt> can stay a general purpose class.
If all the parts are cloned and added to the <tt class=
"varname">resources</tt> collection, the part specific calls take
place (<tt class="methodname">setParent</tt>) and then the swaps
are performed. The swaps must not throw an exception. After the
swaps, the part clones (not <tt class="literal">null</tt>) are in
p1 and p2, and the old parts (also not <tt class=
"literal">null</tt>) are in <tt class="varname">t1</tt> and
<tt class="varname">t2</tt>. The <tt class="varname">resources</tt>
stack is cleared, and the old parts are pushed in ready to be
disposed of in the <tt class="literal">finally</tt> block. The code
tells us the critical exception guarantees of the methods:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><tt class="methodname">DisposableStack.clear()</tt> must never
throw an exception. This is because the call to <tt class=
"methodname">clear()</tt> happens after the pivot point.</p>
</li>
<li>
<p>If a <tt class="classname">DisposableStack</tt> (eg <tt class=
"varname">resources</tt>) is initialized with a constructor
argument <i class="parameter"><tt>N</tt></i>, then after a call to
<tt class="methodname">resources.clear()</tt> the next <i class=
"parameter"><tt>N</tt></i> calls to <tt class=
"literal">resources.push(resource)</tt> must not throw an
exception. Again, this is because these calls happen after the
pivot point.</p>
</li>
<li>
<p><tt class="methodname">DisposableStack.dispose()</tt> should
allow any exception that arises from it to escape. <tt class=
"classname">DisposableStack</tt> is a general purpose class and
cannot judge the severity of a disposal through an interface.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e359" id="d0e359"></a>An
implementation: Stack of Disposable resources</h2>
</div>
<p>How can we guarantee these constraints? You might think about
using a collection class such as <tt class=
"classname">ArrayList</tt>. Can <tt class=
"classname">ArrayList</tt> methods throw exceptions? I'm not sure
and I'm not going to bother looking because there is a better
solution: use an array. This will not only give us complete control
over exceptional behaviour it will probably also makes the solution
a little faster. Notice that this version disposes of the resources
in a last-in last-out fashion (which seems appropriate), and also
avoids the need for any casting:</p>
<pre class="programlisting">
public final class DisposableStack implements Disposable {
  public DisposableStack(
                 int fixedCapacity) {
    resources =
           new Disposable[fixedCapacity];
    at = 0;
  }

  public void push(Disposable resource) {
    // PreCondition(resource != null)
    // PreCondition(at &lt; resources.length)
    resources[at] = resource;
    ++at;
  }
  public void clear() {
    at = 0;
  }
  public void dispose() {
    while (-at &gt; 0) {
      resources[at].dispose();
    }
  }
  private final Disposable[] resources; 
  private int at;
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e372" id="d0e372"></a>A refinement:
Null Object pattern</h2>
</div>
<p>One glitch in this implementation is that if you push <tt class=
"literal">null</tt>, bad things will happen. You could solve this
by checking for <tt class="literal">null</tt> in a push
precondition. Another way is to use the Null Object pattern, like
this:</p>
<pre class="programlisting">
public final class NullDisposable implements Disposable {
  public static final NullDisposable instance = new NullDisposable();
  public void dispose() {
    // all done!
  }
}
public final class DisposableStack implements Disposable {
  ...
  public void push(Disposable resource) {
    // PreCondition(at &lt; resources.length)
    resources[at] = 
        resource != null ? resource : NullDisposable.instance;
    ++at;
  }
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e385" id="d0e385"></a>A refinement:
swap method</h2>
</div>
<p>Something else that bothers me about this solution is the lack
of a swap abstraction. If you study Alan's original code you'll see
that the swap cannot be factored out because it swaps local
variables that are disposed in their following <tt class=
"literal">finally</tt> blocks. However, at the cost of introducing
a temporary object, it is possible:</p>
<pre class="programlisting">
public class Whole {
  ...
  public void copy(Whole other) {
    DisposableStack resources =
                 new DisposableStack(2);
    try {
      Whole copy = new Whole();
      copy.p1 = (Part)other.p1.clone()
      push(resources, copy.p1); 
      copy.p2 = (Part)other.p2.clone();
      push(resources, copy.p2); 
      copy.p1.setParent(this);
      copy.p2.setParent(this);
      copy.swap(this);
      resources.clear();
      resources.push(copy.p1);
      resources.push(copy.p2);
    }
    finally {
      resources.dispose();
    }
  }

  public void swap(Whole other) {
    Part swap1 = p1;
    p1 = other.p1;
    other.p1 = swap1;
    Part swap2 = p2;
    p2 = other.p2;
    other.p2 = swap2;
  }
  ...
  private Part p1, p2; // never null
}
</pre>
<p>Note that this &quot;solution&quot; requires a default <tt class=
"classname">Whole</tt> constructor that creates an empty <tt class=
"classname">Whole</tt> object, that is, one that contains no
resources. The idea is that you create an empty whole object, and
then gradually fill it. If you've already implemented the default
constructor and it doesn't do this you can simply create a private
constructor with a dummy argument.</p>
<pre class="programlisting">
public class Whole {
  ...
  public Whole copy(Whole other) {
    DisposableStack resources = new DisposableStack(2);
    try {
      Whole empty = new Whole(Empty.instance);
      // as before
    }
    ...
  }

  private static final class Empty {
    public static final Empty instance =
        new Empty(); 
  }
 
  private Whole(Empty unused) {
    // all done
  }
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e405" id="d0e405"></a>A bug:
shallow swap</h2>
</div>
<p>This would be a reasonable solution if it worked but
unfortunately it doesn't. Before the swap, both objects are well
formed. The target of the copy (this) has its parts and these parts
know this is their parent. Similarly, the copied object has its
parts (clones of this's parts) and these parts know copied is their
parent. All well and good! The problem is that the swap only swaps
the references; it's a shallow swap and it needs to be a deep swap.
After the swap, the parts will be referring to the wrong parents.
To swap a whole you have to be able to swap its parts. It's not
enough to just swap the references.</p>
<pre class="programlisting">
public class Part implements Cloneable, Disposable {
  ...
  public void swap(Part other) {
    // swap all fields, must not throw
    ...
  }
}

public class Whole {
  ...
  public void swap(Whole other) {
    // shallow
    Part swap1 = p1;
    p1 = other.p1;
    other.p1 = swap1;
    Part swap2 = p2;
    p2 = other.p2;
    other.p2 = swap2;
    // deep
    p1.swap(other.p1);
    p2.swap(other.p2);
  }
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e412" id="d0e412"></a>A refinement:
copy constructor</h2>
</div>
<p>Let's stop for a moment to think about what we've just done.
We've created an empty object so that we can gradually fill it with
cloned parts. And remember that we're doing this so we can
implement the copy method. With a little reflection the idea of
using a copy constructor suggests itself. That way, we won't have
to worry about the initial state of the object we're creating. (If
you've already implemented the copy constructor and it doesn't do
this you can simply create a private constructor with a dummy
second argument as before). Should the copy constructor be public?
Well, copy method is public so it seems reasonable.</p>
<pre class="programlisting">
public class Whole {
  ...
  public Whole(Whole other) {
    DisposableStack resources =
                 new DisposableStack(2);
    try {
      push(resources,
           p1 = (Part)other.p1.clone());
      push(resources,
           p2 = (Part)other.p2.clone());
      p1.setParent(this);
      p2.setParent(this);
      resources.clear();
    }
    finally {
      resources.dispose();
    }
  }
  ...

  private Part p1, p2; // never null
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e419" id="d0e419"></a>A final
piece: copy method</h2>
</div>
<p>With this copy constructor in place, the obvious (but wrong) way
to write the <tt class="methodname">copy</tt> method is as
follows:</p>
<pre class="programlisting">
public class Whole {
  ...
  public void copy(Whole other) {
    Whole copy = new Whole(other);
    copy.swap(this);
  }
}
</pre>
<p>The problem is that <tt class="methodname">copy</tt> does not
dispose of the old parts after the swap. This is not C++ remember!
Luckily we have exactly the right tool to fix this problem:
<tt class="classname">DisposableStack</tt>.</p>
<pre class="programlisting">
public class Whole {
  ...
  public void copy(Whole other) {
    DisposableStack resources = new DisposableStack(2);
    try {
      Whole copy = new Whole(other);
      copy.swap(this);
      push(resources, copy.p1);
      push(resources, copy.p2);
    }
    finally {
      resources.dispose();
    }
  }
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e439" id="d0e439"></a>A
refactoring: resources as a field</h2>
</div>
<p>This is now a reasonable solution. However, there is one last
refactoring we can perform before returning to the assumption that
<tt class="classname">Part</tt> implements <tt class=
"classname">Disposable</tt>. It revolves around the observation
that there is a lot of pushing going on! A possibly more natural
approach would be for the pushes to happen only at construction and
for the clear to happen only at &quot;disposal&quot;. The way to achieve this
is to make the <tt class="classname">DisposableStack</tt> a field
instead of a local variable. There are a number of points to note
in this solution:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>If there is no exception the copy constructor <span class=
"emphasis"><em>retains</em></span> the references to the parts. The
assumption is that all the constructors will do this. To do this
you need a Boolean variable because there is no way to query
whether an exception is currently pending. (Another noticeable
omission from the Java SDK; interestingly, I've been told that it
is possible to determine whether an exception is pending if you
drop down to the JVM level.)</p>
</li>
<li>
<p>The <tt class="methodname">copy</tt> method makes a copy using
the copy constructor. If this succeeds it swaps itself with the
copy. It then disposes of the parts of its <span class=
"emphasis"><em>old self</em></span> (which of course are now held
in the copy because the swap method swaps the resources field too).
An issue you might like to consider is the possibility of an
exception arising from the call to <tt class=
"methodname">copy.resources.dispose</tt>. Should this exception be
caught and suppressed? How valuable is the simple model of use this
would afford? Is it a deep philosophical truth (and holds in all
applicable programming languages) that exceptions should never
arise from destruction/finalization? Or is disposal different
because the object being disposed is still in scope?</p>
</li>
<li>
<p>It's noticeable how the <tt class="classname">ResourceStack</tt>
is playing the role of a stack-based local variable in languages
like C++ that supports scope based resources.</p>
</li>
</ul>
</div>
<pre class="programlisting">
public class Whole {
  ...
  public Whole(Whole other) {
    boolean exception = true;
    try {
      push(p1 = (Part)other.p1.clone());
      push(p2 = (Part)other.p2.clone());
      p1.setParent(this);
      p2.setParent(this);
      exception = false; 
    }
    finally {
      if (exception) {
        resources.dispose();
      }
    }
  }
    
  public void copy(Whole other) {
    Whole copy = new Whole(other);        
    copy.swap(this);
    copy.resources.dispose(); 
  }

  public void swap(Whole other) {
    // shallow
    DisposableStack swap0 = resources;
    resources = other.resources;
    other.resources = swap0;
    Part swap1 = p1;
    p1 = other.p1;
    other.p1 = swap1;
    Part swap2 = p2;
    p2 = other.p2;
    other.p2 = swap2;
    // deep
    p1.swap(other.p1);
    p2.swap(other.p2);
  }

  private void push(Part resource)
    if (resource == null) 
      throw ...
    }
    resources.push(resource);
  }

  private DisposableStack resources =
                  new DisposableStack(2);
  private Part p1, p2; // never null
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e480" id="d0e480"></a>An assumption
revisited: Part Disposer</h2>
</div>
<p>Now let's return to the original assumption. What if <tt class=
"classname">Part</tt> does not implement the <tt class=
"classname">Disposable</tt> interface? Simple, just use an
<tt class="classname">Adapter</tt>.</p>
<pre class="programlisting">
public final class PartDisposer
                    implements Disposable 
  public PartDisposer(Part adapted) {
    // PreCondition(adapted != null)
    adaptee = adapted;
  }
  public void dispose() {
    adaptee.dispose();
  }
  private final Part adaptee;
}
</pre>
<p>Fine, but how do you use the adapter? There is a final trap we
must take care not to fall into. The obvious (but flawed) way to
use this adapter is as follows:</p>
<pre class="programlisting">
public class Whole {
  ...
  private void push(Part resource) {
    if (resource == null) {
      throw ...
    }
    resources.push(new PartDisposer(resource));
  }
  ...
}
</pre>
<p>The problem is that if the creation of a new <tt class=
"classname">PartDisposer</tt> throws an exception the copied
<tt class="classname">Part</tt> will not be pushed onto the
resources stack. There are a number of ways to fix this. One is via
a careful use of a <tt class="literal">try</tt>/<tt class=
"literal">finally</tt> block in the <tt class=
"methodname">Whole.push</tt> helper method:</p>
<pre class="programlisting">
public class Whole {
  ...
  private void push(Part resource) {
    if (resource == null) {
      throw ... 
    }
    try {
      resources.push(
             new PartDisposer(resource));
      resource = null;
    }
    finally {
      if (resource != null) {
        resource.dispose();
      }
    }
  }
  ... 
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e519" id=
"d0e519"></a>Conclusion</h2>
</div>
<p>Has it been worth it? Is this version useful? As always there
are opposing forces. This version is something of a sledgehammer
cracking a nut when the number of parts is small. But as the number
of parts increases, so does the depth of the try/finally nesting,
and so the more attractive this version becomes. However, it does
so at the cost of creating extra objects. It's also noticeable that
this version involves a lot less work if the Part classes implement
the <tt class="classname">Disposable</tt> interface, thus avoiding
the need for <tt class="classname">Adapter</tt>s.</p>
<p>It's also important to consider that Java programs normally
express copying through the creation of new objects rather than
emulating deep assignment. Perhaps it's best to think of this
solution to Tom Cargill's whole-part copy problem as showing just
<span class="emphasis"><em>one</em></span> way to use the
<tt class="classname">DisposableStack</tt> class. The important
thing, as Alan says, is that the exception safety guarantees make
sense in Java and should be applied when writing or reviewing code.
The problem is that the Java language offers almost no in-built
support for this activity. <tt class=
"classname">DisposableStack</tt> is a class that can help.</p>
<p>In design, as in life, you learn more from making the journey
than you do from reaching the destination. I look forward to more,
as yet, unvisited trails.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
