java - using an in-memory orientdb in a multithreaded application -
i trying utilize orientdb in-memory instance in multi-threaded app. i've looked @ lots of code examples none of seem cover case. here's test code:
dbtest.java
public class dbtest { public static void main(string [] args) { odatabasedocumenttx db = new odatabasedocumenttx("memory:mydb").create(); runnable myrunnable = new myrunnable(db); thread thread = new thread(myrunnable); thread.start(); } }
myrunnable.java
public class myrunnable implements runnable { private odatabasedocumenttx db; myrunnable(odatabasedocumenttx db) { this.db = db; } public void run() { odocument animal = new odocument("animal"); animal.field( "name", "gaudi" ); animal.field( "location", "madrid" ); animal.save(); } }
this gives error
exception in thread "thread-3" com.orientechnologies.orient.core.exception.odatabaseexception: database instance not set in current thread. assure set with: odatabaserecordthreadlocal.instance.set(db);
i read should seek utilize connection pool, connection pool not seem work memory databases
odatabasedocumenttx db = odatabasedocumentpool.global().acquire("memory:mydb", "admin", "admin");
exception in thread "main" com.orientechnologies.orient.core.exception.ostorageexception: cannot open local storage 'mydb' mode=rw
any ideas how supposed work?
an odatabasedocumentpool
instance thread-safe , can reused. odatabasedocumenttx
not thread-safe , should used single thread. orientdb api little ugly here, memory database must created first not possible using default api. however, when using memory database, pooling not create sense.
so in example, efficient way is:
public class orienttest { static class myrunnable implements runnable { @override public void run() { // if using java7+, utilize try-with-resources! seek (odatabasedocumenttx tx = getdatabase("memory:test", "admin", "admin")) { odocument animal = tx.newinstance("animal") .field("name", "gaudi") .field("location", "madrid"); tx.save(animal); } } private odatabasedocumenttx getdatabase(string url, string username, string password) { odatabasedocumenttx tx = new odatabasedocumenttx(url); // database not open yet! if (!tx.exists()) { // create , open database! // default credentials "admin"/"admin" tx.create(); homecoming tx; } homecoming tx.open(username, password); } } public static void main(string[] args) { new thread(new myrunnable()).start(); } }
java multithreading orientdb in-memory-database
No comments:
Post a Comment