简体   繁体   中英

Can I lock row of DB2 for reading?

I've few scheduled processes which perform on the same row. Actually this row is a SMS needed to be sent. First process is @Asynchronious process which invoked when I press send button and second process is @Scheduled process which invoked once per minute. After I've written a SMS into DB it has status 0. After I've successfully or unsuccessfully sent it, it will have status 2 or 3 accordingly. The problem that when I read a SMS from the DB2 but before I actually sent it the second process can read and send it too. So, my question how can I prevent it? Can I lock specific row for reading? Another way is to add additional status 'processing' and change this status when I read a specific row, but I doubt is is possible to read and to write simultaneously? I though also about global flag which will indicate that this process can't be run, but I'm not only looking for solution I also looking for the most correct solution. Thank you very much!

And sorry for my English guys, if somebody will edit it I'll be grateful.

I'm assuming you're using DB2 for Linux/Unix/Windows, since you don't mention a platform.

There is a way to have DB2 lock a row on a SELECT, see the isolation-clause and lock-request-clause on this Information Center page .

When specifying an isolation level of either RR (repeatable read) or RS (read stability), you can also say that you want to lock the rows that are read, either with a SHARE , UPDATE , or EXCLUSIVE lock.

That statement will lock the row as long as the transaction is active.

You cannot reliably prevent other applications from reading a row locked by one application. Queries running with the uncommitted read isolation level will be able to access even exclusively locked rows. Queries running with the cursor stability isolation level using the currently committed semantics will access the previous version of the exclusively locked row.

I think your best choice is to use a special value (like 'processing') in the status column to prevent other sessions from processing the same row.

Ok, I actually solved it by creating a singleton with following flag public static boolean busy; first method which run change its value to true and while it's true second method doesn't run. While first method completed it changes it back to false.

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