简体   繁体   中英

Two threads writing different fields of same entity

I have the following situation.

One business entity (BE) consists of 2 parts provided asynchronously by 2 threads. Example: our BE has fields id and, A, B, C - all in one table in database. Id is generated by sequence when entity is stored into database. B is unique field, there's constraint on it in database. Process1 provides fields A and B. Process2 provides fields B and C. So after both processes finish, we should have one row in a table with all columns filled in.

What is the good way to make this work?

What is done now:

In each process we first select all values from table where value in column B is what we now have. (If any - this means the other process already saved it's part). If there's something, it is enriched with the missing column and persisted. If there's nothing - we just persist what we have. But while all this is done, it can occur that the other process finished it's job and when we persist our entity, we get ConstraintViolationException and hibernate marks transaction to rollback. And the missing column is still missing.

You first have to decide how you want conflicts to be handled. For this answer the following questions:

If process 1 changes your entity while process 2 is running are the results of 2 still valid? Or should it rerun?

If process 1 updates field B should while process 2 is running should process 2 overwrite it? or just keep the value of process 1?

Of course the questions should also be answered with 1 and 2 interchanged.

If you implement the process in a way that they take the original entity, and produce a new modified + the original entity they startet with, you can have a single queue where all these results get added and a single process applying these changes to your database.

In specific scenarios, simpler approaches might be possible, but this is the approach I would recommend in the very general case you describe in your question.

i would do it this way

  • load or create Entity before launching the threads
  • launch thread and give it to each
  • update it in both threads
  • when both finished save to db

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM