`
leonzhx
  • 浏览: 768038 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 64: Strive for failure atomicity

阅读更多

1.  Generally speaking, a failed method invocation should leave the object in the state that it was in prior to the invocation. A method with this property is said to be failure atomic.

 

2.  The simplest way to achieve failure atomicity is to design immutable objects. If an operation fails, it may prevent a new object from getting created, but it will never leave an existing object in an inconsistent state.

 

3.  For methods that operate on mutable objects, the most common way to achieve failure atomicity is to check parameters for validity before performing the operation. A closely related approach to achieving failure atomicity is to order the computation so that any part that may fail takes place before any part that modifies the object.

 

4.  A third and far less common approach to achieving failure atomicity is to 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.

 

5.  A final approach to achieving failure atomicity is to 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.)

 

6.  It would be wrong to assume that an object was still usable after catching a ConcurrentModificationException.

 

7.  As a rule, errors (as opposed to exceptions) are unrecoverable, and methods need not even attempt to preserve failure atomicity when throwing errors.

 

8.  As a rule, 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.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics