我並不熟悉問題的具體細節,但聽起來很像流水線CPU中的data hazards。
在您的情況下,您希望在不引入數據危險的情況下最大限度地利用您的功能單元(流)。也許你可以編寫一個簡單的調度程序,查看下n個指令,並將它們安排到流中?
/**
* Keeps track of which stream is scheduled to process each account.
* If an account is not currently scheduled to be processed, it doesn't appear in the keySet of this map.
*/
Map<Account, Stream> accountsInFlight; // use a synchronized implementation
void schedule(Instruction instruction) {
// If the input account is in flight somewhere, use that stream
if (accountsInFlight.containsKey(instruction.getInAccount())) {
scheduleToStream(instruction, accountsInFlight.get(instruction.getInAccount()));
// If the output account is in flight somewhere, use that stream
} else if (accountsInFlight.containsKey(instruction.getOutAccount())) {
scheduleToStream(instruction, accountsInFlight.get(instruction.getOutAccount()));
// If neither are in flight, this is a good candidate for parallel execution,
// put it in a different stream
} else {
Stream stream = // pick a stream (maybe the one with the shortest queue?)
scheduleToStream(instruction, stream);
}
}
private void scheduleToStream(Instruction instruction, Stream stream) {
stream.addToQueue(instruction);
// Update accountsInFlight
accountsInFlight.put(instruction.getInAccount(), stream);
accountsInFlight.put(instruction.getOutAccount(), stream);
}
// Remove accounts from the map when the instruction completes
注意,這全是假的代碼:它不是最優化,也沒有正確地涵蓋所有情況,但也許它會給你一些想法開始。