java - using an in-memory orientdb in a multithreaded application -


I am trying to use an overindex in-memory instance in a multi-threaded app. I have seen many code examples but none of these cover this matter. Here is my test code:

DbTest.java

  public class DbTest {public static zero main (string [] args) {ODatabaseDocumentTx db = New ODatabaseDocumentTx ("Memory: MyDb "). Creation (); Runnable myRunnable = New MyRunnable (DB); Thread thread = new thread (myRunnable); Thread.start (); }}  

MyRunnable.java

  The public class applies MyRunnable Runnable {Private ODatabaseDocumentTx db; MyRunnable (ODatabaseDocumentTx DB) {this.db = db; } Run Public Nil () {ODocument Animal = New ODocument ("Animals"); Animal.field ("name", "gaudy"); Animal.field ("Place", "Madrid"); Animal.save (); }}  

returns this error

Exception in the thread "Thread 3" com.orientechnologies.orient.core.exception.odatabaseException: database example Assign to set it not in the current thread: ODatabaseRecordThreadLocal.INSTANCE.set (db);

I have read that I should try to use the connection pool, but connection pool does not seem to work with memory database

  ODatabaseDocumentTx Db = ODatabaseDocumentPool.global (). Acquisition ("Memory: MyDb", "Administrator", "Admin"); Exception in thread "main" com.orientechnologies.orient.core.exception.OStorageException: Local storage can not open with 'MyDb' mode = RW   
>

Any idea how really should work?

A ODatabaseDocumentPool example is thread-safe and can be used again A ODatabaseDocumentTx is not thread-safe and should be used by only one thread, the OrientDB API is somewhat ugly, memory database should be created first, it is not possible to use the default API. However, when using memory databases, there is no point in pooling.

So, in your example, the most effective way to do this is:

  Public class OrientTest {MyLayer class runs MyNurn Runnable {@Override Public Zero Run} { // If using Java7 +, try with resources! (ODatabaseDocumentTx tx = getDatabase ("memory: test", "admin", "admin")) {ODocument animal = tx.New instance ("animal") .field ("name", "goudi") .field ("location "," Madrid "); Tx.save (animal); }} Private ODatabaseDocumentTx getDatabase (string url, string username, string password) {ODatabaseDocumentTx tx = new ODatabaseDocumentTx (url); // Database is not open yet! If (! Tx.exists ()) {// This will create and open database! // default credentials are "admin" / "admin" tx.create (); Return tx; } Return tx.open (username, password); }} Public static zero main (string [] args) {New thread (New MyRunnable) Start (); }}  

Comments