O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

Follow these steps to implement the example:

  1. Create a class named MyAbstractQueuedSynchronizer that extends the AbstractQueuedSynchronizer class:
        public class MyAbstractQueuedSynchronizer extends                                        AbstractQueuedSynchronizer {
  1. Declare a private AtomicInteger attribute named state:
        private final AtomicInteger state;
  1. Implement the constructor of the class to initialize its attribute:
        public MyAbstractQueuedSynchronizer() {           state=new AtomicInteger(0);         }
  1. Implement the tryAcquire() method. This method tries to change the value of the state variable from zero to one. If it can, it returns the true value; else, it returns false:
        @Override         protected boolean tryAcquire(int arg) {  return state.compareAndSet(0, 1);  ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required