I tried a couple of attempts with higher-level designs, but nothing came to mind. I think this may be the reason for moving to the low-level API:
EDIT: I really think you are trying to fix a problem that is intrinsically complex (see the second to last paragraph) and probably not needed (see the last paragraph). But that said how this can be done, and I will leave a color comment for the end of this answer.
private int someMethod1Invocations = 0; private int someMethod2Invocations = 0; public void someMethod1() { synchronized(this) {
One glaring problem with the above is that it can lead to thread starvation . For example, someMethod1() works (and blocks someMethod2() s), and as soon as it finishes, another thread appears and calls someMethod1() . This happens very well, and just as another thread ends, someMethod1() starts, etc. In this case, someMethod2() will never get a chance to run. This is actually not an error in the code above; this is a problem with your design needs that should actively work on the solution. I think an honest AbstractQueuedSynchronizer could do the trick, although this exercise is left to the reader. :)
Finally, I can't resist, but embed an opinion: given that ConcurrentHashMap operations are pretty simple, you could better just put one mutex around both methods and just do it. Therefore, yes, threads will have to queue to call someMethod1() , but each thread will complete its turn (and thus allow other threads to continue) very quickly. This should not be a problem.
yshavit
source share