I have a code in here which is being used to explain how the semaphore works.. No matter How hard I try I am not understanding the line below and there by how to code semaphore is invoked.
Basically the code tries to simulate many connects being made...
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 (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            doConnect();
        } finally {
            sem.release();
        }
    }
    public void doConnect() {
        synchronized (this) {
            connections++;
            System.out.println("Current connections: " + connections);
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        synchronized (this) {
            connections--;
        }
    }
}
Main class file..
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class App {
    public static void main(String[] args) throws Exception {
        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);
    }
}
I am not understanding the run part
public void run() {
    Connection.getInstance().connect();
}
How can we call a connect method from the above? in my judgement connections output should always be one as new threads are being called. surprisingly but that never happens.
 
     
     
     
    