I've created the following class to manage the assignment of port numbers to passive FTP server sockets. Notice that Semaphore here is to make the thread wait in case all the ports are assigned, not for Stack synchronization, which is already thread-safe.Is this class safe assuming releasePort is always invoked when the socket is closed ? And regarding that, what would be the safest way to ensure it, that is, of detecting that the socket has been closed, either correctly or by any exception ?import java.util.Stack;import java.util.Vector;import java.util.concurrent.Semaphore;public class PassivePortStack {    private Semaphore semaphore;    private Stack<Integer> stack;    public PassivePortStack(Vector<Integer> ports) {        semaphore = new Semaphore(ports.size());        stack = new Stack<Integer>();        stack.setSize(ports.size());                for (Integer port : ports) {            stack.push(port);        }    }    public int acquirePort() {        Integer port = -1;        try {            semaphore.acquire();            port = stack.pop();        } catch (InterruptedException e) {            e.printStackTrace();        }        return port;    }    public void releasePort(int port) {        stack.push(port);        semaphore.release();    }}
Passive FTP port assignment synchronization
java;synchronization;ftp