Java synchronized method around parameter value

Consider the following method:

public void upsert(int customerId, int somethingElse) {
  // some code which is prone to race conditions    
}

I want to protect this method from race conditions, but this can only happen if two threads with the same customerIdcall it at the same time. If I do the whole method synchronized, it will reduce efficiency and will not be needed. I really want to sync it around customerId. Is this possible somehow with Java? Are there any built-in tools for this or will I need Map Integersto use as locks?

Also feel free to advise if you think that I am doing something wrong :)

Thank!

+4
source share
1 answer

, , . ( ). , parallelism. 8-16 , , .

:

private final Object[] locks = new Object[8];

synchronized (locks[customerId % locks.length]) {
    ...implementation...
}
+11

Source: https://habr.com/ru/post/1654569/


All Articles