java - Multithreading with Embedded ObjectDB -


ObjectDB requires a nuclear counter but the following code does not work as I expected:

Previous> final EntityManagerFactory emf = Persistence.createEntityManagerFactory ("test.odb"); EntityManager em = emf.createEntityManager (); Point P = new point (0, 0); Em.getTransaction () start () .; em.persist (p); Committed to em.getTransaction (). Em.close (); Last counting l = new countdownload (100); (Int i = 0; i & lt; 100; i ++) {thread t = new thread (new runnable)} {@Override public runs zero ({{EntityManager em = emf.createEntityManager (); em.getTransaction ( ). Query query = em.createQuery ("UPDATE Point SET x = x + 1"); query.executeUpdate (); Em .getTransaction (). Commit (); em.close (); l.countDown ();}}); T.start (); } L.ait (); Em = emf.createEntityManager (); TypedQuery & LT; Point & gt; Myquery = em.createQuery ("Point P to SELECT p", Point.class); & Lt; Point & gt; Results = myquery.getResultList (); System.out.println ("X-sync is:" + results.get (0) .getX ()); Em.close ();

It should be printed X coordinate 100. But in reality, it is not

What's wrong with my code?

You can fix your code one by one:

Synchronize updated questions so that they can be executed sequentially, instead:

  synchronize (lock) {em.createQuery ("UPDATE Point SET x = x + 1") . ExecuteUpdate (); }   

Your lock object should be an object, which is shared by all threads.

Or, use ObjectDB / JPA locking, by setting a pessimistic locking timeout, e.g. By: Maps & lt; String, integer & gt; Properties = Archive. Singletnet map ("javax.preistence.lock.timeout", 1000); EntityManagerFactory emf = Perseverence.createEntityManagerFactory ("objectdb: $ objectdb / db / test.tmp; drop", property);

And then replacing the UPDATE query with a lock and an update with an update:

  point dot = em.find (Point.class, 1, LockModeType.PESSIMISTIC_WRITE); point.setX (point.getX (+ 1);    

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -