Saturday, 16 May 2015

Semaphores in Java

Semaphores are mainly used to limit the number of simultaneous threads that can access a resources, but you can also use them to implement deadlock recovery systems since a semaphore with one permit is basically a lock that you can unlock from other threads.

public class SemaphoresMain {
    public static void main(final String[] args) throws Exception {
        final Semaphore semaphore = new Semaphore(1);

        semaphore.release();// Increase permit value by 1
        semaphore.release();
        semaphore.acquire();// Decrees permit value by 1
        System.out.println("Number of permits " + semaphore.availablePermits());
       
    }
}
Output will be 1
public class SemaphoresMain {
    public static void main(final String[] args) throws Exception {
        final Semaphore semaphore = new Semaphore(0);
        semaphore.acquire();// Decrees value by 1
        System.out.println("Number of permits " + semaphore.availablePermits());

    }
}
Output: if there is no permit then acquire method wait for getting a permit. So we can use acquire and release method like wait and notify.

Below example give you clear idea. Here we are connecting ten at a time.

//****************************************************************
//* Copyright (c) 2015. All Rights Reserved.
//****************************************************************
package com.java.thread.semaphores;

import java.util.concurrent.Semaphore;

public class Connection {
    private static Connection instance = new Connection();

    private Semaphore sem = new Semaphore(10, true);

    private int connections = 0;

    private Connection() {
    }

    public static Connection getInstance() {
        return instance;
    }

    public void connect() {
        try {
            sem.acquire();
        } catch (final InterruptedException e1) {
            e1.printStackTrace();
        }

        try {
            doConnect();
        } finally {
            sem.release();
        }
    }

    public void doConnect() {

        synchronized (this) {
            connections++;
            System.out.println("Current connections: " + connections);
        }

        try {
            Thread.sleep(2000);
        } catch (final InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        synchronized (this) {
            connections--;
        }
    }
}
//****************************************************************
//* Copyright (c) 2015. All Rights Reserved.
//****************************************************************
package com.java.thread.semaphores;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SemaphoresMain {
    public static void main(final String[] args) throws Exception {

        final ExecutorService executor = Executors.newCachedThreadPool();

        for (int i = 0; i < 200; i++) {
            executor.submit(new Runnable() {
                public void run() {
                    Connection.getInstance().connect();
                }
            });
        }

        executor.shutdown();

        executor.awaitTermination(1, TimeUnit.DAYS);
    }


}

Output:

Current connections: 1
Current connections: 2
Current connections: 3
Current connections: 4
Current connections: 5
Current connections: 6
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 5
Current connections: 6
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 8
Current connections: 6
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 9
Current connections: 6
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 6
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 8
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 8
Current connections: 8
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 8
Current connections: 8
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 8
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 9
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 10
Current connections: 7
Current connections: 7
Current connections: 8
Current connections: 9
Current connections: 9
Current connections: 8
Current connections: 9
Current connections: 9
Current connections: 10


Kindly provide your valuable feedback in comment box.

No comments:

Post a Comment