我尝试并行创建多个顶点:
public static void main(String[] args) throws InterruptedException {
//create db and seq
ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:/TestDB");
db.create();
OSequenceLibrary seqLib = db.getMetadata().getSequenceLibrary();
seqLib.createSequence("testSeq",
OSequence.SEQUENCE_TYPE.ORDERED,
new OSequence.CreateParams().setStart(0L).setIncrement(1)
);
OrientGraphFactory factory = new OrientGraphFactory("memory:/TestDB", "admin", "admin").setupPool(1, 8);
//mt
Executor executor = Executors.newFixedThreadPool(8);
CountDownLatch latch = new CountDownLatch(1000);
for (int i = 1; i <= 1000; i++) {
executor.execute(() -> {
OrientGraph g = factory.getTx();
try {
OSequence seq = g.getRawGraph().getMetadata().getSequenceLibrary().getSequence("testSeq");
OrientVertex v = g.addVertex("TestClass");
v.setProperty("seq", seq.next());
latch.countDown();
} finally {
g.shutdown();
}
});
}
latch.await(5, TimeUnit.SECONDS);
System.exit(0);
}
并收到很多例外:
com.orientechnologies.orient.core.exception.OConcurrentModificationException: 无法更新记录#7:0因为版本不是最新版本。 您可能正在更新旧记录或已被修改过 另一个用户(db = v2 your = v1)
如何在mt环境中正确使用序列?
答案 0 :(得分:2)
OrientDB完全基于乐观的方法,没有锁定或锁定很少。因此,您应该捕获异常并重试。例如:
OrientGraph g = factory.getTx();
try {
for( int retry = 0; retry < 100; ++retry ){
try {
OSequence seq = g.getRawGraph().getMetadata().getSequenceLibrary().getSequence("testSeq");
OrientVertex v = g.addVertex("TestClass");
v.setProperty("seq", seq.next());
latch.countDown();
break;
} catch( ONeedRetryException e ) {
}
}
} finally {
g.shutdown();
}