0

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

michele
  • 26,348
  • 30
  • 111
  • 168

1 Answers1

1

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;
}
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
  • so a possible solution would be create client server system, and for each request the server with a synchronize method, decrement the value. is it correct? – michele May 24 '15 at 11:27
  • Yes, you should decrement and return `value` in a synchronized method, and then invoke that method on the server for each client request. However, take care that you synchronize always on the same object instance, this is **NOT** going to work properly: `new MyObject().mySyncMethod()`. – Dragan Bozanovic May 24 '15 at 11:38
  • yes I will use a singleton object. Do you mean this? – michele May 24 '15 at 11:39
  • Yes, that would ensure same lock for each invocation. – Dragan Bozanovic May 24 '15 at 11:51