代码改变世界

Effective Java 64 Strive for failure atomicity

2014-04-28 06:02  小郝(Kaibo Hao)  阅读(589)  评论(0编辑  收藏  举报

Principle

Failure atomic - A failed method invocation should leave the object in the state that it was in prior to the invocation.

   

Ways to achieve failure atomic

1. Method operates on Immutable objects

It's free to failure atomic since the state of the immutable objects is consistent when it's created and can't be modified thereafter.

2. Method operates on mutable objects

  • Check parameters for validity before performing operation(Item 38).

   

public Object pop() {

if (size == 0)

throw new EmptyStackException();

/* If there is no such checking there will be non-abstract exception thrown by the app and the size field will be in an invalid state after the exception. */

Object result = elements[--size];

elements[size] = null; // Eliminate obsolete reference

return result;

}

  • Order the computation

    Any part that may fail takes place before any part that modifies the object.

3. Write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began.

This approach is used mainly for durable (disk-based) data structures.

4. Perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete.

Collections.sort dumps its input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.

   

Summary

Any generated exception that is part of a method's specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.