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;
024import java.util.Objects;
025
026import org.apache.commons.collections4.Factory;
027import org.apache.commons.collections4.Transformer;
028import org.apache.commons.collections4.functors.FactoryTransformer;
029
030/**
031 * Decorates another {@code Map} to create objects in the map on demand.
032 * <p>
033 * When the {@link #get(Object)} method is called with a key that does not
034 * exist in the map, the factory is used to create the object. The created
035 * object will be added to the map using the requested key.
036 * </p>
037 * <p>
038 * For instance:
039 * </p>
040 * <pre>
041 * Factory&lt;Date&gt; factory = new Factory&lt;Date&gt;() {
042 *     public Date create() {
043 *         return new Date();
044 *     }
045 * }
046 * Map&lt;String, Date&gt; lazy = LazyMap.lazyMap(new HashMap&lt;String, Date&gt;(), factory);
047 * Date date = lazy.get("NOW");
048 * </pre>
049 *
050 * <p>
051 * After the above code is executed, {@code date} will refer to
052 * a new {@code Date} instance. Furthermore, that {@code Date}
053 * instance is mapped to the "NOW" key in the map.
054 * </p>
055 * <p>
056 * <strong>Note that LazyMap is not synchronized and is not thread-safe.</strong>
057 * If you wish to use this map from multiple threads concurrently, you must use
058 * appropriate synchronization. The simplest approach is to wrap this map
059 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
060 * exceptions when accessed by concurrent threads without synchronization.
061 * </p>
062 * <p>
063 * This class is Serializable from Commons Collections 3.1.
064 * </p>
065 *
066 * @param <K> the type of the keys in this map
067 * @param <V> the type of the values in this map
068 * @since 3.0
069 */
070public class LazyMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {
071
072    /** Serialization version */
073    private static final long serialVersionUID = 7990956402564206740L;
074
075    /**
076     * Factory method to create a lazily instantiated map.
077     *
078     * @param <K>  the key type
079     * @param <V>  the value type
080     * @param map  the map to decorate, must not be null
081     * @param factory  the factory to use, must not be null
082     * @return a new lazy map
083     * @throws NullPointerException if map or factory is null
084     * @since 4.0
085     */
086    public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Factory<? extends V> factory) {
087        return new LazyMap<>(map, factory);
088    }
089
090    /**
091     * Factory method to create a lazily instantiated map.
092     *
093     * @param <K>  the key type
094     * @param <V>  the value type
095     * @param map  the map to decorate, must not be null
096     * @param factory  the factory to use, must not be null
097     * @return a new lazy map
098     * @throws NullPointerException if map or factory is null
099     * @since 4.0
100     */
101    public static <V, K> LazyMap<K, V> lazyMap(final Map<K, V> map, final Transformer<? super K, ? extends V> factory) {
102        return new LazyMap<>(map, factory);
103    }
104
105    /** The factory to use to construct elements */
106    protected final Transformer<? super K, ? extends V> factory;
107
108    /**
109     * Constructor that wraps (not copies).
110     *
111     * @param map  the map to decorate, must not be null
112     * @param factory  the factory to use, must not be null
113     * @throws NullPointerException if map or factory is null
114     */
115    protected LazyMap(final Map<K, V> map, final Factory<? extends V> factory) {
116        super(map);
117        this.factory = FactoryTransformer.factoryTransformer(Objects.requireNonNull(factory, "factory"));
118    }
119
120    /**
121     * Constructor that wraps (not copies).
122     *
123     * @param map  the map to decorate, must not be null
124     * @param factory  the factory to use, must not be null
125     * @throws NullPointerException if map or factory is null
126     */
127    protected LazyMap(final Map<K, V> map, final Transformer<? super K, ? extends V> factory) {
128        super(map);
129        this.factory = Objects.requireNonNull(factory, "factory");
130    }
131
132    @Override
133    public V get(final Object key) {
134        // create value for key if key is not currently in the map
135        if (!map.containsKey(key)) {
136            @SuppressWarnings("unchecked")
137            final K castKey = (K) key;
138            final V value = factory.transform(castKey);
139            map.put(castKey, value);
140            return value;
141        }
142        return map.get(key);
143    }
144
145    /**
146     * Read the map in using a custom routine.
147     *
148     * @param in  the input stream
149     * @throws IOException if an error occurs while reading from the stream
150     * @throws ClassNotFoundException if an object read from the stream can not be loaded
151     * @since 3.1
152     */
153    @SuppressWarnings("unchecked")
154    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
155        in.defaultReadObject();
156        map = (Map<K, V>) in.readObject();
157    }
158
159    /**
160     * Write the map out using a custom routine.
161     *
162     * @param out  the output stream
163     * @throws IOException if an error occurs while writing to the stream
164     * @since 3.1
165     */
166    private void writeObject(final ObjectOutputStream out) throws IOException {
167        out.defaultWriteObject();
168        out.writeObject(map);
169    }
170
171    // no need to wrap keySet, entrySet or values as they are views of
172    // existing map entries - you can't do a map-style get on them.
173}