Wednesday, August 19, 2015

Dijkstra Sleeping Barber Problem | Oracle Java Combo



Sleeping Barber Problem | Oracle Java Combo
The Sleeping-Barber Problem. A barbershop consists of a waiting room with n chairs and a barber room with one barber chair. If there are no customers to be served, the barber goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the customer leaves the shop. If the barber is busy but chairs are available, then the customer sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber. Write a program to  coordinate the barber and the customers.

Good Java code:
https://github.com/MikeChristianson/sleeping-barber/tree/master/src/name/christianson/mike

private final static AtomicBoolean shopOpen = new AtomicBoolean(); private final static AtomicInteger totalHaircuts = new AtomicInteger();
private final static AtomicInteger lostCustomers = new AtomicInteger();
private final BlockingQueue<Object> waitingRoom = new LinkedBlockingQueue<>(NUM_WAITING_ROOM_CHAIRS);

https://vyatkins.wordpress.com/2013/12/21/sleeping-barber-problem/
X. Using Block Queue
public class BlockinQueueSleepingBarber extends Thread {
    public static final int CHAIRS = 5;
    public static final long BARBER_TIME = 5000;
    private static final long CUSTOMER_TIME = 2000;
    public static final long OFFICE_CLOSE = BARBER_TIME * 2;
    public static BlockingQueue queue = new ArrayBlockingQueue(CHAIRS);
    class Customer extends Thread {
        int iD;
        boolean notCut = true;
        BlockingQueue queue = null;
        public Customer(int i, BlockingQueue queue) {
            iD = i;
            this.queue = queue;
        }
        public void run() {
            while (true) { // as long as the customer is not cut he is in the queue or if not enough sits he is out
                try {
                    this.queue.add(this.iD);
                    this.getHaircut(); // take a sit
                } catch (IllegalStateException e) {
                    System.out.println(&quot;There are no free seats. Customer &quot;
                            + this.iD + &quot; has left the barbershop.&quot;);
                }
                break;
            }
        }
        // take a seat
        public void getHaircut() {
            System.out.println(&quot;Customer &quot; + this.iD + &quot; took a chair&quot;);
        }
    }
    class Barber extends Thread {
        BlockingQueue queue = null;
        public Barber(BlockingQueue queue) {
            this.queue = queue;
        }
        public void run() {
            while (true) { // runs in an infinite loop
                try {
                        Integer i = this.queue.poll(OFFICE_CLOSE, TimeUnit.MILLISECONDS);
                        if (i==null) break; // barber slept for long time (OFFICE_CLOSE) no more clients in the queue - close office
                    this.cutHair(i); // cutting...
                } catch (InterruptedException e) {
                }
            }
        }
        // simulate cutting hair
        public void cutHair(Integer i) {
            System.out.println(&quot;The barber is cutting hair for customer #&quot; + i);
            try {
                sleep(BARBER_TIME);
            } catch (InterruptedException ex) {
            }
        }
    }
    public static void main(String args[]) {
        BlockinQueueSleepingBarber barberShop = new BlockinQueueSleepingBarber();
        barberShop.start(); // Let the simulation begin
    }
    public void run() {
        Barber giovanni = new Barber(BlockinQueueSleepingBarber.queue);
        giovanni.start();
        //  create new customers
        for (int i = 1; i &lt; 16; i++) {
            Customer aCustomer = new Customer(i, BlockinQueueSleepingBarber.queue);
            aCustomer.start();
            try {
                sleep(CUSTOMER_TIME);
            } catch (InterruptedException ex) {};
        }
    }
}
You can easily modify this code for example if you need to add new barber like this
Barber barber01 = new Barber(BlockinQueueSleepingBarber.queue, &quot;01&quot;);
barber01.start();
Barber barber02 = new Barber(BlockinQueueSleepingBarber.queue, &quot;02&quot;);
barber02.start();


Actors in Action – Sleeping Barber Problem with AKKA

public class Barber implements Runnable {
    Queue<Customer>customers;

    private Shop shop;

    public Barber(Shop shop) {
        this.shop = shop;
        customers = new LinkedBlockingQueue & lt; Customer & gt;
        ();
    }

    public void addCustomerToQueue(Customer customer) {
        customers.add(customer);
    }

    public void run() { // add while(running)
        while (!customers.isEmpty()) {
            Customer customer = customers.remove();
            performHaircut(customer);
            shop.releaseChair();
        }  // ===>   }
    }

    private void performHaircut(Customer customer) {
        System.out.println("Customer " + customer.getId()
                + " has got a haircut");

    }
}
public class Shop {
    private Barber barber;
    private Semaphore semaphore;
    private AtomicInteger count = new AtomicInteger(0);

    public Shop() {
        semaphore = new Semaphore(3);
    }

    public void init() {
        barber = new Barber(this);
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(barber, 100,
                1000, TimeUnit.MILLISECONDS);
    }

    public void acquireChair(Customer customer) throws InterruptedException {
        boolean acquired = semaphore.tryAcquire(1, 100, TimeUnit.MILLISECONDS);
        if (acquired) {
            count.getAndIncrement();
            barber.addCustomerToQueue(customer);
            return;
        }
        System.out.println("Turning customer " + customer.getId() + " away");
    }

    public void releaseChair() {
        semaphore.release(1);
    }

    public int getSuccessfulHaircutCount() {
        return count.intValue();
    }
}
AKKA:
public class Barber extends UntypedActor {
    Random random = new Random();

    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof Customer) {
            Customer customer = (Customer) message;
            Thread.sleep(random.nextInt(1150));
            System.out.println("Customer " + customer.getId() + " Got a Haircut");

        }
    }
}

public class Shop extends UntypedActor {
    Queue<Customer>customers=new LinkedBlockingQueue<Customer>();
    ActorRef barber;
    int counter = 0;

    public Shop(ActorRef barber) {
        this.barber = barber;
    }

    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof Customer) {
            processCustomer(message);
        } else if (message instanceof WakeUp) {
            barber.tell(customers.poll());
        }
    }

    private void processCustomer(Object message) {
        if (customers.size() == 3) {
            Customer customer = (Customer) message;
            System.out.println("Customer " + customer.getId() + " is leaving");
            return;
        }
        counter++;
        customers.add((Customer) message);
    }

    @Override
    public void postStop() {
        System.out.println(counter + " Customers got a haircut today");
        super.postStop();
    }
}
Sleeping barber problem using Reentrant Locks
Sleeping barber problem using Semaphores
How to use Kafka message broker for Dijkstra’s Sleeping Barber problem
Read full article from Sleeping Barber Problem | Oracle Java Combo

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts