`
Donald_Draper
  • 浏览: 984788 次
社区版块
存档分类
最新评论

ConcurrentMap介绍

    博客分类:
  • JUC
阅读更多
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.Map;

/**
 * A {@link java.util.Map} providing additional atomic
 * <tt>putIfAbsent</tt>, <tt>remove</tt>, and <tt>replace</tt> methods.
 *
 ConcurrentMap提供了原子的操作putIfAbsent,remove,replace
 * <p>Memory consistency effects: As with other concurrent
 * collections, actions in a thread prior to placing an object into a
 * {@code ConcurrentMap} as a key or value
 * [url=package-summary.html#MemoryVisibility]<i>happen-before</i>[/url]
 * actions subsequent to the access or removal of that object from
 * the {@code ConcurrentMap} in another thread.
 *
 内存一致性:与其他并发集合意向,线程有限执行put操,即put的操作happen-before
 其他线程读操作或者移除操作。
 * <p>This interface is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 */
public interface ConcurrentMap<K, V> extends Map<K, V> {
    /**
     * If the specified key is not already associated
     * with a value, associate it with the given value.
     * This is equivalent to
     * <pre>
     *   if (!map.containsKey(key))
     *       return map.put(key, value);
     *   else
     *       return map.get(key);</pre>
     * except that the action is performed atomically.
     *
     如果Map不包含对应的Key则,执行put的操作,否则返回旧值
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with the specified key, or
     *         <tt>null</tt> if there was no mapping for the key.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with the key,
     *         if the implementation supports null values.)
     * @throws UnsupportedOperationException if the <tt>put</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     * @throws NullPointerException if the specified key or value is null,
     *         and this map does not permit null keys or values
     * @throws IllegalArgumentException if some property of the specified key
     *         or value prevents it from being stored in this map
     *
     */
    V putIfAbsent(K key, V value);

    /**
     * Removes the entry for a key only if currently mapped to a given value.
     * This is equivalent to
     * <pre>
     *   if (map.containsKey(key) &amp;&amp; map.get(key).equals(value)) {
     *       map.remove(key);
     *       return true;
     *   } else return false;</pre>
     * except that the action is performed atomically.
     *
     如果Map中存在Key和value相等的Entry,则移除
     * @param key key with which the specified value is associated
     * @param value value expected to be associated with the specified key
     * @return <tt>true</tt> if the value was removed
     * @throws UnsupportedOperationException if the <tt>remove</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the key or value is of an inappropriate
     *         type for this map
     *         ([url=../Collection.html#optional-restrictions]optional[/url])
     * @throws NullPointerException if the specified key or value is null,
     *         and this map does not permit null keys or values
     *         ([url=../Collection.html#optional-restrictions]optional[/url])
     */
    boolean remove(Object key, Object value);

    /**
     * Replaces the entry for a key only if currently mapped to a given value.
     * This is equivalent to
     * <pre>
     *   if (map.containsKey(key) &amp;&amp; map.get(key).equals(oldValue)) {
     *       map.put(key, newValue);
     *       return true;
     *   } else return false;</pre>
     * except that the action is performed atomically.
     *
     如果Map中存在Key和value相等的Entry,put的操作,更新值
     * @param key key with which the specified value is associated
     * @param oldValue value expected to be associated with the specified key
     * @param newValue value to be associated with the specified key
     * @return <tt>true</tt> if the value was replaced
     * @throws UnsupportedOperationException if the <tt>put</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of a specified key or value
     *         prevents it from being stored in this map
     * @throws NullPointerException if a specified key or value is null,
     *         and this map does not permit null keys or values
     * @throws IllegalArgumentException if some property of a specified key
     *         or value prevents it from being stored in this map
     */
    boolean replace(K key, V oldValue, V newValue);
    如果Map中存在Key相等的Entry,put的操作,更新值
    /**
     * Replaces the entry for a key only if currently mapped to some value.
     * This is equivalent to
     * <pre>
     *   if (map.containsKey(key)) {
     *       return map.put(key, value);
     *   } else return null;</pre>
     * except that the action is performed atomically.
     *
     * @param key key with which the specified value is associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with the specified key, or
     *         <tt>null</tt> if there was no mapping for the key.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with the key,
     *         if the implementation supports null values.)
     * @throws UnsupportedOperationException if the <tt>put</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     * @throws NullPointerException if the specified key or value is null,
     *         and this map does not permit null keys or values
     * @throws IllegalArgumentException if some property of the specified key
     *         or value prevents it from being stored in this map
     */
    V replace(K key, V value);
}

ConcurrentHashMap由于是线程安全,是否可以用ConcurrentHashMap来实现单例模式能,答案是肯定的
来看具体的实例:
package juc.map;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
 * 用ConcurrentHashMap实现单例模式
 * @author donald
 * 2017年3月11日
 * 下午6:18:09
 */
public class TestInstanceConcurrentMap {
		private static final ConcurrentMap<String, TestInstanceConcurrentMap> map = new ConcurrentHashMap<String, TestInstanceConcurrentMap>();
		private static TestInstanceConcurrentMap instance;
		/**
		 * 
		 * @return
		 */
		public static TestInstanceConcurrentMap getInstance() {
			if (instance == null) {
				map.putIfAbsent("INSTANCE", new TestInstanceConcurrentMap());
				instance = map.get("INSTANCE");
			}
			return instance;
		}
		/**
		 * 
		 */
		private TestInstanceConcurrentMap() {
		}
}


0
0
分享到:
评论

相关推荐

    基础技术部牛路《Java多线程入阶分享》纯干货

    5.Lock-free:atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList 6.关于锁的经验介绍 7.并发流程控制手段:CountDownLatch、Barrier 8.定时器:ScheduledExecutorService、大规模定时器TimerWheel 9.并发三...

    Python concurrent.futures模块使用实例

    这篇文章主要介绍了Python concurrent.futures模块使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 concurrent.futures的作用: 管理并发任务池。...

    Java并发程序设计教程

    5、Lock-free: atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList☆☆☆ 6、关于锁使用的经验介绍 7、并发流程控制手段:CountDownlatch、Barrier 8、定时器: ScheduledExecutorService、大规模定时器...

    Java编程并发程序设计

    5、Lock-free: atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList☆☆☆ 6、关于锁使用的经验介绍 7、并发流程控制手段:CountDownlatch、Barrier 8、定时器: ScheduledExecutorService、大规模定时器...

    使用Java并发编程Concurrent Programming Using Java

    - **ConcurrentHashMap**:一种线程安全的哈希表实现,相比传统的`synchronized`修饰的方法或者`Collections.synchronizedMap()`更加高效。 - **CopyOnWriteArrayList/CopyOnWriteArraySet**:这两个集合类采用“写...

    golang 并发安全Map以及分段锁的实现方法

    在这个例子中,`ConcurrentMap`是由多个`ConcurrentMapShared`组成的数组。每个`ConcurrentMapShared`代表一个分片,有自己的读写锁和内部存储`map`。 #### 初始化分段锁Map ```go func New() ConcurrentMap { m :...

    阿里面试题:ConcurrentHashMap为什么是线程安全的?

    先阅读一下两篇介绍HashMap的文章 你真的懂大厂面试题:HashMap吗? jdk1.7 HashMap中的致命错误:循环链表 jdk1.7 ConcurrentHashMap jdk1.7 ConcurrentHashMap数据结构 jdk1.7 ConcurrentHashMap是由一个Segment...

    java.util.concurrent系列文章(2)

    在上一篇文章中,我们简要介绍了并发集合类的基本概念及其重要性,并探讨了如何通过共享数据结构的方法来提高程序的并发性和吞吐量。本文将继续深入到 `java.util.concurrent` 包中的 `ConcurrentHashMap` 类,它是...

    mapdb-hz-offheap:为土耳其的内存中数据网格构建提供堆外存储

    赫兹 该项目为HZ地图提供堆外存储。 这是非官方的扩展和Hazelcast公司内部HZ它将替换不支持ConcurrentHashMap与离堆HTreeMap从 。 它独立于其他非堆解决方案,并且在... private final ConcurrentMap&lt; Data , Record

    python程序中的线程操作 concurrent模块使用详解

    一、concurrent模块的介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPoolExecutor:进程池,提供异步调用 ProcessPoolExecutor 和 ...

    Java并发编程实践-电子书-03章

    - **并发集合**:这些集合类为多线程环境提供了更高效的支持,主要包括`BlockingQueue`、`ConcurrentMap`、`ConcurrentNavigableMap`等。 - **同步器**:包括`Semaphore`、`Barrier`、`Latch`、`Exchanger`等,用于...

    mastering-c-multithreading-write-robust-concurrent-and-parallel

    5. **线程安全的数据结构**:介绍线程安全容器,如std::unordered_map和std::vector的线程安全版本,以及如何在多线程环境中正确使用它们。 6. **并发算法和并发模式**:讨论线程池、工作窃取队列、并行算法(如std...

    如何基于LoadingCache实现Java本地缓存

    Guava 是 Google 开源的一套工具库,其中提供的 cache 模块非常方便,是一种与 ConcurrentMap 相似的缓存 Map。Guava cache 模块提供了许多有用的特性,如自动加载、缓存池大小限制、缓存项过期时间设置、缓存项移除...

    Java Map遍历方法

    6. **注意并发问题**: 如果在多线程环境中遍历Map,应考虑使用`ConcurrentMap`的并发安全遍历方法,如`forEach()`,或者使用`Collections.synchronizedMap()`使普通Map线程安全。 7. **流式处理**: 自JDK 8起,还...

    Java8 Stream Collectors收集器使用方法解析

    Collectors.toConcurrentMap()方法可以将Stream流数据收集到ConcurrentMap中,第一个参数是key的函数,第二个参数是value的函数。例如: ```java Stream.of(studentA, studentB, studentC) .parallel() .collect...

    triemap:Scala集合库中并发trie哈希映射实现的Java端口

    关于这是Scala集合库中并发的trie哈希映射实现的Java端口。 它曾经是从Scala到Java的几乎逐行... 此类实现所有ConcurrentMap&Iterator方法并通过所有测试。 可以用作常规Java映射(包括ConcurrentHashMap)的直接替

    在Struts 2中实现CRUD

    private static final ConcurrentMap, Book&gt; data; static { instance = new BookDao(); data = new ConcurrentHashMap(); // 初始化数据... } // CRUD操作方法... } ``` 在`BookDao`类中,提供了获取所有...

    java面试宝典

    77、简述synchronized和java.util.concurrent.locks.Lock的异同 ? 18 78、abstract class Name { private String name; public abstract boolean isStupidName(String name) {}}这有何错误? 18 79、public class ...

    Python并行编程 中文版

    1. concurrent.futures模块使用:介绍如何使用这个模块来执行异步任务。 2. Asyncio模块:介绍Python的Asyncio库,用于编写单线程并发代码。 3. 事件循环管理:解释如何使用Asyncio管理事件循环。 4. 协程管理:...

Global site tag (gtag.js) - Google Analytics