Multi-Threading

OrientDB supports multi-threads access to the database. ODatabase* and OrientGraph* instances are not thread-safe, so you’ve to get an instance per thread and each database instance can be used only in one thread per time. For more information about how concurrency is managed by OrientDB look at Concurrency.

Multi-Threading - 图1 Since v2.1 OrientDB doesn’t allow implicit usage of multiple database instances from the same thread. Any attempt to manage multiple instances in the same thread must explicitly call the method db.activateOnCurrentThread() against the database instance BEFORE you use it.

Multiple database instances point to the same storage by using the same URL. In this case Storage is thread-safe and orchestrates requests from different ODatabase* instances.

  1. ODatabaseDocumentTx-1------+
  2. +----> OStorage (url=plocal:/temp/db)
  3. ODatabaseDocumentTx-2------+

The same as for Graph API:

  1. OrientGraph-1------+
  2. +----> OStorage (url=plocal:/temp/db)
  3. OrientGraph-2------+

Database instances share the following objects:

  • schema
  • index manager
  • security

These objects are synchronized for concurrent contexts by storing the current database in the ThreadLocal variable. Every time you create, open or acquire a database connection, the database instance is automatically set into the current ThreadLocal space, so in normal use this is hidden from the developer.

The current database is always reset for all common operations like load, save, etc.

Example of using two database in the same thread:

  1. ODocument rec1 = database1.newInstance();
  2. ODocument rec2 = database2.newInstance();
  3. rec1.field("name", "Luca");
  4. database1.activateOnCurrentThread(); // MANDATORY SINCE 2.1
  5. database1.save(rec1); // force saving in database1 no matter where the record came from
  6. rec2.field("name", "Luke");
  7. database2.activateOnCurrentThread(); // MANDATORY SINCE 2.1
  8. database2.save(rec2); // force saving in database2 no matter where the record came from

In version 2.0.x, method activateOnCurrentThread() does not exist, you can use setCurrentDatabaseInThreadLocal() instead.

Get current database

To get the current database from the ThreadLocal use:

  1. ODatabaseDocument database = (ODatabaseDocument) ODatabaseRecordThreadLocal.INSTANCE.get();

Manual control

Beware when you reuse database instances from different threads or then a thread handle multiple databases. In this case you can override the current database by calling this manually:

  1. database.activateOnCurrentThread(); //v 2.1
  2. // for OrientDB v. 2.0.x: database.setCurrentDatabaseInThreadLocal();

Where database is the current database instance. Example:

  1. database1.activateOnCurrentThread();
  2. ODocument rec1 = database1.newInstance();
  3. rec1.field("name", "Luca");
  4. rec1.save();
  5. database2.activateOnCurrentThread();
  6. ODocument rec2 = database2.newInstance();
  7. rec2.field("name", "Luke");
  8. rec2.save();

Custom database factory

Since v1.2 Orient provides an interface to manage custom database management in MultiThreading cases:

  1. public interface ODatabaseThreadLocalFactory {
  2. public ODatabaseRecord getThreadDatabase();
  3. }

Examples:

  1. public class MyCustomRecordFactory implements ODatabaseThreadLocalFactory {
  2. public ODatabaseRecord getDb(){
  3. return ODatabaseDocumentPool.global().acquire(url, "admin", "admin");
  4. }
  5. }
  6. public class MyCustomObjectFactory implements ODatabaseThreadLocalFactory {
  7. public ODatabaseRecord getThreadDatabase(){
  8. return OObjectDatabasePool.global().acquire(url, "admin", "admin").getUnderlying().getUnderlying();
  9. }
  10. }

Registering the factory:

  1. ODatabaseThreadLocalFactory customFactory = new MyCustomRecordFactory();
  2. Orient.instance().registerThreadDatabaseFactory(customFactory);

When a database is not found in current thread it will be called the factory getDb() to retrieve the database instance.

Close a database

What happens if you are working with two databases and close just one? The Thread Local isn’t a stack, so you loose the previous database in use. Example:

  1. ODatabaseDocumentTx db1 = new ODatabaseDocumentTx("local:/temo/db1").create();
  2. ODatabaseDocumentTx db2 = new ODatabaseDocumentTx("local:/temo/db2").create();
  3. ...
  4. db2.close();
  5. // NOW NO DATABASE IS SET IN THREAD LOCAL. TO WORK WITH DB1 SET IT IN THE THREAD LOCAL
  6. db1.activateOnCurrentThread();
  7. ...

Multi Version Concurrency Control

If two threads update the same record, then the last one receive the following exception: “OConcurrentModificationException: Cannot update record #X:Y in storage ‘Z’ because the version is not the latest. Probably you are updating an old record or it has been modified by another user (db=vA your=vB)”

This is because every time you update a record, the version is incremented by 1. So the second update fails checking the current record version in database is higher than the version contained in the record to update.

This is an example of code to manage the concurrency properly:

Graph API

  1. for( int retry = 0; retry < maxRetries; ++retry ) {
  2. try{
  3. // APPLY CHANGES
  4. vertex.setProperty( "name", "Luca" );
  5. vertex.addEdge( "Buy", product );
  6. break;
  7. } catch( ONeedRetryException e ) {
  8. // RELOAD IT TO GET LAST VERSION
  9. vertex.reload();
  10. product.reload();
  11. }
  12. }

Document API

  1. for( int retry = 0; retry < maxRetries; ++retry ) {
  2. try{
  3. // APPLY CHANGES
  4. document.field( "name", "Luca" );
  5. document.save();
  6. break;
  7. } catch( ONeedRetryException e ) {
  8. // RELOAD IT TO GET LAST VERSION
  9. document.reload();
  10. }
  11. }

The same in transactions:

  1. for( int retry = 0; retry < maxRetries; ++retry ) {
  2. db.begin();
  3. try{
  4. // CREATE A NEW ITEM
  5. ODocument invoiceItem = new ODocument("InvoiceItem");
  6. invoiceItem.field( "price", 213231 );
  7. invoiceItem.save();
  8. // ADD IT TO THE INVOICE
  9. Collection<ODocument> items = invoice.field( items );
  10. items.add( invoiceItem );
  11. invoice.save();
  12. db.commit();
  13. break;
  14. } catch( OTransactionException e ) {
  15. // RELOAD IT TO GET LAST VERSION
  16. invoice.reload();
  17. }
  18. }

Where maxRetries is the maximum number of attempt of reloading.

What about running transaction?

Transactions are bound to a database, so if you change the current database while a tx is running, the deleted and saved objects remain attached to the original database transaction. When it commits, the objects are committed.

Example:

  1. ODatabaseDocumentTx db1 = new ODatabaseDocumentTx("local:/temo/db1").create();
  2. db1.begin();
  3. ODocument doc1 = new ODocument("Customer");
  4. doc1.field("name", "Luca");
  5. doc1.save(); // NOW IT'S BOUND TO DB1'S TX
  6. ODatabaseDocumentTx db2 = new ODatabaseDocumentTx("local:/temo/db2").create(); // THE CURRENT DB NOW IS DB2
  7. ODocument doc2 = new ODocument("Provider");
  8. doc2.field("name", "Chuck");
  9. doc2.save(); // THIS IS BOUND TO DB2 BECAUSE IT'S THE CURRENT ONE
  10. db1.activateOnCurrentThread();
  11. db1.commit(); // WILL COMMIT DOC1 ONLY