In my service method I need to do the following:
- get an entry from the database and lock it for updating and deleting,
- check the status property of the entry (entity object),
- if the status is "stopped" return "starting..."(scenarios where the status is not stopped are not a problem)
- what for 15 seconds
- update status to "running"
- 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.