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     // Callback method for implementations that need special handling when fd is
  80     // removed (currently only needed in the AIX-Port - see AixPollPort.java)
  81     void unregisterImpl(int fd) {
  82         // Do nothing by default.
  83     }
  84 
  85     /**
  86      * Unregister channel identified by its file descriptor
  87      */
  88     final void unregister(int fd) {
  89         boolean checkForShutdown = false;
  90 
  91         unregisterImpl(fd);
  92 
  93         fdToChannelLock.writeLock().lock();
  94         try {
  95             fdToChannel.remove(Integer.valueOf(fd));
  96 
  97             // last key to be removed so check if group is shutdown
  98             if (fdToChannel.isEmpty())
  99                 checkForShutdown = true;
 100 
 101         } finally {
 102             fdToChannelLock.writeLock().unlock();
 103         }
 104 
 105         // continue shutdown
 106         if (checkForShutdown && isShutdown()) {
 107             try {
 108                 shutdownNow();
 109             } catch (IOException ignore) { }
 110         }
 111     }
 112     /**
 113      * Register file descriptor with polling mechanism for given events.
 114      * The implementation should translate the events as required.
 115      */
 116     abstract void startPoll(int fd, int events);
 117 
 118     @Override
 119     final boolean isEmpty() {
 120         fdToChannelLock.writeLock().lock();
 121         try {
 122             return fdToChannel.isEmpty();
 123         } finally {
 124             fdToChannelLock.writeLock().unlock();
 125         }
 126     }
 127 
 128     @Override
 129     final Object attachForeignChannel(final Channel channel, FileDescriptor fd) {
 130         int fdVal = IOUtil.fdVal(fd);
 131         register(fdVal, new PollableChannel() {
 132             public void onEvent(int events, boolean mayInvokeDirect) { }
 133             public void close() throws IOException {
 134                 channel.close();
 135             }
 136         });
 137         return Integer.valueOf(fdVal);
 138     }
 139 
 140     @Override
 141     final void detachForeignChannel(Object key) {
 142         unregister((Integer)key);
 143     }
 144 
 145     @Override
 146     final void closeAllChannels() {
 147         /**
 148          * Close channels in batches of up to 128 channels. This allows close
 149          * to remove the channel from the map without interference.
 150          */
 151         final int MAX_BATCH_SIZE = 128;
 152         PollableChannel channels[] = new PollableChannel[MAX_BATCH_SIZE];
 153         int count;
 154         do {
 155             // grab a batch of up to 128 channels
 156             fdToChannelLock.writeLock().lock();
 157             count = 0;
 158             try {
 159                 for (Integer fd: fdToChannel.keySet()) {
 160                     channels[count++] = fdToChannel.get(fd);
 161                     if (count >= MAX_BATCH_SIZE)
 162                         break;
 163                 }
 164             } finally {
 165                 fdToChannelLock.writeLock().unlock();
 166             }
 167 
 168             // close them
 169             for (int i=0; i<count; i++) {
 170                 try {
 171                     channels[i].close();
 172                 } catch (IOException ignore) { }
 173             }
 174         } while (count > 0);
 175     }
 176 }