1 /*
   2  * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.nio.ch;
  27 
  28 import java.nio.channels.spi.AsynchronousChannelProvider;
  29 import java.nio.channels.*;
  30 import java.io.IOException;
  31 import java.io.Closeable;
  32 import java.io.FileDescriptor;
  33 import java.util.Map;
  34 import java.util.HashMap;
  35 import java.util.concurrent.locks.ReadWriteLock;
  36 import java.util.concurrent.locks.ReentrantReadWriteLock;
  37 
  38 /**
  39  * Base implementation of AsynchronousChannelGroupImpl for Unix systems.
  40  */
  41 
  42 abstract class Port extends AsynchronousChannelGroupImpl {
  43     static final short POLLIN       = 0x0001;
  44     static final short POLLOUT      = 0x0004;
  45     static final short POLLERR      = 0x0008;
  46     static final short POLLHUP      = 0x0010;
  47 
  48     /**
  49      * Implemented by clients registered with this port.
  50      */
  51     interface PollableChannel extends Closeable {
  52         void onEvent(int events, boolean mayInvokeDirect);
  53     }
  54 
  55     // maps fd to "pollable" channel
  56     protected final ReadWriteLock fdToChannelLock = new ReentrantReadWriteLock();
  57     protected final Map<Integer,PollableChannel> fdToChannel =
  58         new HashMap<Integer,PollableChannel>();
  59 
  60 
  61     Port(AsynchronousChannelProvider provider, ThreadPool pool) {
  62         super(provider, pool);
  63     }
  64 
  65     /**
  66      * Register channel identified by its file descriptor
  67      */
  68     final void register(int fd, PollableChannel ch) {
  69         fdToChannelLock.writeLock().lock();
  70         try {
  71             if (isShutdown())
  72                 throw new ShutdownChannelGroupException();
  73             fdToChannel.put(Integer.valueOf(fd), ch);
  74         } finally {
  75             fdToChannelLock.writeLock().unlock();
  76         }
  77     }
  78 
  79     /**
  80      * Unregister channel identified by its file descriptor
  81      */
  82     final void unregister(int fd) {
  83         boolean checkForShutdown = false;
  84 
  85         fdToChannelLock.writeLock().lock();
  86         try {
  87             fdToChannel.remove(Integer.valueOf(fd));
  88 
  89             // last key to be removed so check if group is shutdown
  90             if (fdToChannel.isEmpty())
  91                 checkForShutdown = true;
  92 
  93         } finally {
  94             fdToChannelLock.writeLock().unlock();
  95         }
  96 
  97         // continue shutdown
  98         if (checkForShutdown && isShutdown()) {
  99             try {
 100                 shutdownNow();
 101             } catch (IOException ignore) { }
 102         }
 103     }
 104     /**
 105      * Register file descriptor with polling mechanism for given events.
 106      * The implementation should translate the events as required.
 107      */
 108     abstract void startPoll(int fd, int events);
 109 
 110     @Override
 111     final boolean isEmpty() {
 112         fdToChannelLock.writeLock().lock();
 113         try {
 114             return fdToChannel.isEmpty();
 115         } finally {
 116             fdToChannelLock.writeLock().unlock();
 117         }
 118     }
 119 
 120     @Override
 121     final Object attachForeignChannel(final Channel channel, FileDescriptor fd) {
 122         int fdVal = IOUtil.fdVal(fd);
 123         register(fdVal, new PollableChannel() {
 124             public void onEvent(int events, boolean mayInvokeDirect) { }
 125             public void close() throws IOException {
 126                 channel.close();
 127             }
 128         });
 129         return Integer.valueOf(fdVal);
 130     }
 131 
 132     @Override
 133     final void detachForeignChannel(Object key) {
 134         unregister((Integer)key);
 135     }
 136 
 137     @Override
 138     final void closeAllChannels() {
 139         /**
 140          * Close channels in batches of up to 128 channels. This allows close
 141          * to remove the channel from the map without interference.
 142          */
 143         final int MAX_BATCH_SIZE = 128;
 144         PollableChannel channels[] = new PollableChannel[MAX_BATCH_SIZE];
 145         int count;
 146         do {
 147             // grab a batch of up to 128 channels
 148             fdToChannelLock.writeLock().lock();
 149             count = 0;
 150             try {
 151                 for (Integer fd: fdToChannel.keySet()) {
 152                     channels[count++] = fdToChannel.get(fd);
 153                     if (count >= MAX_BATCH_SIZE)
 154                         break;
 155                 }
 156             } finally {
 157                 fdToChannelLock.writeLock().unlock();
 158             }
 159 
 160             // close them
 161             for (int i=0; i<count; i++) {
 162                 try {
 163                     channels[i].close();
 164                 } catch (IOException ignore) { }
 165             }
 166         } while (count > 0);
 167     }
 168 }