Migrate from GitHub to SourceForge with this tool. Check out all of SourceForge's recent improvements.
Close

Buffered Collections

Buffered collections are useful if you want to modify your collection in code-block where exception can be thrown and data stored in your collection becomes inconsistent.Buffered collection decorator bufferes all modification to the decorated collection, but don’t modify original decorated collection. You can revert any changes made to your buffered collection since last commit. If you commit changes decorated collection will be also modified.

package org.happy.examples.collections.decorators.examples.buffered;

import java.util.HashSet;
import java.util.Set;

import org.happy.collections.sets.decorators.BufferedSet_1x0;

import com.google.common.base.Preconditions;

public class CollectionAtomicityExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        //original list
        final Set<String> namesSet = new HashSet<>();

        //buffered list
        final BufferedSet_1x0<String> bufNameSet = BufferedSet_1x0.of(namesSet);

        //in this block some exceptions can be thrown, thus the changes made tot he set may be reverted
        try{
            bufNameSet.add("A");
            Preconditions.checkState(!namesSet.contains("A"));
            Preconditions.checkState(bufNameSet.contains("A"));
            bufNameSet.commit();//commit changes
        }
        catch(Throwable t){
            bufNameSet.flush();//revert changes
        }

        Preconditions.checkState(namesSet.contains("A"));
    }

}