java1.8項(xiàng)目纖程實(shí)戰(zhàn)和性能壓測(cè)

新建一個(gè)maven依賴項(xiàng)目

pom.xml中引入纖程jar的坐標(biāo)依賴

<dependency>
   <groupId>co.paralleluniverse</groupId>
   <artifactId>quasar-core</artifactId>
   <version>0.7.4</version>
   <classifier>jdk8</classifier>
</dependency>
纖程使用示例

package com.example.demo.fiber;

import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.futures.AsyncCompletionStage;
import co.paralleluniverse.strands.Strand;
import co.paralleluniverse.strands.SuspendableRunnable;
import com.example.demo.fiber.tool.WorkTools;

import java.util.concurrent.CountDownLatch;

/**
 * 描述:纖程demo </br>
 * 作者:王林沖 </br>
 * 時(shí)間:2023/4/7 15:44
 */
public class Test {
    public static void main(String[] args) throws InterruptedException {
        fiberTest();
    }

    public static void fiberTest() throws InterruptedException {
        new Fiber(() -> {
            Strand.sleep(5000);
            System.out.println("纖程開(kāi)始執(zhí)行了");
        }).start();
        System.out.println("主線程執(zhí)行完畢");
    }

}

為了實(shí)現(xiàn)類似于線程池的功能,想在一個(gè)批量處理的過(guò)程中,開(kāi)多個(gè)纖程處理,在統(tǒng)一獲取結(jié)果,然后繼續(xù)主線程執(zhí)行,場(chǎng)景相當(dāng)多

自己實(shí)現(xiàn)個(gè)纖程池

package com.example.demo.fiber.tool;

import co.paralleluniverse.fibers.Fiber;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 描述:協(xié)程工作程池 </br>
 * 作者:王林沖 </br>
 * 時(shí)間:2023/4/7 17:33
 */
@Slf4j
public class FiberWorkPool {
    /**
     * 工作協(xié)程數(shù)組
     */
    private List<Fiber> workThreads;
    /**
     * 協(xié)程任務(wù)倒計(jì)數(shù)門栓
     */
    private CountDownLatch countDownLatch = new CountDownLatch(0);


    /**
     * 建立協(xié)程池,taskCount 為協(xié)程池中工做協(xié)程的個(gè)數(shù)
     * @param taskCount
     */
    public FiberWorkPool(int taskCount) {
        workThreads = new ArrayList<>(taskCount);
        countDownLatch = new CountDownLatch(taskCount);
    }

    /**
     * 任務(wù)加入任務(wù)隊(duì)列
     * @param task
     */
    public void execute(Fiber task) {
        try {
            workThreads.add(task);   //阻塞接口的Fiber work插入
        } catch (Exception e) {
            log.error("========> Fiber work add failed ..., msg : {}", e.getMessage());
        }
    }

    //銷毀協(xié)程池,該方法保證全部任務(wù)都完成的狀況下才銷毀全部協(xié)程,不然等待任務(wù)完成再銷毀
    public void shutdown() throws InterruptedException {
        start();
        countDownLatch.await();
        workThreads.clear();  //清空等待隊(duì)列
        log.debug("========> successfully closed FiberWorkPool ...");
    }

    /**
     * 啟動(dòng)協(xié)程池里所有的協(xié)程
     */
    public void start() {
        if (workThreads.size() != 0) {
            for (Fiber fiber : workThreads) {
                fiber.start();
            }
        }
    }

    /**
     * 獲取倒計(jì)數(shù)門栓
     *
     * @return
     */
    public CountDownLatch getCountDownLatch() {
        return this.countDownLatch;
    }


}

纖程池使用demo

package com.example.demo.fiber.tool;

import co.paralleluniverse.fibers.Fiber;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.*;

/**
 * 描述:協(xié)程池應(yīng)用demo </br>
 * 作者:王林沖 </br>
 * 時(shí)間:2023/4/10 17:17
 */
@Component
public class FiberWorkPoolAppDemo {

    public void fiber() throws InterruptedException {
        //開(kāi)啟5個(gè)協(xié)程,50個(gè)任務(wù)列隊(duì)。
        FiberWorkPool fiberWorkPool = new FiberWorkPool(50);
        for (int i = 0; i < 50; i++) {
            fiberWorkPool.execute(new Fiber(() -> {
                Fiber.sleep(50);
                //System.out.println("========= " + Fiber.currentFiber().getName() + " ============");
                fiberWorkPool.getCountDownLatch().countDown();
            }));
        }
        //等待協(xié)程任務(wù)完畢后再結(jié)束主線程
        fiberWorkPool.shutdown();
    }

    public void thread() throws ExecutionException, InterruptedException {
        List<Future<Void>> futures = Lists.newArrayList();
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        for (int i = 0; i < 50; i++) {
            futures.add(executorService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Thread.sleep(50);
                    return null;
                }
            }));
        }
        for (Future<Void> future : futures) {
            future.get();
        }
        executorService.shutdownNow();
    }


}

測(cè)試controller

package com.example.demo.fiber.tool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * 描述:協(xié)程controller </br>
 * 作者:王林沖 </br>
 * 時(shí)間:2023/4/10 17:20
 */
@RestController
@RequestMapping("/fiber")
public class FiberTestController {

    @Autowired
    private FiberWorkPoolAppDemo fiberWorkPoolAppDemo;

    /**
     * 協(xié)程測(cè)試
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @GetMapping("/fiberTest")
    public void fiberTest () throws InterruptedException, ExecutionException {
        Long start = System.currentTimeMillis();
        fiberWorkPoolAppDemo.fiber();
        System.out.println("=======> "+ (System.currentTimeMillis() - start) + "=======毫秒");
    }

    /**
     * 線程測(cè)試
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @GetMapping("/threadTest")
    public void threadTest () throws InterruptedException, ExecutionException {
        Long start = System.currentTimeMillis();
        fiberWorkPoolAppDemo.thread();
        System.out.println("=======> "+ (System.currentTimeMillis() - start) + "=======毫秒");
    }

}

jmeter壓測(cè)參數(shù)

238629bk-1.png

線程池壓測(cè)

238629bk-2.png

纖程池壓測(cè)

238629bk-3.png

差距一目了然,當(dāng)你的線程池,異步出現(xiàn)性能問(wèn)題時(shí),請(qǐng)考慮纖程,讓你的代碼性能數(shù)量級(jí)的提升,線程池之所以慢,是因?yàn)榇罅康木€程頻繁的上下文切換,和線程此中任務(wù)爭(zhēng)奪線程while循環(huán),耗cpu那是相當(dāng)多,纖程就避免了這個(gè)問(wèn)題。所以性能剛杠杠的



作者: IT學(xué)習(xí)道場(chǎng)


歡迎關(guān)注微信公眾號(hào) : IT學(xué)習(xí)道場(chǎng)