加锁方法对于Map

 hashmap是不带有锁的,hashtable是带有锁的,多线程使用过程中,需要对hashmap加锁,可以用

1.使用 synchronized 关键字,这也是最原始的方法。代码如下

synchronized(anObject)  {   

     value = map.get(key);

}  

2.使用 JDK1.5 提供的锁(java.util.concurrent.locks.Lock)。代码如下2.

Java代码  复制代码
  1. lock.lock();   
  2. value = map.get(key);   
  3. lock.unlock();  

3.这样处理时对于hashmap的读写都加锁了,但是如果涉及到少量插入及频繁的查找,那么上面两种的效率不是很高,这时候最好的方式是加读写锁。以下为构造读写锁包装map的方法:

[java] view plain copy
  1. <span style="font-size:18px;">import java.util.Map;  
  2. import java.util.concurrent.locks.Lock;  
  3. import java.util.concurrent.locks.ReadWriteLock;  
  4. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  5.   
  6. public class ReadWriteMap<K, V> {  
  7.     private final Map<K, V> map;  
  8.     private final ReadWriteLock lock = new ReentrantReadWriteLock();  
  9.     private final Lock r = lock.readLock();  
  10.     private final Lock w = lock.writeLock();  
  11.   
  12.     public ReadWriteMap(Map<K, V> map) {  
  13.         this.map = map;  
  14.     }  
  15.   
  16.     public V put(K key, V value) {  
  17.         w.lock();  
  18.         try {  
  19.             return map.put(key, value);  
  20.         } finally {  
  21.             w.unlock();  
  22.         }  
  23.     }  
  24.   
  25.     public V get(Object key) {  
  26.         r.lock();  
  27.         try {  
  28.             return map.get(key);  
  29.         } finally {  
  30.             r.unlock();  
  31.         }  
  32.     }  
  33. }</span>  

 

 

4、使用 JDK1.5 提供的 java.util.concurrent.ConcurrentHashMap 类。该类将 Map 的存储空间分为若干块,每块拥有自己的锁,大大减少了多个线程争夺同一个锁的情况。代码如下

value = map.get(key);  //同步机制内置在 get 方法中

这种方式最快

 

结论: 

1、如果 ConcurrentHashMap 够用,则使用 ConcurrentHashMap。 
2、如果需自己实现同步,则使用 JDK1.5 提供的锁机制,避免使用 synchronized 关键字。

 

 

package com.cyyun.xc.command.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

public class testendpoint {

	protected volatile boolean running = false;
	/**
	 * Server socket acceptor thread.
	 */
	protected ServerSocket serverSocket = null;
	protected ServerSocketFactory serverSocketFactory = null;

	public void start() throws Exception {
		running = true;
		// 获得serverSocketFactory
		serverSocketFactory = ServerSocketFactory.getDefault();
		// 获得serverSocket,监听8080端口
		serverSocket = serverSocketFactory.createServerSocket(8888);
		// 建立监听线程
		Thread acceptorThread = new Thread(new Acceptor(), "-Acceptor-");
		acceptorThread.start();
	}

	// 处理socket
	protected boolean processSocket(Socket socket) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));
		String inputLine;
		while ((inputLine = in.readLine()) != null) {
			System.out.println(inputLine);
		}

		return true;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		testendpoint ts = new testendpoint();
		try {
			System.out.println("Server start");
			ts.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// 监听类,不断循环
	protected class Acceptor implements Runnable {

		/**
		 * The background thread that listens for incoming TCP/IP connections
		 * and hands them off to an appropriate processor.
		 */
		public void run() {

			// Loop until we receive a shutdown command
			while (running) {

				// Loop if endpoint is paused
				// Accept the next incoming connection from the server socket
				try {
					Socket socket = serverSocket.accept();
					// Hand this socket off to an appropriate processor
					if (!processSocket(socket)) {
						// Close socket right away
						try {
							socket.close();
						} catch (IOException e) {
							// Ignore
						}
					}
				} catch (IOException x) {

				} catch (Throwable t) {

				}

				// The processor will recycle itself when it finishes

			}

		}

	}
}

 

 

Server start
GET / HTTP/1.1
Host: localhost:8888
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive

POST /aer HTTP/1.1
Content-Length: 1189
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 127.0.0.1:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.5 (java 1.5)

POST / HTTP/1.1
Content-Length: 1189
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 127.0.0.1:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.5 (java 1.5)

POST / HTTP/1.1
Content-Length: 10
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: 127.0.0.1:8888
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.3.5 (java 1.5)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值