How to write a consumer producer using JPA

I currently have a JPA object for some tasks. Some processes write to this table, and the scheduled process works on these tasks and changes state when ready. I need to prioritize tasks and repeat them with decreasing frequency if they fail. My environment is GlassFish 3 + JPA through Hibernate + MySQL + XA transactions. In the medium term, the project will replace GlassFish with a Spring solution (using Jetty or so).

Somehow it worked out, but I'm not very happy with it: I get OptimisticLockExceptions, it seems that in some cases I didn’t receive the transaction, and the JPA timers on GlassFish are also messy if you need variable times.

I have the feeling that I am using the wrong tools here, and that I should use some kind of mature, stable design, and not something knocked down. Using JPA entities seems to be tough, but raw JDBC looks even worse. Of course, I want to avoid heavy dependencies in the library, but perhaps I am losing sight of the simple “canned” solution for my specific problem (which does not seem so unusual).

[change]

To clarify: I won’t change the use case (I don’t have the code anymore), I just want to get some general recommendations to “do it right” (TM) next time. To answer the question from ben75: the worker can be multithreaded, and I need small transactions, as this should be done all the time - maybe within a few months.

+4
source share
1 answer

I think you just need to try to see things from above to determine the roles in this process and determine the dependencies between the task creator, task processor (s) and priority controller. Next, design clean, reusable EJBs / Services for each of these roles.

Sometimes for relative short tasks that take only 10-20 seconds, it makes sense to make the user wait using Asynchronous EJB ( @Asynchronous search) instead of creating a task.

About OptimisticLockExpcetions: this may be due to data changes occurring during this time that may be caused by one of your other client user threads or by a client that is modifying data. Determine the cause, and if this is the first case, correct the error. Of course, you will get additional help if you provide some kind of code or explain how everything works.

When processing tasks: I get Task objects with Pessimistic Lock, so that another thread does not start processing the same task.

So, I believe your process is complex and you need a more flexible design.

+1
source

Source: https://habr.com/ru/post/1486761/


All Articles