用java协调变化

用java协调变化,java,transactions,java-8,Java,Transactions,Java 8,下面是一个演示示例 if (someList.contains(fooObject)) { someList.add(someObject); someStorage.serialize(someObject); } 我需要执行两个协调的任务:将对象someObject添加到someList并将其序列化到存储someStorage。我希望someList和someStorage具有一致的数据:两个操作都成功,或者其中一些操作失败,或者如果其中一个成功,则回滚,但另一个失败。如何做到这一

下面是一个演示示例

if (someList.contains(fooObject)) {
  someList.add(someObject);
  someStorage.serialize(someObject);
}

我需要执行两个协调的任务:将对象
someObject
添加到
someList
并将其序列化到存储
someStorage
。我希望
someList
someStorage
具有一致的数据:两个操作都成功,或者其中一些操作失败,或者如果其中一个成功,则回滚,但另一个失败。如何做到这一点?

一种方法是采用两阶段提交(-ish)方法。因此,您需要重新构造添加和序列化操作,以便执行最初可能失败的所有中间操作。然后将中间结果存储在变量中。验证生成的两个中间结果后,提交更改

if (someList.contains(fooObject)) {
  // we start with the operation which is easier to undo
  try{
    someList.add(someObject);
    //the first operation is succeded
    try{
      someStorage.serialize(someObject);
    }catch(Exception ex){
      // the second operation faild --> undo the first
      someList.remove(someObject);
      //report error
    }
  }catch(Exception ex){
    // the first operation faild -->   report error
  }  
}
类似这样的东西

if (someList.contains(fooObject)) {
  boolean r1 = someList.preAdd(someObject);
  boolean r2 = someStorage.preSerialize(someObject);
  if ( r1 && r2 ) {
    someList.commit();
    someStorage.commit();
  } else {
    if (!r1) someList.rollback()
    if (!r2) someStorage.rollback()
  }
}

根据实际界面的不同,您可能希望使用
try/catch
而不是
if/else

那么,“存储”是什么意思呢?数据库、文件、网络?目前它是一个xml文件。