Reputation: 475
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();
}}
In the above program, Two concurrent threads are trying to update the value..from “F” to “B” for the same RequestId=203
.
It seems like both threads are getting the status value as “F” and updating it to B.
But I want only one thread should change the value from “F” to “B”. After updating the value , I have used commit() also to save the changes.
If any thread changed the status from “(F)ree” to “(B)usy”..and other thread should see the changed value..(“B”).
Kindly help me to resolve this.
Upvotes: 0
Views: 135
Reputation: 3565
You could use a mutex or a synchronized()
block to ensure only one thread can perform that operation at any given time. Something like the following may work:
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();
So the above block synchronized(titanGraph)
is basically stating that for whatever is inside that block it can only executed by a thread that has the lock on the object within the brackets. In this case the titanGraph
. If a thread does not have the lock then it waits for the lock to become available.
Here is a really nice tutorial on using synchronized
Upvotes: 2