日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網(wǎng)為廣大站長提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請做好本站友鏈:【 網(wǎng)站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會(huì)員:747

JAVA8 parallelStream并發(fā)安全

背景

Java8的stream接口極大地減少了for循環(huán)寫法的復(fù)雜性,stream提供了map/reduce/collect等一系列聚合接口,還支持并發(fā)操作:parallelStream。

在爬蟲開發(fā)過程中,經(jīng)常會(huì)遇到遍歷一個(gè)很大的集合做重復(fù)的操作,這時(shí)候如果使用串行執(zhí)行會(huì)相當(dāng)耗時(shí),因此一般會(huì)采用多線程來提速。Java8的paralleStream用fork/join框架提供了并發(fā)執(zhí)行能力。但是如果使用不當(dāng),很容易陷入誤區(qū)。

Java8的paralleStream是線程安全的嗎

一個(gè)簡單的例子,在下面的代碼中采用stream的forEach接口對1-10000進(jìn)行遍歷,分別插入到3個(gè)ArrayList中。其中對第一個(gè)list的插入采用串行遍歷,第二個(gè)使用paralleStream,第三個(gè)使用paralleStream的同時(shí)用ReentryLock對插入列表操作進(jìn)行同步:

private static List<Integer> list1 = new ArrayList<>();
private static List<Integer> list2 = new ArrayList<>();
private static List<Integer> list3 = new ArrayList<>();
private static Lock lock = new ReentrantLock();

