Search code examples
java-ee-6nio

Using java nio in java ee


I want to use java nio in java ee. But I don't know how to do it right. I need to after server has deploy java.nio.selector always listens the port and processing socket connection. I try do it there:

@Singleton
@Lock(LockType.READ)
public class TaskManager {

    private static final int LISTENINGPORT;

    static {
        LISTENINGPORT = ConfigurationSettings.getConfigureSettings().getListeningPort();
    }

    private ArrayList<ServerCalculationInfo> serverList;

    public TaskManager() {
        serverList = new ArrayList<ServerCalculationInfo>();
        select();
    }

    @Asynchronous
    public void select() {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            Selector selector = Selector.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(LISTENINGPORT));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                try {
                    selector.select();
                } catch (IOException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                    break;
                }
                Iterator it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selKey = (SelectionKey) it.next();
                    it.remove();
                    try {
                        processSelectionKey(serverSocketChannel, selKey);
                    } catch (IOException e) {
                        serverList.remove(serverCalculationInfo);
                    }
                }
            }

        } catch (IOException e) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
        } catch (Exception e) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
        }
    }
}

It don't work correctly. The process hangs during deploy and redeploy application possible only after restart Glassfish. How can I do right it?


Solution

  • It works correctly if invoke @Asynchronous method from the @PostConstructor:

    @PostConstruct
    public void postTaskManager() {
        serverList = new ArrayList<ServerCalculationInfo>();
        select();
    }
    

    instead of invoke it from constructor. But class must be without @Startup annotation.