1

Is there an analog of InitializeCriticalSectionWithSpinCount in Java? It implements a hybrid mutex. I have a problem seeing too many thread spending time in LockSupport.park() method while locking very short portions of computation intensive code with either ReentrantLock or synchronized (the code being locked takes hardly measurable portion of total running time on a single core). Here is a class that helps significantly my case, I wonder if I took wrong path.

    public class ReentrantLockWithSpin extends ReentrantLock {
        private final int _spinCount;
        ReentrantLockWithSpin() {
            _spinCount = 1000;
        }
        ReentrantLockWithSpin(int spinCount) {
            _spinCount = spinCount;
        }
        @Override
        public void lock() {
            for (int spin = 0; spin != _spinCount; spin++) {
                if (super.tryLock())
                    return;

                Thread.yield();
            }

            super.lock();
        }
    }
0kcats
  • 672
  • 5
  • 16
  • A spin lock in Java is just a regular lock. The JVM will replace any lightly contested locks in your system with a spin lock. But if you're seeing a lot of threads blocked in `LockSupport.park()` then your lock is heavily contested and blocking is a better idea. – markspace Jan 17 '19 at 19:43
  • 1
    @markspace Where can I confirm that JVM will replace my locks with spin locks? – 0kcats Jan 17 '19 at 20:06
  • There are a lot of answer to that question when I used google to look it up. What did you find and what questions to you still have? Here's one answer: https://stackoverflow.com/questions/26709471/how-to-implement-a-spinlock-to-avoid-blocking – markspace Jan 17 '19 at 22:11
  • 1
    @markspace I don't see how this link confirms that JVM replaces locks with spin locks. Mine is: java version "10.0.2" 2018-07-17 Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode) – 0kcats Jan 17 '19 at 22:38
  • Related: https://stackoverflow.com/questions/26709471/how-to-implement-a-spinlock-to-avoid-blocking – 0kcats Nov 16 '20 at 18:32
  • Related: https://stackoverflow.com/questions/6325824/does-any-jvm-implement-blocking-with-spin-waiting – 0kcats Nov 16 '20 at 18:32
  • https://stackoverflow.com/questions/20689718/what-is-adaptive-spinning-w-r-t-lock-acquisition – 0kcats Nov 16 '20 at 18:34

0 Answers0