java的concurrent用法详解
http://www.ibm.com/developerworks/cn/java/j-5things4.html
http://blog.csdn.net/cping1982/article/details/1931539
http://www.open-open.com/bbs/view/1320131360999/
http://www.open-open.com/bbs/view/1320131462624
我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,
当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便。
而当针对高质量Java多线程并发程序设计时,为防止死蹦等现象的出现,
比如使用java之前的wait()、notify()和synchronized等,
每每需要考虑性能、死锁、公平性、资源管理以及如何避免线程安全性方面带来的危害等诸多因素,
往往会采用一些较为复杂的安全策略,加重了程序员的开发负担.万幸的是,
在JDK1.5出现之后,Sun大神(Doug Lea)终于为我们这些可怜的小程序员推出了
java.util.concurrent工具包以简化并发完成。
开发者们借助于此,将有效的减少竞争条件(race conditions)和死锁线程。
concurrent包很好的解决了这些问题,为我们提供了更实用的并发程序模型。
Semaphore :一个计数信号量
ReentrantLock :一个可重入的互斥锁定 Lock,功能类似synchronized,但要强大的多。
Future :是与Runnable,Callable进行交互的接口,比如一个线程执行结束后取返回的结果等等,还提供了cancel终止线程。
BlockingQueue :阻塞队列。
CompletionService : ExecutorService的扩展,可以获得线程执行结果的
CountDownLatch :一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
CyclicBarrier :一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点
Future :Future 表示异步计算的结果。
ScheduledExecutorService :一个 ExecutorService,可安排在给定的延迟后运行或定期执行的命令。
Callable
TimeUnit
CopyOnWriteArrayList
ConcurrentMap
SynchronousQueues
Java Concurrent处理并发需求
java5开始,增加了concurrent api,用于并发处理。比如起多个线程并发从网络上下载图片,然后在本地显示。
这里写个简单的代码,来说明如何使用concurrent api提供的线程连接池。
运行结果类似这样:
start do 1 task …
>>main thread end.
start do 2 task …
start do 1 finished.
start do 3 task …
start do 2 finished.
start do 3 finished.
这里的task1到task3,都做的同样的事情,让它所属的线程休眠2000ms:
1
private static void doSomething(int id) {
2
System.out.println("start do " + id + " task …");
3
try {
4
Thread.sleep(1000 * 2);
5
} catch (InterruptedException e) {
6
e.printStackTrace();
7
}
8
System.out.println("start do " + id + " finished.");
9
}
如果没有java自带的这个api,需要自己或者使用不标准的第三方线程池api。用concurrent api写起来很简洁:
package com.easymorse.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new Runnable() {
@Override
public void run() {
doSomething(1);
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
doSomething(2);
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
doSomething(3);
}
});
executorService.shutdown();
System.out.println(">>main thread end.");
}
private static void doSomething(int id) {
System.out.println("start do " + id + " task ...");
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("start do " + id + " finished.");
}
}
首先,创建了一个线程池,里面有2个线程:
ExecutorService executorService = Executors.newFixedThreadPool(2);
然后,通过submit()方法,提交一个Runnable的实例,这个实例将交由线程池中空闲的线程执行。
在main线程中直接运行了:
executorService.shutdown();
不必担心,线程池不会直接关闭的,只有当它执行完所有提交的任务后才会关闭。
如果不写这行,在本例中,应用将不会停止,因为虽然main线程(就是运行main方法的线程,也叫主线程)退出了,
但是线程池中依然有线程运行,因此应用(进程)不会退出。
ConcurrentMap和HashMap的区别
1。hashMap可以有null的键,concurrentMap不可以有
2。hashMap是线程不安全的,在多线程的时候需要Collections.synchronizedMap(hashMap),ConcurrentMap使用了重入锁保证线程安全。
3。在删除元素时候,两者的算法不一样。
ConcurrentMap.putIfAbsent(key,value) 用法讨论
先看一段代码
public class Locale {
private final static Map<String, Locale> map = new HashMap<String,Locale>();
public static Locale getInstance(String language, String country,
String variant) {
//...
String key = some_string;
Locale locale = map.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
map.put(key, locale);
}
return locale;
}
// ....
}
这段代码要做的事情是:
调用 map.get(key) 方法,判断 map 里面是否有该 key 对应的 value (Locale 对象)。
如果返回 null,表示 map 里面没有要查找的 key-value mapping。new 一个 Locale 对象,并把 new 出来的这个对象与 key 一起放入 map。
最后返回新创建的 Locale 对象
我们期望每次调用 getInstance 方法时要保证相同的 key 返回同一个 Local 对象引用。那么,单看第一段代码,请问它能实现这个期望么?
答案是:在单线程环境下可以满足要求,但是在多线程环境下会存在线程安全性问题,即不能保证在并发的情况相同的 key 返回同一个 Local 对象引用。
这是因为在上面的代码里存在一个习惯被称为 put-if-absent 的操作 [1],而这个操作存在一个 race condition:
if (locale == null) {
locale = new Locale(language, country, variant);
map.put(key, locale);
}
因为在某个线程做完 locale == null 的判断到真正向 map 里面 put 值这段时间,其他线程可能已经往 map 做了 put 操作,
这样再做 put 操作时,同一个 key 对应的 locale 对象被覆盖掉,
最终 getInstance 方法返回的同一个 key 的 locale 引用就会出现不一致的情形。
所以对 Map 的 put-if-absent 操作是不安全的(thread safty)。
为了解决这个问题,java 5.0 引入了 ConcurrentMap 接口,
在这个接口里面 put-if-absent 操作以原子性方法 putIfAbsent(K key, V value) 的形式存在。
所以可以使用该方法替代上面代码里的操作。但是,替代的时候很容易犯一个错误。请看下面的代码:
public class Locale implements Cloneable, Serializable {
private final static ConcurrentMap<String, Locale> map = new ConcurrentHashMap<String, Locale>();
public static Locale getInstance(String language, String country,
String variant) {
//...
String key = some_string;
Locale locale = map.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
map.putIfAbsent(key, locale);
}
return locale;
}
// ....
}
这段代码使用了 Map 的 concurrent 形式(ConcurrentMap、ConcurrentHashMap),
并简单的使用了语句map.putIfAbsent(key, locale) 。这同样不能保证相同的 key 返回同一个 Locale 对象引用。
这里的错误出在忽视了 putIfAbsent 方法是有返回值的,并且返回值很重要。
“如果(调用该方法时)key-value 已经存在,则返回那个 value 值。如果调用时 map 里没有找到 key 的 mapping,返回一个 null 值”
所以,使用 putIfAbsent 方法时切记要对返回值进行判断。如下所示(java.util.Locale 类中的实现代码):
public final class Locale implements Cloneable, Serializable {
// cache to store singleton Locales
private final static ConcurrentHashMap<String, Locale> cache = new ConcurrentHashMap<String, Locale>(32);
static Locale getInstance(String language, String country, String variant) {
if (language== null || country == null || variant == null) {
throw new NullPointerException();
}
StringBuilder sb = new StringBuilder();
sb.append(language).append('_').append(country).append('_').append(variant);
String key = sb.toString();
Locale locale = cache.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
Locale l = cache.putIfAbsent(key, locale);
//与前段代码相比,增加了对方法返回值的判断:
if (l != null) {
locale = l;
}
}
return locale;
}
// ....
}
这样可以保证并发情况下代码行为的准确行。
http://www.ibm.com/developerworks/cn/java/j-5things4.html
http://blog.csdn.net/cping1982/article/details/1931539
http://www.open-open.com/bbs/view/1320131360999/
http://www.open-open.com/bbs/view/1320131462624
我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,
当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便。
而当针对高质量Java多线程并发程序设计时,为防止死蹦等现象的出现,
比如使用java之前的wait()、notify()和synchronized等,
每每需要考虑性能、死锁、公平性、资源管理以及如何避免线程安全性方面带来的危害等诸多因素,
往往会采用一些较为复杂的安全策略,加重了程序员的开发负担.万幸的是,
在JDK1.5出现之后,Sun大神(Doug Lea)终于为我们这些可怜的小程序员推出了
java.util.concurrent工具包以简化并发完成。
开发者们借助于此,将有效的减少竞争条件(race conditions)和死锁线程。
concurrent包很好的解决了这些问题,为我们提供了更实用的并发程序模型。
Semaphore :一个计数信号量
ReentrantLock :一个可重入的互斥锁定 Lock,功能类似synchronized,但要强大的多。
Future :是与Runnable,Callable进行交互的接口,比如一个线程执行结束后取返回的结果等等,还提供了cancel终止线程。
BlockingQueue :阻塞队列。
CompletionService : ExecutorService的扩展,可以获得线程执行结果的
CountDownLatch :一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
CyclicBarrier :一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点
Future :Future 表示异步计算的结果。
ScheduledExecutorService :一个 ExecutorService,可安排在给定的延迟后运行或定期执行的命令。
Callable
TimeUnit
CopyOnWriteArrayList
ConcurrentMap
SynchronousQueues
Java Concurrent处理并发需求
java5开始,增加了concurrent api,用于并发处理。比如起多个线程并发从网络上下载图片,然后在本地显示。
这里写个简单的代码,来说明如何使用concurrent api提供的线程连接池。
运行结果类似这样:
start do 1 task …
>>main thread end.
start do 2 task …
start do 1 finished.
start do 3 task …
start do 2 finished.
start do 3 finished.
这里的task1到task3,都做的同样的事情,让它所属的线程休眠2000ms:
1
private static void doSomething(int id) {
2
System.out.println("start do " + id + " task …");
3
try {
4
Thread.sleep(1000 * 2);
5
} catch (InterruptedException e) {
6
e.printStackTrace();
7
}
8
System.out.println("start do " + id + " finished.");
9
}
如果没有java自带的这个api,需要自己或者使用不标准的第三方线程池api。用concurrent api写起来很简洁:
package com.easymorse.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new Runnable() {
@Override
public void run() {
doSomething(1);
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
doSomething(2);
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
doSomething(3);
}
});
executorService.shutdown();
System.out.println(">>main thread end.");
}
private static void doSomething(int id) {
System.out.println("start do " + id + " task ...");
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("start do " + id + " finished.");
}
}
首先,创建了一个线程池,里面有2个线程:
ExecutorService executorService = Executors.newFixedThreadPool(2);
然后,通过submit()方法,提交一个Runnable的实例,这个实例将交由线程池中空闲的线程执行。
在main线程中直接运行了:
executorService.shutdown();
不必担心,线程池不会直接关闭的,只有当它执行完所有提交的任务后才会关闭。
如果不写这行,在本例中,应用将不会停止,因为虽然main线程(就是运行main方法的线程,也叫主线程)退出了,
但是线程池中依然有线程运行,因此应用(进程)不会退出。
ConcurrentMap和HashMap的区别
1。hashMap可以有null的键,concurrentMap不可以有
2。hashMap是线程不安全的,在多线程的时候需要Collections.synchronizedMap(hashMap),ConcurrentMap使用了重入锁保证线程安全。
3。在删除元素时候,两者的算法不一样。
ConcurrentMap.putIfAbsent(key,value) 用法讨论
先看一段代码
public class Locale {
private final static Map<String, Locale> map = new HashMap<String,Locale>();
public static Locale getInstance(String language, String country,
String variant) {
//...
String key = some_string;
Locale locale = map.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
map.put(key, locale);
}
return locale;
}
// ....
}
这段代码要做的事情是:
调用 map.get(key) 方法,判断 map 里面是否有该 key 对应的 value (Locale 对象)。
如果返回 null,表示 map 里面没有要查找的 key-value mapping。new 一个 Locale 对象,并把 new 出来的这个对象与 key 一起放入 map。
最后返回新创建的 Locale 对象
我们期望每次调用 getInstance 方法时要保证相同的 key 返回同一个 Local 对象引用。那么,单看第一段代码,请问它能实现这个期望么?
答案是:在单线程环境下可以满足要求,但是在多线程环境下会存在线程安全性问题,即不能保证在并发的情况相同的 key 返回同一个 Local 对象引用。
这是因为在上面的代码里存在一个习惯被称为 put-if-absent 的操作 [1],而这个操作存在一个 race condition:
if (locale == null) {
locale = new Locale(language, country, variant);
map.put(key, locale);
}
因为在某个线程做完 locale == null 的判断到真正向 map 里面 put 值这段时间,其他线程可能已经往 map 做了 put 操作,
这样再做 put 操作时,同一个 key 对应的 locale 对象被覆盖掉,
最终 getInstance 方法返回的同一个 key 的 locale 引用就会出现不一致的情形。
所以对 Map 的 put-if-absent 操作是不安全的(thread safty)。
为了解决这个问题,java 5.0 引入了 ConcurrentMap 接口,
在这个接口里面 put-if-absent 操作以原子性方法 putIfAbsent(K key, V value) 的形式存在。
所以可以使用该方法替代上面代码里的操作。但是,替代的时候很容易犯一个错误。请看下面的代码:
public class Locale implements Cloneable, Serializable {
private final static ConcurrentMap<String, Locale> map = new ConcurrentHashMap<String, Locale>();
public static Locale getInstance(String language, String country,
String variant) {
//...
String key = some_string;
Locale locale = map.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
map.putIfAbsent(key, locale);
}
return locale;
}
// ....
}
这段代码使用了 Map 的 concurrent 形式(ConcurrentMap、ConcurrentHashMap),
并简单的使用了语句map.putIfAbsent(key, locale) 。这同样不能保证相同的 key 返回同一个 Locale 对象引用。
这里的错误出在忽视了 putIfAbsent 方法是有返回值的,并且返回值很重要。
“如果(调用该方法时)key-value 已经存在,则返回那个 value 值。如果调用时 map 里没有找到 key 的 mapping,返回一个 null 值”
所以,使用 putIfAbsent 方法时切记要对返回值进行判断。如下所示(java.util.Locale 类中的实现代码):
public final class Locale implements Cloneable, Serializable {
// cache to store singleton Locales
private final static ConcurrentHashMap<String, Locale> cache = new ConcurrentHashMap<String, Locale>(32);
static Locale getInstance(String language, String country, String variant) {
if (language== null || country == null || variant == null) {
throw new NullPointerException();
}
StringBuilder sb = new StringBuilder();
sb.append(language).append('_').append(country).append('_').append(variant);
String key = sb.toString();
Locale locale = cache.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
Locale l = cache.putIfAbsent(key, locale);
//与前段代码相比,增加了对方法返回值的判断:
if (l != null) {
locale = l;
}
}
return locale;
}
// ....
}
这样可以保证并发情况下代码行为的准确行。