ForkJoin框架与读写锁

Fork/Join框架就是在必要的情况下,将一个大任务,进行拆分(fork)成若千个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行join汇总。

mark

ForkJoin框架采用工作窃取模式(work-stealing) :当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。

相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上,在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行。这种方式减少了线程的等待时间,提高了性能。

ForkJoin框架

下面是一个很简单的示例,即用Fork/Join框架来计算0-500亿的和,普通For用时13745毫秒,Fork/Join框架用时8846毫秒,而且还有拆装箱的时间,足以看出Fork/Join框架的优势。

 1import java.time.Duration;
 2import java.time.Instant;
 3import java.util.concurrent.ForkJoinPool;
 4import java.util.concurrent.ForkJoinTask;
 5import java.util.concurrent.RecursiveTask;
 6
 7public class TestForkJoinPool {
 8    public static void main(String[] args) {
 9        Instant start = Instant.now();
10        ForkJoinPool forkJoinPool = new ForkJoinPool();
11        ForkJoinTask<Long> task = new ForkJoinSunCalculate(0L, 50000000000L);
12        Long invoke = forkJoinPool.invoke(task);
13        System.out.println(invoke);
14        Instant end = Instant.now();
15        System.out.println(Duration.between(start, end).toMillis()); //8846
16    }
17
18    public static void main(String[] args) {
19        Instant start = Instant.now();
20        long sum = 0L;
21        for (long i = 0; i < 50000000000L; i++) {
22            sum += i;
23        }
24        System.out.println(sum);
25        Instant end = Instant.now();
26        System.out.println(Duration.between(start, end).toMillis()); //13745
27    }
28}
29
30class ForkJoinSunCalculate extends RecursiveTask<Long> {
31    private long start;
32    private long end;
33
34    //临界值
35    private static final long VALUE = 10000L;
36
37    public ForkJoinSunCalculate(long start, long end){
38        this.start = start;
39        this.end = end;
40    }
41
42    @Override
43    protected Long compute() {
44        long length = end - start;
45        if(length <= VALUE){
46            long sum = 0L;
47            for (long i = start; i <= end; i++) {
48                sum += i;
49            }
50            return sum;
51        }else{
52            long middle = (end - start) / 2 + start;
53            ForkJoinSunCalculate leftCalculate = new ForkJoinSunCalculate(start, middle);
54            leftCalculate.fork(); //进行拆分,同时压入线程队列
55
56            ForkJoinSunCalculate rightCalculate = new ForkJoinSunCalculate(middle + 1, end);
57            rightCalculate.fork();//进行拆分,同时压入线程队列
58
59            return leftCalculate.join() + rightCalculate.join();
60        }
61    }
62}

用JDK8的特性stream谁快呢?

 1import java.time.Duration;
 2import java.time.Instant;
 3import java.util.concurrent.ForkJoinPool;
 4import java.util.concurrent.ForkJoinTask;
 5import java.util.concurrent.RecursiveTask;
 6import java.util.stream.LongStream;
 7
 8public class TestForkJoinPool {
 9    public static void main(String[] args) {
10        Instant start = Instant.now();
11        long sum = LongStream.rangeClosed(0L, 50000000000L)
12                .parallel()
13                .reduce(0L, Long::sum);
14        System.out.println(sum);
15        Instant end = Instant.now();
16        System.out.println(Duration.between(start, end).toMillis()); //5156
17    }
18}

其实这简单的计算还是stream更快,底层优化太多了。

ReadWriteLock

ReadWriteLock维护了一对相关的锁,一个用于只读操作,另一个用于写入操作。只要没有writer,读取锁可以由多个reader线程同时保持,写入锁是独占的。

ReadWriteLock读取操作通常不会改变共享资源,但执行写入操作时,必须独占方式来获取锁。对于读取操作占多数的数据结构。ReadWriteLock 能提供比独占锁更高的并发性。而对于只读的数据结构,其中包含的不变性可以完全不需要考虑加锁操作。

 1package thread_study;
 2
 3import java.util.concurrent.locks.ReadWriteLock;
 4import java.util.concurrent.locks.ReentrantReadWriteLock;
 5
 6//读写锁
 7public class TestReadWriteLock {
 8    public static void main(String[] args) {
 9        ReadWriteLockDemo writeLockDemo = new ReadWriteLockDemo();
10        new Thread(()->{
11            for (int i = 0; i < 30; i++) {
12                writeLockDemo.set(i);
13            }
14        }, "Write Thread").start();
15        for (int i = 0; i < 20; i++) {
16            new Thread(writeLockDemo::get, "Read Thread").start();
17        }
18    }
19}
20
21class ReadWriteLockDemo{
22    private int number = 0;
23    private ReadWriteLock lock = new ReentrantReadWriteLock();
24
25    public void get(){
26        lock.readLock().lock();
27        try{
28            System.out.println(Thread.currentThread().getName() + " : " + number);
29        }finally {
30            lock.readLock().unlock();
31        }
32    }
33
34    public void set(int number){
35        lock.writeLock().lock();
36        try{
37            System.out.println(Thread.currentThread().getName());
38            this.number = number;
39        }finally {
40            lock.writeLock().unlock();
41        }
42    }
43}