public static void main(String[] args) {
 IntStream.range(0, 10000).forEach(list1::add);

 IntStream.range(0, 10000).parallel().forEach(list2::add);

 IntStream.range(0, 10000).forEach(i -> {
 lock.lock();
 try {
  list3.add(i);
 }finally {
  lock.unlock();
 }
 });

 System.out.println("串行執(zhí)行的大?。?quot; + list1.size());
 System.out.println("并行執(zhí)行的大?。?quot; + list2.size());
 System.out.println("加鎖并行執(zhí)行的大?。?quot; + list3.size());
}

執(zhí)行結(jié)果:

串行執(zhí)行的大小:10000并行執(zhí)行的大?。?595加鎖并行執(zhí)行的大?。?0000

并且每次的結(jié)果中并行執(zhí)行的大小不一致,而串行和加鎖后的結(jié)果一直都是正確結(jié)果。顯而易見,stream.parallel.forEach()中執(zhí)行的操作并非線程安全。

那么既然paralleStream不是線程安全的,是不是在其中的進(jìn)行的非原子操作都要加鎖呢?我在stackOverflow上找到了答案:

  • https://codereview.stackexchange.com/questions/60401/using-java-8-parallel-streams
  • https://stackoverflow.com/questions/22350288/parallel-streams-collectors-and-thread-safety

在上面兩個(gè)問題的解答中,證實(shí)paralleStream的forEach接口確實(shí)不能保證同步,同時(shí)也提出了解決方案:使用collect和reduce接口。

  • http://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html

在Javadoc中也對stream的并發(fā)操作進(jìn)行了相關(guān)介紹:

The Collections Framework provides synchronization wrAppers, which add automatic synchronization to an arbitrary collection, making it thread-safe.

Collections框架提供了同步的包裝,使得其中的操作線程安全。

所以下一步,來看看collect接口如何使用。

stream的collect接口

閑話不多說直接上源碼吧,Stream.java中的collect方法句柄:

<R, A> R collect(Collector<? super T, A, R> collector);

在該實(shí)現(xiàn)方法中,參數(shù)是一個(gè)Collector對象,可以使用Collectors類的靜態(tài)方法構(gòu)造Collector對象,比如Collectors.toList(),toSet(),toMap(),etc,這塊很容易查到API故不細(xì)說了。

除此之外,我們?nèi)绻赾ollect接口中做更多的事,就需要自定義實(shí)現(xiàn)Collector接口,需要實(shí)現(xiàn)以下方法:

Supplier<A> supplier();
BiConsumer<A, T> accumulator();
BinaryOperator<A> combiner();
Function<A, R> finisher();
Set<Characteristics> characteristics();

要輕松理解這三個(gè)參數(shù),要先知道fork/join是怎么運(yùn)轉(zhuǎn)的,一圖以蔽之:

嗯,不錯(cuò)通俗易懂的講解Java8 ParallelStream并發(fā)安全原理

 

上圖來自:http://www.infoq.com/cn/articles/fork-join-introduction

簡單地說就是大任務(wù)拆分成小任務(wù),分別用不同線程去完成,然后把結(jié)果合并后返回。所以第一步是拆分,第二步是分開運(yùn)算,第三步是合并。這三個(gè)步驟分別對應(yīng)的就是Collector的supplier,accumulator和combiner。talk is cheap show me the code,下面用一個(gè)例子來說明:

輸入是一個(gè)10個(gè)整型數(shù)字的ArrayList,通過計(jì)算轉(zhuǎn)換成double類型的Set,首先定義一個(gè)計(jì)算組件:

Compute.java:

public class Compute {
public Double compute(int num) {
 return (double) (2 * num);
}
}

接下來在Main.java中定義輸入的類型為ArrayList的nums和類型為Set的輸出結(jié)果result:

private List<Integer> nums = new ArrayList<>();
private Set<Double> result = new HashSet<>();

定義轉(zhuǎn)換list的run方法,實(shí)現(xiàn)Collector接口,調(diào)用內(nèi)部類Container中的方法,其中characteristics()方法返回空set即可:

public void run() {
 // 填充原始數(shù)據(jù),nums中填充0-9 10個(gè)數(shù)
 IntStream.range(0, 10).forEach(nums::add);
 //實(shí)現(xiàn)Collector接口
 result = nums.stream().parallel().collect(new Collector<Integer, Container, Set<Double>>() {

 @Override
 public Supplier<Container> supplier() {
  return Container::new;
 }

 @Override
 public BiConsumer<Container, Integer> accumulator() {
  return Container::accumulate;
 }

 @Override
 public BinaryOperator<Container> combiner() {
  return Container::combine;
 }

 @Override
 public Function<Container, Set<Double>> finisher() {
  return Container::getResult;
 }

 @Override
 public Set<Characteristics> characteristics() {
  // 固定寫法
  return Collections.emptySet();
 }
 });
}

構(gòu)造內(nèi)部類Container,該類的作用是一個(gè)存放輸入的容器,定義了三個(gè)方法:

  • accumulate方法對輸入數(shù)據(jù)進(jìn)行處理并存入本地的結(jié)果
  • combine方法將其他容器的結(jié)果合并到本地的結(jié)果中
  • getResult方法返回本地的結(jié)果

Container.java:

class Container {
 // 定義本地的result
 public Set<Double> set;

 public Container() {
 this.set = new HashSet<>();
 }

 public Container accumulate(int num) {
 this.set.add(compute.compute(num));
 return this;
 }

 public Container combine(Container container) {
 this.set.addAll(container.set);
 return this;
 }

 public Set<Double> getResult() {
 return this.set;
 }
}

在Main.java中編寫測試方法:

public static void main(String[] args) {
 Main main = new Main();
 main.run();
 System.out.println("原始數(shù)據(jù):");
 main.nums.forEach(i -> System.out.print(i + " "));
 System.out.println("nncollect方法加工后的數(shù)據(jù):");
 main.result.forEach(i -> System.out.print(i + " "));
}

輸出:

原始數(shù)據(jù):0 1 2 3 4 5 6 7 8 9

collect方法加工后的數(shù)據(jù):0.0 2.0 4.0 8.0 16.0 18.0 10.0 6.0 12.0 14.0

我們將10個(gè)整型數(shù)值的list轉(zhuǎn)成了10個(gè)double類型的set,至此驗(yàn)證成功~

本程序參考 http://blog.csdn.net/io_field/article/details/54971555。

一言蔽之

總結(jié)就是paralleStream里直接去修改變量是非線程安全的,但是采用collect和reduce操作就是滿足線程安全的了。

java8中parallelStream性能測試及結(jié)果分析

測試1

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 20, time = 3, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class StreamBenchTest {
  List<String> data = new ArrayList<>();
  @Setup
  public void init() {
    // prepare
    for(int i=0;i<100;i++){
      data.add(UUID.randomUUID().toString());
    }
  }
  @TearDown
  public void destory() {
    // destory
  }
  @Benchmark
  public void benchStream(){
    data.stream().forEach(e -> {
      e.getBytes();
      try {
        Thread.sleep(10);
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
    });
  }
  @Benchmark
  public void benchParallelStream(){
    data.parallelStream().forEach(e -> {
      e.getBytes();
      try {
        Thread.sleep(10);
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
    });
  }
  public static void main(String[] args) throws RunnerException {
    Options opt = new OptionsBuilder()
        .include(".*" +StreamBenchTest.class.getSimpleName()+ ".*")
        .forks(1)
        .build();
    new Runner(opt).run();
  }
}

parallelStream線程數(shù)

默認(rèn)是Runtime.getRuntime().availableProcessors() - 1,這里為7

運(yùn)行結(jié)果

# Run complete. Total time: 00:02:44
Benchmark              Mode Cnt      Score     Error Units
StreamBenchTest.benchParallelStream avgt  20  155868805.437 ± 1509175.840 ns/op
StreamBenchTest.benchStream     avgt  20 1147570372.950 ± 6138494.414 ns/op

測試2

將數(shù)據(jù)data改為30,同時(shí)sleep改為100

Benchmark              Mode Cnt      Score     Error Units
StreamBenchTest.benchParallelStream avgt  20  414230854.631 ± 725294.455 ns/op
StreamBenchTest.benchStream     avgt  20 3107250608.500 ± 4805037.628 ns/op

可以發(fā)現(xiàn)sleep越長,parallelStream優(yōu)勢越明顯。

小結(jié)

parallelStream在阻塞場景下優(yōu)勢更明顯,其線程池個(gè)數(shù)默認(rèn)為Runtime.getRuntime().availableProcessors() - 1,如果需修改則需設(shè)置-Djava.util.concurrent.ForkJoinPool.common.parallelism=8

以上就是本次講述知識(shí)點(diǎn)的全部內(nèi)容,感謝你對碼農(nóng)之家的支持。

以上就是本次給大家分享的關(guān)于java的全部知識(shí)點(diǎn)內(nèi)容總結(jié),感謝大家的閱讀和支持。

分享到:
標(biāo)簽:Java8 ParallelStream
用戶無頭像

網(wǎng)友整理

注冊時(shí)間:

網(wǎng)站:5 個(gè)   小程序:0 個(gè)  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會(huì)員

趕快注冊賬號(hào),推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運(yùn)動(dòng)步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動(dòng)步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績評定2018-06-03

通用課目體育訓(xùn)練成績評定