構建輕量、無鎖、無隊列/消息/事件概念的線程間通訊框架,僅用普通 Java 接口實現 POJO 通訊。初期用動態代理 + 阻塞隊列 + 緩存線程池,但性能遠遜單線程(5000 倍差距)。
stationIndex.get() % stationCount == myStation 即到站。
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列車,容量32K | 767M | — |
| SPSC | 2列車,容量1 | 1.07B | 133.5 |
| SPSC | 32K列車,容量1 | 1.57B | 1.3μs |
| SPMC(1生產7消費) | 32列車,容量256 | 432M | 592.5 |
| MPSC(3生產1消費) | 多列車輪流裝貨 | 162M | 18.5 |
對比:同場景 Disruptor 最好 128M,LinkedBlockingQueue 僅 4.5M。Railway 超越 Disruptor 1.2x~12x,逼近單線程極限(2.68B)。