I'm trying to solve a problem where multiple concurrent HTTP requests are coming in and the server will read and increment the value stored in Hazelcast by 1. For example there are 3 incoming requests, the previous number value from 0 will increase to 1, keep increasing to 2 when processing request 2 and increasing to 3 when processing request 3. I am afraid that if I don't sync it, HTTP requests may read and write the old value causing problem of data inconsistency. I researched and found the method using "vertx.executeBlocking(future{});".
vertx.executeBlocking(future -> {
}, res -> {
});
However, I don't know if using this method will synchronize the problem of reading and writing HTTP requests simultaneously or not? Or is there any solution for me to solve the above problem? I would be very grateful and appreciative of that. Thank
CodePudding user response:
There is a lot mixed up here.
vertx.executeBlocking
Is a way to off load blocking work onto a worker thread. If you are doing something that is not async on the event loop - this is a convenience method so that you can offload that work to a background thread to not block the event loop. It has nothing to do with 'syncing' read/writes
I am afraid that if I don't sync it
Hazelcast is already concurrency safe - so you should increment it and hazelcast will do the 'sync'
If all you want is a counter then you should just have a simple AtomicLong that gets incremented instead of dealing with hazelcast
CodePudding user response:
You could use Counter class in Vert.x library https://vertx.io/docs/apidocs/io/vertx/core/shareddata/Counter.html. It is distributed counter. executeBlocking method won't work in multi instance environment.