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.

       

  • 相关阅读:
    Review Python装饰器
    Python自动化开发三元运算 列表解析 生成器表达式
    Python自动化开发函数02
    Python自动化开发函数03
    Python自动化开发文件
    ELK02ELK收集Linux系统平台应用系统日志
    ELK01Elasticsearch
    html5调用摄像头并拍照
    Docker 安装 PostgreSQL
    《TensorFlow+Keras自然语言处理实战》图书介绍
  • 原文地址:https://www.cnblogs.com/haokaibo/p/strive-for-failure-atomicity.html
Copyright © 2011-2022 走看看