0

I have many clients Ai (A1,...,An) everyone of which does the action X. And a server B which does the action Y. But Y could only be done only if there is no one executes X.

So I think of the mutex lock: every client has an own lock Li. It's no problem for clients, but it will be horrible for the server B, something like this:

synchronized(L1){
    synchronized(L2){
        ...
    }
}

Is there any better solution for this kind of problem?

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
Silver
  • 77
  • 10
  • 1
    Use semaphore or atomic counter and adopt it to work cross-server – Antoniossss Oct 05 '16 at 09:48
  • If I use semaphore, I should precise the number of permit which is uncertain as the number of clients. – Silver Oct 05 '16 at 10:01
  • @Silver Not true. You can create a `Semaphore` with 1000 permits and have B always try to acquire all 1000. If any client has one checked out, it will have to wait. – Kayaman Oct 05 '16 at 10:06
  • @Silver ofc you cannot use in straight-forward way but it is possible to use its synchronization advantages for your gain like Kayman pointed out. You can always have Long.maxVal permits - clients will aquire and release only single permit while server will always aquire all of them (thus block till then) do the work and release aquired permits allowing clients to work again. – Antoniossss Oct 05 '16 at 10:12
  • @Kayaman well, between clients, there should not be any block with each other. If I fix 1000 permits, there may be risks. – Silver Oct 05 '16 at 10:31
  • @Silver That was an example. If you think that you can have 1000 simultaneous clients, then use `1000000` permits. Or `1000000000` permits. – Kayaman Oct 05 '16 at 10:43
  • @Silver why exactly you want to skip 'Y' when someone executes 'X'? because they share a common variable?? – Supun Wijerathne Oct 11 '16 at 07:29
  • @SupunWijerathne Yes it is. Actually olsli's answer solved my problem. – Silver Oct 11 '16 at 07:51
  • @Silver if you can give an exact answer for my comment, I might be able to specify an easier way. :)) – Supun Wijerathne Oct 11 '16 at 07:56

1 Answers1

1

You may try with ReadWriteLock (ReentrantReadWriteLock) shared between all nodes. Server should acquire write lock and will block all clients from performing X. And client should acquire read lock and not block other clients.

olsli
  • 831
  • 6
  • 8