[Java] Simple Concurrenthashmap

Source: Internet
Author: User

Concurrentmap and Guava's LocalCache implementation principle is similar, the underlying storage mode uses the time table way to store. The simplest and most violent way to use this is to lock each time you visit.

Concurrenthashmap Interface:

Public interface Concurrenthashmap<k, v> {public    V get (k K);    public void put (K key, V value);    public void Putall (iterable<mapentry<k, v>> kiterator);    Public V remove (k k);}

Mapentry:

public class Mapentry<k, v> {    private K key;    private V value;    Public K GetKey () {        return key;    }    public void Setkey (K key) {        This.key = key;    }    Public V GetValue () {        return value;    }    public void SetValue (V value) {        this.value = value;    }}

Simpleconcurrenthashmap Interface:

Import Com.google.common.base.preconditions;import Com.google.common.collect.maps;import Java.util.HashMap;import  Java.util.iterator;public class Simpleconcurrenthashmap<k, v> implements Concurrenthashmap<k, V> {private    Final hashmap<k, v> cache = Maps.newhashmap ();        Public Simpleconcurrenthashmap () {} @Override public V get (k k) {Preconditions.checknotnull (k);        Synchronized (cache) {return cache.get (k);        }} @Override public void put (K key, V value) {preconditions.checknotnull (key);        Preconditions.checknotnull (value);        Synchronized (cache) {Cache.put (key, value); }} @Override public void Putall (iterable<mapentry<k, v>> entryiterable) {Preconditions.check        Notnull (entryiterable);        Iterator<mapentry<k, v>> Iterator = Entryiterable.iterator (); while (Iterator.hasnext ()) {mapentry<k, v> next = Iterator.next();        This.put (Next.getkey (), Next.getvalue ());        }} @Override public V remove (k k) {Preconditions.checknotnull (k);        Synchronized (cache) {return cache.remove (k); }    }}

  

[Java] Simple Concurrenthashmap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.