2017-03-23 86 views
0
public class a { 
    private static TitanGraph titanGraph = null; 
    static GraphTraversalSource traversalSource = null; 
public static void main(String a[]) 
{ 
    titanGraph = TitanFunctions.getTitanGraph(); 
    traversalSource = titanGraph.traversal(); 
    // Task to be executed by each thread 
    Runnable r = new Runnable() { 
     public void run() { 

      long ab = traversalSource.V().has("RequestJob", "RequestId", 203) 
        .has("JobLockStatus","F") 
        .property("JobLockStatus", "B").count().next(); 
      titanGraph.tx().commit(); 
      System.out.println("value: "+ab+" : " +Thread.currentThread().getName()); 
     } 
    }; 
    Thread t1 = new Thread(r, "T1"); 
    Thread t2 = new Thread(r, "T2"); 
    t1.start(); 
    t2.start(); 
    }} 

在上面的程序併發更新,兩個併發線程試圖在value..from 「F」更新到「B」爲同一RequestId=203
看起來好像兩個線程的狀態值都是「F」並將其更新爲B。 但我想只有一個線程應該將值從「F」更改爲「B」。更新值後,我也使用commit()來保存更改。
如果任何線程將狀態從「(F)ree」更改爲「(B)usy」..並且其他線程應該看到更改後的值..(「B」)。
請幫我解決這個問題。問題與泰坦圖形數據庫

回答

2

您可以使用互斥鎖或synchronized()塊來確保在任何給定時間只有一個線程可以執行該操作。像下面的內容可能工作:

titanGraph = TitanFunctions.getTitanGraph(); 
traversalSource = titanGraph.traversal(); 
Runnable r = new Runnable() { 
    public void run() { 
     synchronized(titanGraph){ 
      long ab = traversalSource.V().has("RequestJob", "RequestId", 203) 
       .has("JobLockStatus","F") 
       .property("JobLockStatus", "B").count().next(); 
      titanGraph.tx().commit(); 
     }  
    } 
}; 
Thread t1 = new Thread(r, "T1"); 
Thread t2 = new Thread(r, "T2"); 
t1.start(); 
t2.start(); 

所以上面的塊synchronized(titanGraph)基本上闡明,不管什麼是塊它只能由具有括號內的對象上的鎖的線程執行中。在這種情況下titanGraph。如果線程沒有鎖定,則等待鎖定變爲可用。

Here是使用​​

+0

@ Filipe..It一個非常好的教程working..thank u爲鏈接,並解釋....多了一個疑問是..如果跨節點運行的進程..並且不止一個流程嘗試改變狀態。只有一個流程會改變'joblockstatus'。我怎樣才能做到這一點?請幫助我。檢查Titan數據庫中的'ConsistencyModifier.Lock' ..但它不工作.. – User12345

+0

只要上面的代碼運行在單個JVM(它會),泰坦將處理最終的一致性本身。如[指定](http://s3.thinkaurelius.com/docs/titan/1.0.0/eventual-consistency.html)所指定的'ConsistencyModifier.Lock'是有用的,如果你想更確定你的唯一性約束。它減慢了提交速度,但確保了唯一的索引。 –