Menu

Transient Collections

Transient collection hold stored elements only for defined period of time. After that period if stored elements were not used, they will be automatically removed from decorated collection.

The example above creates a transient map with two objects (A,B), one of this objects will be used in the while-loop. The transientMap removes not used object (B), thus only used object (A) remains in the map.

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

import java.util.HashMap;
import java.util.Map;

import org.happy.collections.maps.decorators.TransientMap_1x2;

import com.google.common.base.Preconditions;

/**
 * The example above creates a transient map with two objects (A,B), one of this objects will be used in the while-loop. 
 * The transientMap removes not used object (B), thus only used object (A) remains in the map.
 * @author Andreas Hollmann
 */
public class RemoveNotUsedElementsExample {

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        long maxAge = 1000;
        long updatePeriod = 100;
        final TransientMap_1x2<String, Object> transientMap = TransientMap_1x2.of(map, maxAge, updatePeriod);

        String key1 = "A";
        String key2 = "B";
        transientMap.put(key1 , "Andrej");
        transientMap.put(key2 , "Ben");

        long startTime = System.currentTimeMillis();
        while(true){
            //use key1
            transientMap.get(key1);
            if( (startTime + maxAge*2) < System.currentTimeMillis()){
                break;
            }
        }
        Preconditions.checkState(map.containsKey(key1));
        Preconditions.checkState(!map.containsKey(key2));
        System.out.println(transientMap);
    }

}