001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.map;
018
019import java.io.IOException;
020import java.io.ObjectInputStream;
021import java.io.ObjectOutputStream;
022import java.io.Serializable;
023import java.util.Map;
024
025import org.apache.commons.collections4.Factory;
026import org.apache.commons.collections4.Transformer;
027import org.apache.commons.collections4.functors.FactoryTransformer;
028
029/**
030 * Decorates another <code>Map</code> to create objects in the map on demand.
031 * <p>
032 * When the {@link #get(Object)} method is called with a key that does not
033 * exist in the map, the factory is used to create the object. The created
034 * object will be added to the map using the requested key.
035 * <p>
036 * For instance:
037 * <pre>
038 * Factory&lt;Date&gt; factory = new Factory&lt;Date&gt;() {
039 *     public Date create() {
040 *         return new Date();
041 *     }
042 * }
043 * Map&lt;String, Date&gt; lazy = LazyMap.lazyMap(new HashMap&lt;String, Date&gt;(), factory);
044 * Date date = lazy.get("NOW");
045 * </pre>
046 *
047 * After the above code is executed, <code>date</code> will refer to
048 * a new <code>Date</code> instance. Furthermore, that <code>Date</code>
049 * instance is mapped to the "NOW" key in the map.
050 * <p>
051 * <strong>Note that LazyMap is not synchronized and is not thread-safe.</strong>
052 * If you wish to use this map from multiple threads concurrently, you must use
053 * appropriate synchronization. The simplest approach is to wrap this map
054 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
055 * exceptions when accessed by concurrent threads without synchronization.
056 * <p>
057 * This class is Serializable from Commons Collections 3.1.
058 *
059 * @since 3.0
060 * @version $Id: LazyMap.html 972421 2015-11-14 20:00:04Z tn $
061 */
062public class LazyMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {
063
064    /** Serialization version */
065    private static final long serialVersionUID = 7990956402564206740L;
066
067    /** The factory to use to construct elements */
068    protected final Transformer<? super K, ? extends V> factory;
069
070    /**
071     * Factory method to create a lazily instantiated map.
072     *
073     * @param <K>  the key type
074     * @param <V>  the value type
075     * @param map  the map to decorate, must not be null
076     * @param factory  the factory to use, must not be null
077     * @return a new lazy map
078     * @throws IllegalArgumentException if map or factory is null
079     * @since 4.0
080     */
081    public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Factory< ? extends V> factory) {
082        return new LazyMap<K,V>(map, factory);
083    }
084
085    /**
086     * Factory method to create a lazily instantiated map.
087     *
088     * @param <K>  the key type
089     * @param <V>  the value type
090     * @param map  the map to decorate, must not be null
091     * @param factory  the factory to use, must not be null
092     * @return a new lazy map
093     * @throws IllegalArgumentException if map or factory is null
094     * @since 4.0
095     */
096    public static <V, K> LazyMap<K, V> lazyMap(final Map<K, V> map, final Transformer<? super K, ? extends V> factory) {
097        return new LazyMap<K,V>(map, factory);
098    }
099
100    //-----------------------------------------------------------------------
101    /**
102     * Constructor that wraps (not copies).
103     *
104     * @param map  the map to decorate, must not be null
105     * @param factory  the factory to use, must not be null
106     * @throws IllegalArgumentException if map or factory is null
107     */
108    protected LazyMap(final Map<K,V> map, final Factory<? extends V> factory) {
109        super(map);
110        if (factory == null) {
111            throw new IllegalArgumentException("Factory must not be null");
112        }
113        this.factory = FactoryTransformer.factoryTransformer(factory);
114    }
115
116    /**
117     * Constructor that wraps (not copies).
118     *
119     * @param map  the map to decorate, must not be null
120     * @param factory  the factory to use, must not be null
121     * @throws IllegalArgumentException if map or factory is null
122     */
123    protected LazyMap(final Map<K,V> map, final Transformer<? super K, ? extends V> factory) {
124        super(map);
125        if (factory == null) {
126            throw new IllegalArgumentException("Factory must not be null");
127        }
128        this.factory = factory;
129    }
130
131    //-----------------------------------------------------------------------
132    /**
133     * Write the map out using a custom routine.
134     *
135     * @param out  the output stream
136     * @throws IOException
137     * @since 3.1
138     */
139    private void writeObject(final ObjectOutputStream out) throws IOException {
140        out.defaultWriteObject();
141        out.writeObject(map);
142    }
143
144    /**
145     * Read the map in using a custom routine.
146     *
147     * @param in  the input stream
148     * @throws IOException
149     * @throws ClassNotFoundException
150     * @since 3.1
151     */
152    @SuppressWarnings("unchecked")
153    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
154        in.defaultReadObject();
155        map = (Map<K, V>) in.readObject();
156    }
157
158    //-----------------------------------------------------------------------
159    @Override
160    public V get(final Object key) {
161        // create value for key if key is not currently in the map
162        if (map.containsKey(key) == false) {
163            @SuppressWarnings("unchecked")
164            final K castKey = (K) key;
165            final V value = factory.transform(castKey);
166            map.put(castKey, value);
167            return value;
168        }
169        return map.get(key);
170    }
171
172    // no need to wrap keySet, entrySet or values as they are views of
173    // existing map entries - you can't do a map-style get on them.
174}