hashmap是不带有锁的,hashtable是带有锁的,多线程使用过程中,需要对hashmap加锁,可以用
1.使用 synchronized 关键字,这也是最原始的方法。代码如下
synchronized(anObject) {
value = map.get(key);
}
2.使用 JDK1.5 提供的锁(java.util.concurrent.locks.Lock)。代码如下2.
- lock.lock();
- value = map.get(key);
- lock.unlock();
3.这样处理时对于hashmap的读写都加锁了,但是如果涉及到少量插入及频繁的查找,那么上面两种的效率不是很高,这时候最好的方式是加读写锁。以下为构造读写锁包装map的方法:
- <span style="font-size:18px;">import java.util.Map;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReadWriteLock;
- import java.util.concurrent.locks.ReentrantReadWriteLock;
- public class ReadWriteMap<K, V> {
- private final Map<K, V> map;
- private final ReadWriteLock lock = new ReentrantReadWriteLock();
- private final Lock r = lock.readLock();
- private final Lock w = lock.writeLock();
- public ReadWriteMap(Map<K, V> map) {
- this.map = map;
- }
- public V put(K key, V value) {
- w.lock();
- try {
- return map.put(key, value);
- } finally {
- w.unlock();
- }
- }
- public V get(Object key) {
- r.lock();
- try {
- return map.get(key);
- } finally {
- r.unlock();
- }
- }
- }</span>
4、使用 JDK1.5 提供的 java.util.concurrent.ConcurrentHashMap 类。该类将 Map 的存储空间分为若干块,每块拥有自己的锁,大大减少了多个线程争夺同一个锁的情况。代码如下
这种方式最快
结论:
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)