• 为什么会快?


    下面是我在读commons-beanutils.jar时的一个类FastHashMap,

    大家从上面往下阅读代码,到最后有个红色代码块,有谁能告诉我蓝色代码为什么不能换成“return (map.put(key, value));”?   map.clone()在这里到底有什么作用呢?

    /*
     *  Copyright 2001-2004 The Apache Software Foundation
     *
     *  Licensed under the Apache License, Version 2.0 (the "License");
     *  you may not use this file except in compliance with the License.
     *  You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     *  Unless required by applicable law or agreed to in writing, software
     *  distributed under the License is distributed on an "AS IS" BASIS,
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     *  See the License for the specific language governing permissions and
     *  limitations under the License.
     */
    package org.apache.commons.collections;

    import java.util.Collection;
    import java.util.ConcurrentModificationException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;

    /**
     * <p>A customized implementation of <code>java.util.HashMap</code> designed
     * to operate in a multithreaded environment where the large majority of
     * method calls are read-only, instead of structural changes.  When operating
     * in "fast" mode, read calls are non-synchronized and write calls perform the
     * following steps:</p>
     * <ul>
     * <li>Clone the existing collection
     * <li>Perform the modification on the clone
     * <li>Replace the existing collection with the (modified) clone
     * </ul>
     * <p>When first created, objects of this class default to "slow" mode, where
     * all accesses of any type are synchronized but no cloning takes place.  This
     * is appropriate for initially populating the collection, followed by a switch
     * to "fast" mode (by calling <code>setFast(true)</code>) after initialization
     * is complete.</p>
     *
     * <p><strong>NOTE</strong>: If you are creating and accessing a
     * <code>HashMap</code> only within a single thread, you should use
     * <code>java.util.HashMap</code> directly (with no synchronization), for
     * maximum performance.</p>
     *
     * <p><strong>NOTE</strong>: <i>This class is not cross-platform. 
     * Using it may cause unexpected failures on some architectures.</i>
     * It suffers from the same problems as the double-checked locking idiom. 
     * In particular, the instruction that clones the internal collection and the
     * instruction that sets the internal reference to the clone can be executed
     * or perceived out-of-order.  This means that any read operation might fail
     * unexpectedly, as it may be reading the state of the internal collection
     * before the internal collection is fully formed.
     * For more information on the double-checked locking idiom, see the
     * <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html">
     * Double-Checked Locking Idiom Is Broken Declaration</a>.</p>
     *
     * @since Commons Collections 1.0
     * @version $Revision: 1.1 $ $Date: 2004/05/10 19:51:13 $
     *
     * @author Craig R. McClanahan
     * @author Stephen Colebourne
     */
    public class FastHashMap extends HashMap {

        /**
         * The underlying map we are managing.
         */
        protected HashMap map = null;

        /**
         * Are we currently operating in "fast" mode?
         */
        protected boolean fast = false;

        // Constructors
        // ----------------------------------------------------------------------

        /**
         * Construct an empty map.
         */
        public FastHashMap()

    Unknown macro: {        super();        this.map = new HashMap();    }

        /**
         * Construct an empty map with the specified capacity.
         *
         * @param capacity  the initial capacity of the empty map
         */
        public FastHashMap(int capacity)

    Unknown macro: {        super();        this.map = new HashMap(capacity);    }

        /**
         * Construct an empty map with the specified capacity and load factor.
         *
         * @param capacity  the initial capacity of the empty map
         * @param factor  the load factor of the new map
         */
        public FastHashMap(int capacity, float factor)

    Unknown macro: {        super();        this.map = new HashMap(capacity, factor);    }

        /**
         * Construct a new map with the same mappings as the specified map.
         *
         * @param map  the map whose mappings are to be copied
         */
        public FastHashMap(Map map)

    Unknown macro: {        super();        this.map = new HashMap(map);    }

        // Property access
        // ----------------------------------------------------------------------

        /**
         *  Returns true if this map is operating in fast mode.
         *
         *  @return true if this map is operating in fast mode
         */
        public boolean getFast()

    Unknown macro: {        return (this.fast);    }

        /**
         *  Sets whether this map is operating in fast mode.
         *
         *  @param fast true if this map should operate in fast mode
         */
        public void setFast(boolean fast)

    Unknown macro: {        this.fast = fast;    }

        // Map access
        // ----------------------------------------------------------------------
        // These methods can forward straight to the wrapped Map in 'fast' mode.
        // (because they are query methods)

        /**
         * Return the value to which this map maps the specified key.  Returns
         * <code>null</code> if the map contains no mapping for this key, or if
         * there is a mapping with a value of <code>null</code>.  Use the
         * <code>containsKey()</code> method to disambiguate these cases.
         *
         * @param key  the key whose value is to be returned
         * @return the value mapped to that key, or null
         */
        public Object get(Object key) {
            if (fast)

    Unknown macro: {            return (map.get(key));        }

    else {
                synchronized (map)

    Unknown macro: {                return (map.get(key));            }

            }
        }

        /**
         * Return the number of key-value mappings in this map.
         *
         * @return the current size of the map
         */
        public int size() {
            if (fast)

    Unknown macro: {            return (map.size());        }

    else {
                synchronized (map)

    Unknown macro: {                return (map.size());            }

            }
        }

        /**
         * Return <code>true</code> if this map contains no mappings.
         *
         * @return is the map currently empty
         */
        public boolean isEmpty() {
            if (fast)

    Unknown macro: {            return (map.isEmpty());        }

    else {
                synchronized (map)

    Unknown macro: {                return (map.isEmpty());            }

            }
        }

        /**
         * Return <code>true</code> if this map contains a mapping for the
         * specified key.
         *
         * @param key  the key to be searched for
         * @return true if the map contains the key
         */
        public boolean containsKey(Object key) {
            if (fast)

    Unknown macro: {            return (map.containsKey(key));        }

    else {
                synchronized (map)

    Unknown macro: {                return (map.containsKey(key));            }

            }
        }

        /**
         * Return <code>true</code> if this map contains one or more keys mapping
         * to the specified value.
         *
         * @param value  the value to be searched for
         * @return true if the map contains the value
         */
        public boolean containsValue(Object value) {
            if (fast)

    Unknown macro: {            return (map.containsValue(value));        }

    else {
                synchronized (map)

    Unknown macro: {                return (map.containsValue(value));            }

            }
        }

        // Map modification
        // ----------------------------------------------------------------------
        // These methods perform special behaviour in 'fast' mode.
        // The map is cloned, updated and then assigned back.
        // See the comments at the top as to why this won't always work.

        /**
         * Associate the specified value with the specified key in this map.
         * If the map previously contained a mapping for this key, the old
         * value is replaced and returned.
         *
         * @param key  the key with which the value is to be associated
         * @param value  the value to be associated with this key
         * @return the value previously mapped to the key, or null
         */
        public Object put(Object key, Object value) {
            if (fast) {
                synchronized (this) {
                    HashMap temp = (HashMap) map.clone();
                    Object result = temp.put(key, value);
                    map = temp;
                    return (result);
                }
            } else {
                synchronized (map) {
                    return (map.put(key, value));
                }
            }
        }

    。。。。。。接下去的代码不需要贴了

    今天仔细想了一下,应该是这样的:

        所谓FastHashMap主要是将原来线程不安全的HashMap改造成线程安全的HashMap,其中还分了两个模式:

             当在fast模式下,所有的读操作不存在互斥,所有的读操作和写操作不存在互斥,为了保证读完以后map不被修改,用了clone这个策略,也就是内存拷贝,什么叫内存拷贝?假如一个线程A在读,一个线程B在写,那么B操作的map是A操作的map的拷贝,这样不管B做了什么,都不会影响A的操作,这样就保证了不存在并发修。

              当不再fast模式下,为了做到线程同步,只能对整个map加锁,这样保证了map的线程安全性,但是整个map的各种操作都将只是单线程的,所以慢了。 

  • 相关阅读:
    shell 函数
    使用Alpine镜像构建镜像
    macos修改vmware Fusion的NAT网络
    K8s Pod与宿主机时区不同步
    nginx热升级
    awk分析web日志
    k8s 新建用户远程连接集群和context切换
    查询出口公网ip
    微服务之服务网格 Istio
    Systemd 、systemctl进程管理工具
  • 原文地址:https://www.cnblogs.com/sunwei2012/p/1863176.html
Copyright © 2020-2023  润新知