Search code examples
javaclient-serverjava.util.concurrentconcurrency

java model client server architecture with lock on resources


I have to develop a client server architecture with Java (server side), but I need some advice.

Situation:

  1. a server that exposes an action decrementValue
  2. the server has a variable called Value = integer value
  3. some clients can send a decrementValue request to the server
  4. server, for each requests, do:
    -- if value > 0 value = value - 1 and answer the new val to the client

    -- if value = 0 answer impossible operation

So, if value = 2 and 3 request arrives at the same time, only 2 request can decrement value.

What is the best solution to do it?

How can I guarantee the exclusive access to value stored in the server, if some request are done in the same time from client to server?

Thank you.

enter image description here


Solution

  • That depends what you mean by best solution. If you just want your program to behave correctly in a concurrent environment, then you should synchronize data that is concurrently modified. That would be a standard (and readable) way to enable exclusive access to shared data.

    However, if this is not your question, but rather what would be the most efficient way to do it in Java in theory, (or if this is called in an extremely concurrent context), then my suggestion is as follows:

    static final AtomicInteger atomicInteger = new AtomicInteger(initialValue);
    ...
    if (atomicInteger.get() <= 0) {
        return "imposibble. value=0";
    }
    int result = atomicInteger.decrementAndGet();
    if (result < 0) {
        atomicInteger.incrementAndGet(); // Revert the effect of decrementing
        return "imposibble. value=0";
    } else {
        return "new value=" + result;
    }