#multithreading in Spring Boot REST API

1 messages · Page 1 of 1 (latest)

cobalt plaza
#

In my service method I need to do the following:

  1. get an entry from the database and lock it for updating and deleting,
  2. check the status property of the entry (entity object),
  3. if the status is "stopped" return "starting..."(scenarios where the status is not stopped are not a problem)
  4. what for 15 seconds
  5. update status to "running"
  6. release the lock.

the problem is that when I return the value in step 4 the method is over, and das so the transaction, so the lock gets released and steps 5 and 6 are not getting executed. I have to make another thread and execute steps 5 and 6 there while still keeping the same transaction so that the lock created in step 1 doesn't get released.
my solution:

public String startServer(int id) {
Object lock1 = new Object();

    new Thread(() -> atamptStart(lock1,id)).start();
    try {
        lock1.wait();
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }

    return message;
}```

atamptStart(lock1, id) calls notify() on the lock1 object when the status is obtained from db and continues executing steps 5 and 6 afterward.
is this a good approach and if not what is better? 
Thanks.
distant patrolBOT
#

This post has been reserved for your question.

Hey @cobalt plaza! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

rapid sorrel
#

I’d suggest looking at a ReentrantReadWriteLock. It’ll most likely have what you’re looking for

cobalt plaza
distant patrolBOT
# cobalt plaza Thank you Twala, this helps definitely

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.