首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 線程間通訊:無鎖 Railway 算法超越 Disruptor 的極致性能探索

     編輯:Java 相關知識

背景與目標

構建輕量、無鎖、無隊列/消息/事件概念的線程間通訊框架,僅用普通 Java 接口實現 POJO 通訊。初期用動態代理 + 阻塞隊列 + 緩存線程池,但性能遠遜單線程(5000 倍差距)。

演進路線

  1. 阻塞隊列:吞吐量 ~8M ops/sec(4 核 i7),成瓶頸。
  2. SPSC 無鎖隊列(Nitsan Wakart / Martin Thompson 設計):單生產單消費 ~100M ops/sec,但多生產者(MPSC)場景無解。
  3. LMAX Disruptor:環形緩衝區,3 生產 1 消費 ~11M ops/sec(批量 ~128M),仍有提升空間。
  4. Railway 算法(鐵路模型):終極方案,靈感源自地鐵站台發車。

Railway 核心模型

  • Train(列車):承載數據的固定容量數組(貨物艙)。
  • Station(車站):線程等待/裝卸貨的節點,每線程專屬一站。
  • AtomicInteger stationIndex:原子計數器追蹤列車當前站點,stationIndex.get() % stationCount == myStation 即到站。
  • 忙等待 + Thread.yield():線程在站點自旋等待列車到達,極低延遲。

關鍵代碼片段

public class RailWay {
    private final Train train = new Train();
    private final AtomicInteger stationIndex = new AtomicInteger();
    public Train waitTrainOnStation(int stationNo) {
        while (stationIndex.get() % stationCount != stationNo) Thread.yield();
        return train;
    }
    public void sendTrain() { stationIndex.getAndIncrement(); }
}
class Train {
    static final int CAPACITY = 2048; // 可調
    final long[] goodsArray = new long[CAPACITY];
    int index;
    void addGoods(long v) { goodsArray[index++] = v; }
    long getGoods(int i) { index--; return goodsArray[i]; }
}

性能數據震撼

場景配置吞吐量 (ops/sec)延遲 (ns)
SPSC(1生產1消費)1列車,容量32K767M—
SPSC2列車,容量11.07B133.5
SPSC32K列車,容量11.57B1.3μs
SPMC(1生產7消費)32列車,容量256432M592.5
MPSC(3生產1消費)多列車輪流裝貨162M18.5

對比:同場景 Disruptor 最好 128M,LinkedBlockingQueue 僅 4.5M。Railway 超越 Disruptor 1.2x~12x,逼近單線程極限(2.68B)。

擴展性

  • 增加車站支持任意生產者/消費者拓撲。
  • 同一線程可兼任生產與消費(混合模式)。
  • 通過調整列車數量與容量平衡吞吐量與延遲。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved