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.

       

  • 相关阅读:
    postmessage
    input、textarea等输入框输入中文时,拼音在输入框内会触发input事件的问题
    h5判断设备是ios还是android
    js获取地址栏的参数
    BootStrap 响应式布局
    前端框架 BootStrap 快速入门(Hallo Word)
    HTML + CSS + JavaScript 实现注册页面信息验证(表单验证)
    HTML + CSS + JavaScript 实现勾选动态表格中的记录
    JavaScript常见的事件监听
    HTML + CSS + JavaScript 实现简单的动态表格
  • 原文地址:https://www.cnblogs.com/haokaibo/p/strive-for-failure-atomicity.html
Copyright © 2011-2022 走看看