数据处理的原子性(clone数据副本,再对数据副本做处理)

private synchronized void addConnection(Object receiver, Method slot,int connectionType) {
...
...
List<Connection> newList = cloneConnectionsForceInstance();
newList.add(new Connection(receiver, slot, returnSig,(byte) connectionType));
connections = newList;
}


private List<Connection> cloneConnectionsForceInstance() {
List<Connection> newList = new ArrayList<Connection>();
if (connections != null)
newList.addAll(connections);
return newList;
}

摘录自:Qt jambi , com.trolltech.qt.internal.QSignalEmitterInternal.AbstractSignalInternal.

悟:

在对原始数据做处理过程中,如果可能发生异常,致使原始数据内容被破坏。

为了防止该种不遂人愿的情况发生,

可以先对数据colne一份副本,然后对副本数据进行加工处理。

如果过程中未发生任何异常,那么就将完全处理的新数据赋给原数据。反之,如果过程中出现了异常,原数据将不会被意外改动,从而保持了原数据的完整性。

原文地址:https://www.cnblogs.com/tao_/p/2192057.html