LazyMap.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.collections4.map;

  18. import java.io.IOException;
  19. import java.io.ObjectInputStream;
  20. import java.io.ObjectOutputStream;
  21. import java.io.Serializable;
  22. import java.util.Map;
  23. import java.util.Objects;

  24. import org.apache.commons.collections4.Factory;
  25. import org.apache.commons.collections4.Transformer;
  26. import org.apache.commons.collections4.functors.FactoryTransformer;

  27. /**
  28.  * Decorates another {@code Map} to create objects in the map on demand.
  29.  * <p>
  30.  * When the {@link #get(Object)} method is called with a key that does not
  31.  * exist in the map, the factory is used to create the object. The created
  32.  * object will be added to the map using the requested key.
  33.  * </p>
  34.  * <p>
  35.  * For instance:
  36.  * </p>
  37.  * <pre>
  38.  * Factory&lt;Date&gt; factory = new Factory&lt;Date&gt;() {
  39.  *     public Date create() {
  40.  *         return new Date();
  41.  *     }
  42.  * }
  43.  * Map&lt;String, Date&gt; lazy = LazyMap.lazyMap(new HashMap&lt;String, Date&gt;(), factory);
  44.  * Date date = lazy.get("NOW");
  45.  * </pre>
  46.  *
  47.  * <p>
  48.  * After the above code is executed, {@code date} will refer to
  49.  * a new {@code Date} instance. Furthermore, that {@code Date}
  50.  * instance is mapped to the "NOW" key in the map.
  51.  * </p>
  52.  * <p>
  53.  * <strong>Note that LazyMap is not synchronized and is not thread-safe.</strong>
  54.  * If you wish to use this map from multiple threads concurrently, you must use
  55.  * appropriate synchronization. The simplest approach is to wrap this map
  56.  * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
  57.  * exceptions when accessed by concurrent threads without synchronization.
  58.  * </p>
  59.  * <p>
  60.  * This class is Serializable from Commons Collections 3.1.
  61.  * </p>
  62.  *
  63.  * @param <K> the type of the keys in this map
  64.  * @param <V> the type of the values in this map
  65.  * @since 3.0
  66.  */
  67. public class LazyMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {

  68.     /** Serialization version */
  69.     private static final long serialVersionUID = 7990956402564206740L;

  70.     /**
  71.      * Factory method to create a lazily instantiated map.
  72.      *
  73.      * @param <K>  the key type
  74.      * @param <V>  the value type
  75.      * @param map  the map to decorate, must not be null
  76.      * @param factory  the factory to use, must not be null
  77.      * @return a new lazy map
  78.      * @throws NullPointerException if map or factory is null
  79.      * @since 4.0
  80.      */
  81.     public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory) {
  82.         return new LazyMap<>(map, factory);
  83.     }

  84.     /**
  85.      * Factory method to create a lazily instantiated map.
  86.      *
  87.      * @param <K>  the key type
  88.      * @param <V>  the value type
  89.      * @param map  the map to decorate, must not be null
  90.      * @param factory  the factory to use, must not be null
  91.      * @return a new lazy map
  92.      * @throws NullPointerException if map or factory is null
  93.      * @since 4.0
  94.      */
  95.     public static <V, K> LazyMap<K, V> lazyMap(final Map<K, V> map, final Transformer<? super K, ? extends V> factory) {
  96.         return new LazyMap<>(map, factory);
  97.     }

  98.     /** The factory to use to construct elements */
  99.     protected final Transformer<? super K, ? extends V> factory;

  100.     /**
  101.      * Constructor that wraps (not copies).
  102.      *
  103.      * @param map  the map to decorate, must not be null
  104.      * @param factory  the factory to use, must not be null
  105.      * @throws NullPointerException if map or factory is null
  106.      */
  107.     protected LazyMap(final Map<K, V> map, final Factory<? extends V> factory) {
  108.         super(map);
  109.         this.factory = FactoryTransformer.factoryTransformer(Objects.requireNonNull(factory, "factory"));
  110.     }

  111.     /**
  112.      * Constructor that wraps (not copies).
  113.      *
  114.      * @param map  the map to decorate, must not be null
  115.      * @param factory  the factory to use, must not be null
  116.      * @throws NullPointerException if map or factory is null
  117.      */
  118.     protected LazyMap(final Map<K, V> map, final Transformer<? super K, ? extends V> factory) {
  119.         super(map);
  120.         this.factory = Objects.requireNonNull(factory, "factory");
  121.     }

  122.     @Override
  123.     public V get(final Object key) {
  124.         // create value for key if key is not currently in the map
  125.         if (!map.containsKey(key)) {
  126.             @SuppressWarnings("unchecked")
  127.             final K castKey = (K) key;
  128.             final V value = factory.apply(castKey);
  129.             map.put(castKey, value);
  130.             return value;
  131.         }
  132.         return map.get(key);
  133.     }

  134.     /**
  135.      * Deserializes the map in using a custom routine.
  136.      *
  137.      * @param in  the input stream
  138.      * @throws IOException if an error occurs while reading from the stream
  139.      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
  140.      * @since 3.1
  141.      */
  142.     @SuppressWarnings("unchecked")
  143.     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
  144.         in.defaultReadObject();
  145.         map = (Map<K, V>) in.readObject();
  146.     }

  147.     /**
  148.      * Serializes this object to an ObjectOutputStream.
  149.      *
  150.      * @param out the target ObjectOutputStream.
  151.      * @throws IOException thrown when an I/O errors occur writing to the target stream.
  152.      * @since 3.1
  153.      */
  154.     private void writeObject(final ObjectOutputStream out) throws IOException {
  155.         out.defaultWriteObject();
  156.         out.writeObject(map);
  157.     }

  158.     // no need to wrap keySet, entrySet or values as they are views of
  159.     // existing map entries - you can't do a map-style get on them.
  160. }