put same key

classic Classic list List threaded Threaded
4 messages Options
javadevmtl javadevmtl
Reply | Threaded
Open this post in threaded view
|

put same key

What happens if 2 different threads try to put the same key at the same time?

I have 80/20 chance that most of the time it wont happen. But it's possible so how do I handle that?
alexey.goncharuk alexey.goncharuk
Reply | Threaded
Open this post in threaded view
|

Re: put same key

If you do plain puts, you will get the same guarantees as if you were updating a simple concurrent hash map - these updates will be ordered in some undefined way and will happen one after another. Of course in the grid backups will be updated in a consistent manner, so you will have the same data on primary and backup nodes regardless of which of the two updates happened first.
Note that there are also other update primitives that give you better control over the cache contents, such as putIfAbsent, replace (compare-and-set, basically).

If you need even more fine-grained control over an update, you can use transactional cache, which allows you to lock a value for the update, so you can make sure that update will happen only if needed. Below is a pseudo-code for this case.

try (Transaction tx = ignite.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
    Object val = cache.get("key"); // get() will acquire a lock for this key. Other threads will not be able to update the key until transaction is finished.

    if (val satisfies some condition) {
         cache.put("key", updatedValue);
         tx.commit();
    }
    // else transaction will be rolled back.
}

Hope this helps,
Alexey

2015-08-28 8:26 GMT-07:00 javadevmtl <[hidden email]>:
What happens if 2 different threads try to put the same key at the same time?

I have 80/20 chance that most of the time it wont happen. But it's possible
so how do I handle that?




--
View this message in context: http://apache-ignite-users.70518.x6.nabble.com/put-same-key-tp1193.html
Sent from the Apache Ignite Users mailing list archive at Nabble.com.

javadevmtl javadevmtl
Reply | Threaded
Open this post in threaded view
|

Re: put same key

So with transactions, if 2 threads try to read/write, the first thread that gets a lock will  block the other thread? And once the first thread finishes the second 1 will continue as normal?

alexey.goncharuk alexey.goncharuk
Reply | Threaded
Open this post in threaded view
|

Re: put same key

Yes, that is correct.

2015-08-28 13:13 GMT-07:00 javadevmtl <[hidden email]>:
So with transactions, if 2 threads try to read/write, the first thread that
gets a lock will  block the other thread? And once the first thread finishes
the second 1 will continue as normal?





--
View this message in context: http://apache-ignite-users.70518.x6.nabble.com/put-same-key-tp1193p1201.html
Sent from the Apache Ignite Users mailing list archive at Nabble.com.