I built a web service with spring boot. I used titan graph as a singleton that accessed across web service. So in case multiple requests to web service, web server will spawn threads to handle requests and titan graph will be used in these threads. Are there any problems with this approach? I using titan graph 1.0.0 and tinkerpop 3.0.1-incubating. So titan graph is quite new to me, and i don't know if any conflicts using titan graph in multi threads. If this approach has problem, so what is best practice to use titan graph in multi threads? Thank for your helps.
2 Answers
Yes, go for it. If you are using Titan, be sure to read the documentation available on multi-threaded transactions.
With Blueprints' default transaction handling, each thread automatically opens its own transaction against the graph database. To open a thread-independent transaction, use the
newTransaction()
method. ThenewTransaction()
method returns a newTransactionalGraph
object that represents this newly opened transaction. The graph object tx supports all of the methods that the original graph did, but does so without opening new transactions for each thread. This allows us to start multiple threads which all work concurrently in the same transaction and one of which finally commits the transaction when all threads have completed their work.
This is likely to be safer if you are using libraries which might carry a single conceptual transaction across multiple threads, e.g. through the use of deferreds or promises.
It is perfectly acceptable to use Titan in that manner. You just need to be sure that transactions don't leak between requests. As per TinkerPop semantics, transactions on the Graph
instance are bound to the current thread. Therefore, the end of every HTTP request needs to close the transaction with commit()
or rollback()
depending on the success or failure of the request. If you are even slightly unsure about your ability to always close a transaction, then you should consider issuing a rollback()
at the start of your request to clean up any stale state from a previous one.