package edu.hm.cs.vss;

import java.util.Optional;

/**
 * Created by Fabio Hellmann on 17.03.2016.
 */
public interface Fork {

    /**
     * @return <code>true</code> if the fork is available.
     */
    boolean isAvailable();

    /**
     * Blocks this fork immediately if it is available.
     *
     * @return the fork or <code>null</code> if the fork wasn't available.
     */
    Optional<Fork> blockIfAvailable();

    /**
     * Set the fork available again.
     */
    void unblock();

    class Builder {
        private static int count = 1;
        private String chairName;

        public Builder withChair(final String chairName) {
            this.chairName = chairName;
            return this;
        }

        public Fork create() {
            return new Fork() {
                private final String name = "Fork-" + (count++);
                private boolean block;

                @Override
                public String toString() {
                    return name + " from " + chairName;
                }

                @Override
                public boolean isAvailable() {
                    return !block;
                }

                @Override
                public synchronized Optional<Fork> blockIfAvailable() {
                    if (isAvailable()) {
                        block = true;
                        return Optional.of(this);
                    }
                    return Optional.empty();
                }

                @Override
                public synchronized void unblock() {
                    block = false;
                }
            };
        }
    }
}

@@ -43,16 +43,66 @@
 ptional;
+%0Aimport java.util.concurrent.atomic.AtomicBoolean;
 %0A%0A/**%0A *
@@ -927,21 +927,60 @@
 ate 
-boolean block
+final AtomicBoolean block = new AtomicBoolean(false)
 ;%0A%0A 
@@ -1228,16 +1228,22 @@
 n !block
+.get()
 ;%0A      
@@ -1304,29 +1304,16 @@
  public 
-synchronized 
 Optional
@@ -1368,62 +1368,43 @@
 if (
-isAvailable()) %7B%0A                        block =
+block.compareAndSet(false,
  true
-;
+)) %7B
 %0A   
@@ -1589,21 +1589,8 @@
 lic 
-synchronized 
 void
@@ -1631,16 +1631,18 @@
 lock
- = false
+.set(true)
 ;%0A  

Use AtomicBoolean in Fork