zoukankan      html  css  js  c++  java
  • Effective Java 64 Strive for failure atomicity

    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.

       

  • 相关阅读:
    数往知来C#面向对象准备〈二〉
    数往知来C#之面向对象准备〈一〉
    如果我比别人走得更远些,那是因为我站在巨人的肩上。
    小记一下
    关于servlet
    使用session防止表单重复提交
    session和cookie的区别
    数据结构排序算法Java实现
    用背景渐变的透明度设置不同颜色的背景渐变
    Java用DOM方法解析xml
  • 原文地址:https://www.cnblogs.com/haokaibo/p/strive-for-failure-atomicity.html
Copyright © 2011-2022 走看看