2016-01-22 66 views
2

嘗試從修補程序段中讀取多線程時,出現非常奇怪的行爲。我有以下情況:從修補程序段中讀取多線程

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)) 
     } 
    } 
} 

上面的代碼工作時,它完全是單線程,但一旦我公司推出的線程池我得到一個奇怪的各種各樣的錯誤。包括:

  1. 頂點屬性"type"不存在。
  2. java.lang.IndexOutOfBoundsException: Index: 0, Size: -1當試圖訪問某些頂點屬性。
  3. 驗證規則最初通過時失敗。

從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(同樣適用於泰坦支持交易)的回報從圖形中讀取時結果不一致。

+0

您的代碼片段沒有清楚說明您的交易界限在哪裏,特別是在您提交交易的地方。你能否添加信息? – Ralf

+0

TinkerGraph不支持事務。雖然TinkerGraph沒有正式的「線程安全」,但我感到半驚訝的是,您會發現TinkerGraph的這些問題與您使用它的方式有關。我認爲更多的信息是必需的,正如傑森所暗示的。 –

+0

我編輯了我的示例。我應該強調,在不同線程中讀取圖表時會出現這些問題。我甚至都沒有看到'commit'語句。 –

回答

0

試試看。更換

String prop = vertex.property("type"); 

與此

String type = vertex.value("type"); 

前者返回一個VertexProperty而後者返回VertexProperty,這是我認爲你正在尋找的value

至於你的#2和#3子彈,你需要提供更多的細節。

+0

該更改無法解決問題。一切工作都是單線程的,但是當我添加線程池時,就會出現這些問題。 –