嘗試從修補程序段中讀取多線程時,出現非常奇怪的行爲。我有以下情況:從修補程序段中讀取多線程
Graph graph = TinkerGraph.open();
Set<Vertex> verticesAdded = randomGraph(graph);
verticesAdded
是一組我在randomGraph(graph)
過程中添加的頂點。一旦我有這個列表,我檢查這個頂點的內部屬性,並根據該屬性將頂點傳遞給線程進行一些額外的工作。我遵循的流程大致是:
public class ValidateVerticies(){
private Set<Vertex> vertices;
private ExecutorService executor;
public ValidateVerticies(Set<Vertex> verticesAdded){
vertices = verticesAdded;
executor = Executors.newSingleThreadExecutor(); //Single just for testing purposes
}
public validate(){
for(Vertex vertex: vertices){
String prop = vertex.property("type");
if(type.equals("1"))
executor.submit(() -> validateRule1(vertex))
else if(type.equals("2"))
executor.submit(() -> validateRule2(vertex))
else if(type.equals("n"))
executor.submit(() -> validateRule3(vertex))
...
else if(type.equals("n"))
executor.submit(() -> validateRulen(vertex))
}
}
}
上面的代碼工作時,它完全是單線程,但一旦我公司推出的線程池我得到一個奇怪的各種各樣的錯誤。包括:
- 頂點屬性
"type"
不存在。 java.lang.IndexOutOfBoundsException: Index: 0, Size: -1
當試圖訪問某些頂點屬性。- 驗證規則最初通過時失敗。
從tinkergraph中進行多線程讀取時是否存在一些微妙之處?
編輯:
我會盡量簡化問題: 以下工作:
public class ValidateVerticies(){
private Set<Vertex> vertices;
public ValidateVerticies(Set<Vertex> verticesAdded){
vertices = verticesAdded;
}
public validate(){
for(Vertex vertex: vertices){
String prop = vertex.property("type");
if(type.equals("1"))
validateRule1(vertex);
...
else if(type.equals("n"))
validateRulen(vertex);
}
}
}
雖然上面的多線程版本失敗TinkerGraph(同樣適用於泰坦支持交易)的回報從圖形中讀取時結果不一致。
您的代碼片段沒有清楚說明您的交易界限在哪裏,特別是在您提交交易的地方。你能否添加信息? – Ralf
TinkerGraph不支持事務。雖然TinkerGraph沒有正式的「線程安全」,但我感到半驚訝的是,您會發現TinkerGraph的這些問題與您使用它的方式有關。我認爲更多的信息是必需的,正如傑森所暗示的。 –
我編輯了我的示例。我應該強調,在不同線程中讀取圖表時會出現這些問題。我甚至都沒有看到'commit'語句。 –