UnixAsynchronousSocketChannelImpl.java 22.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright 2008-2009 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 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 22 23 24 25 26 27 28 29 30 31 32 33 34
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.nio.ch;

import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.net.*;
import java.util.concurrent.*;
import java.io.IOException;
import java.io.FileDescriptor;
import java.security.AccessController;
A
alanb 已提交
35
import sun.net.NetHooks;
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
import sun.security.action.GetPropertyAction;

/**
 * Unix implementation of AsynchronousSocketChannel
 */

class UnixAsynchronousSocketChannelImpl
    extends AsynchronousSocketChannelImpl implements Port.PollableChannel
{
    private final static NativeDispatcher nd = new SocketDispatcher();
    private static enum OpType { CONNECT, READ, WRITE };

    private static final boolean disableSynchronousRead;
    static {
        String propValue = AccessController.doPrivileged(
            new GetPropertyAction("sun.nio.ch.disableSynchronousRead", "false"));
        disableSynchronousRead = (propValue.length() == 0) ?
            true : Boolean.valueOf(propValue);
    }

    private final Port port;
    private final int fdVal;

    // used to ensure that the context for I/O operations that complete
    // ascynrhonously is visible to the pooled threads handling I/O events.
    private final Object updateLock = new Object();

    // pending connect (updateLock)
    private PendingFuture<Void,Object> pendingConnect;

    // pending remote address (statLock)
    private SocketAddress pendingRemote;

    // pending read (updateLock)
    private ByteBuffer[] readBuffers;
    private boolean scatteringRead;
    private PendingFuture<Number,Object> pendingRead;

    // pending write (updateLock)
    private ByteBuffer[] writeBuffers;
    private boolean gatheringWrite;
    private PendingFuture<Number,Object> pendingWrite;


    UnixAsynchronousSocketChannelImpl(Port port)
        throws IOException
    {
        super(port);

        // set non-blocking
        try {
            IOUtil.configureBlocking(fd, false);
        } catch (IOException x) {
            nd.close(fd);
            throw x;
        }

        this.port = port;
        this.fdVal = IOUtil.fdVal(fd);

        // add mapping from file descriptor to this channel
        port.register(fdVal, this);
    }

    // Constructor for sockets created by UnixAsynchronousServerSocketChannelImpl
    UnixAsynchronousSocketChannelImpl(Port port,
                                      FileDescriptor fd,
                                      InetSocketAddress remote)
        throws IOException
    {
        super(port, fd, remote);

        this.fdVal = IOUtil.fdVal(fd);
        IOUtil.configureBlocking(fd, false);

        try {
            port.register(fdVal, this);
        } catch (ShutdownChannelGroupException x) {
            // ShutdownChannelGroupException thrown if we attempt to register a
            // new channel after the group is shutdown
            throw new IOException(x);
        }

        this.port = port;
    }

    @Override
    public AsynchronousChannelGroupImpl group() {
        return port;
    }

    // register for events if there are outstanding I/O operations
    private void updateEvents() {
        assert Thread.holdsLock(updateLock);
        int events = 0;
        if (pendingRead != null)
            events |= Port.POLLIN;
        if (pendingConnect != null || pendingWrite != null)
            events |= Port.POLLOUT;
        if (events != 0)
            port.startPoll(fdVal, events);
    }

    /**
     * Invoked by event handler thread when file descriptor is polled
     */
    @Override
    public void onEvent(int events) {
        boolean readable = (events & Port.POLLIN) > 0;
        boolean writable = (events & Port.POLLOUT) > 0;
        if ((events & (Port.POLLERR | Port.POLLHUP)) > 0) {
            readable = true;
            writable = true;
        }

        PendingFuture<Void,Object> connectResult = null;
        PendingFuture<Number,Object> readResult = null;
        PendingFuture<Number,Object> writeResult = null;

        // map event to pending result
        synchronized (updateLock) {
            if (readable && (pendingRead != null)) {
                readResult = pendingRead;
                pendingRead = null;
            }
            if (writable) {
                if (pendingWrite != null) {
                    writeResult = pendingWrite;
                    pendingWrite = null;
                } else if (pendingConnect != null) {
                    connectResult = pendingConnect;
                    pendingConnect = null;
                }
            }
        }

        // complete the I/O operation. Special case for when channel is
        // ready for both reading and writing. In that case, submit task to
        // complete write if write operation has a completion handler.
        if (readResult != null) {
            if (writeResult != null)
                finishWrite(writeResult, false);
            finishRead(readResult, true);
            return;
        }
        if (writeResult != null) {
            finishWrite(writeResult, true);
        }
        if (connectResult != null) {
            finishConnect(connectResult, true);
        }
    }

    // returns and clears the result of a pending read
    PendingFuture<Number,Object> grabPendingRead() {
        synchronized (updateLock) {
            PendingFuture<Number,Object> result = pendingRead;
            pendingRead = null;
            return result;
        }
    }

    // returns and clears the result of a pending write
    PendingFuture<Number,Object> grabPendingWrite() {
        synchronized (updateLock) {
            PendingFuture<Number,Object> result = pendingWrite;
            pendingWrite = null;
            return result;
        }
    }

    @Override
    void implClose() throws IOException {
        // remove the mapping
        port.unregister(fdVal);

        // close file descriptor
        nd.close(fd);

        // All outstanding I/O operations are required to fail
        final PendingFuture<Void,Object> readyToConnect;
        final PendingFuture<Number,Object> readyToRead;
        final PendingFuture<Number,Object> readyToWrite;
        synchronized (updateLock) {
            readyToConnect = pendingConnect;
            pendingConnect = null;
            readyToRead = pendingRead;
            pendingRead = null;
            readyToWrite = pendingWrite;
            pendingWrite = null;
        }
        if (readyToConnect != null) {
            finishConnect(readyToConnect, false);
        }
        if (readyToRead != null) {
            finishRead(readyToRead, false);
        }
        if (readyToWrite != null) {
            finishWrite(readyToWrite, false);
        }
    }

    @Override
    public void onCancel(PendingFuture<?,?> task) {
        if (task.getContext() == OpType.CONNECT)
            killConnect();
        if (task.getContext() == OpType.READ)
            killConnect();
        if (task.getContext() == OpType.WRITE)
            killConnect();
    }

    // -- connect --

    private void setConnected() throws IOException {
        synchronized (stateLock) {
            state = ST_CONNECTED;
            localAddress = Net.localAddress(fd);
            remoteAddress = pendingRemote;
        }
    }

    private void finishConnect(PendingFuture<Void,Object> result,
                               boolean invokeDirect)
    {
        Throwable e = null;
        try {
            begin();
            checkConnect(fdVal);
            setConnected();
            result.setResult(null);
        } catch (Throwable x) {
            if (x instanceof ClosedChannelException)
                x = new AsynchronousCloseException();
            e = x;
        } finally {
            end();
        }
        if (e != null) {
            // close channel if connection cannot be established
            try {
                close();
            } catch (IOException ignore) { }
            result.setFailure(e);
        }
        if (invokeDirect) {
            Invoker.invoke(result.handler(), result);
        } else {
            Invoker.invokeIndirectly(result.handler(), result);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public <A> Future<Void> connect(SocketAddress remote,
                                    A attachment,
                                    CompletionHandler<Void,? super A> handler)
    {
        if (!isOpen()) {
            CompletedFuture<Void,A> result = CompletedFuture
                .withFailure(this, new ClosedChannelException(), attachment);
            Invoker.invoke(handler, result);
            return result;
        }

        InetSocketAddress isa = Net.checkAddress(remote);

        // permission check
        SecurityManager sm = System.getSecurityManager();
        if (sm != null)
            sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());

        // check and set state
A
alanb 已提交
309
        boolean notifyBeforeTcpConnect;
310 311 312 313 314 315 316
        synchronized (stateLock) {
            if (state == ST_CONNECTED)
                throw new AlreadyConnectedException();
            if (state == ST_PENDING)
                throw new ConnectionPendingException();
            state = ST_PENDING;
            pendingRemote = remote;
A
alanb 已提交
317
            notifyBeforeTcpConnect = (localAddress == null);
318 319 320 321 322 323
        }

        AbstractFuture<Void,A> result = null;
        Throwable e = null;
        try {
            begin();
A
alanb 已提交
324 325 326
            // notify hook if unbound
            if (notifyBeforeTcpConnect)
                NetHooks.beforeTcpConnect(fd, isa.getAddress(), isa.getPort());
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
            int n = Net.connect(fd, isa.getAddress(), isa.getPort());
            if (n == IOStatus.UNAVAILABLE) {
                // connection could not be established immediately
                result = new PendingFuture<Void,A>(this, handler, attachment, OpType.CONNECT);
                synchronized (updateLock) {
                    this.pendingConnect = (PendingFuture<Void,Object>)result;
                    updateEvents();
                }
                return result;
            }
            setConnected();
            result = CompletedFuture.withResult(this, null, attachment);
        } catch (Throwable x) {
            if (x instanceof ClosedChannelException)
                x = new AsynchronousCloseException();
            e = x;
        } finally {
            end();
        }

        // close channel if connect fails
        if (e != null) {
            try {
                close();
            } catch (IOException ignore) { }
            result = CompletedFuture.withFailure(this, e, attachment);
        }

        Invoker.invoke(handler, result);
        return result;
    }

    // -- read --

    @SuppressWarnings("unchecked")
    private void finishRead(PendingFuture<Number,Object> result,
                            boolean invokeDirect)
    {
        int n = -1;
        PendingFuture<Number,Object> pending = null;
        try {
            begin();

            ByteBuffer[] dsts = readBuffers;
            if (dsts.length == 1) {
                n = IOUtil.read(fd, dsts[0], -1, nd, null);
            } else {
                n = (int)IOUtil.read(fd, dsts, nd);
            }
            if (n == IOStatus.UNAVAILABLE) {
                // spurious wakeup, is this possible?
                pending = result;
                return;
            }

            // allow buffer(s) to be GC'ed.
            readBuffers = null;

            // allow another read to be initiated
            boolean wasScatteringRead = scatteringRead;
            enableReading();

            // result is Integer or Long
            if (wasScatteringRead) {
                result.setResult(Long.valueOf(n));
            } else {
                result.setResult(Integer.valueOf(n));
            }

        } catch (Throwable x) {
            enableReading();
            if (x instanceof ClosedChannelException)
                x = new AsynchronousCloseException();
            result.setFailure(x);
        } finally {
            // restart poll in case of concurrent write
            synchronized (updateLock) {
                if (pending != null)
                    this.pendingRead = pending;
                updateEvents();
            }
            end();
        }

        if (invokeDirect) {
            Invoker.invoke(result.handler(), result);
        } else {
            Invoker.invokeIndirectly(result.handler(), result);
        }
    }

    private Runnable readTimeoutTask = new Runnable() {
        public void run() {
            PendingFuture<Number,Object> result = grabPendingRead();
            if (result == null)
                return;     // already completed

            // kill further reading before releasing waiters
            enableReading(true);

            // set completed and invoke handler
            result.setFailure(new InterruptedByTimeoutException());
            Invoker.invokeIndirectly(result.handler(), result);
        }
    };

    /**
     * Initiates a read or scattering read operation
     */
    @Override
    @SuppressWarnings("unchecked")
    <V extends Number,A> Future<V> readImpl(ByteBuffer[] dsts,
                                            boolean isScatteringRead,
                                            long timeout,
                                            TimeUnit unit,
                                            A attachment,
                                            CompletionHandler<V,? super A> handler)
    {
        // A synchronous read is not attempted if disallowed by system property
        // or, we are using a fixed thread pool and the completion handler may
        // not be invoked directly (because the thread is not a pooled thread or
        // there are too many handlers on the stack).
        Invoker.GroupAndInvokeCount myGroupAndInvokeCount = null;
        boolean invokeDirect = false;
        boolean attemptRead = false;
        if (!disableSynchronousRead) {
            myGroupAndInvokeCount = Invoker.getGroupAndInvokeCount();
            invokeDirect = Invoker.mayInvokeDirect(myGroupAndInvokeCount, port);
            attemptRead = (handler == null) || invokeDirect ||
                !port.isFixedThreadPool();  // okay to attempt read with user thread pool
        }

        AbstractFuture<V,A> result;
        try {
            begin();

            int n;
            if (attemptRead) {
                if (isScatteringRead) {
                    n = (int)IOUtil.read(fd, dsts, nd);
                } else {
                    n = IOUtil.read(fd, dsts[0], -1, nd, null);
                }
            } else {
                n = IOStatus.UNAVAILABLE;
            }

            if (n == IOStatus.UNAVAILABLE) {
                result = new PendingFuture<V,A>(this, handler, attachment, OpType.READ);

                // update evetns so that read will complete asynchronously
                synchronized (updateLock) {
                    this.readBuffers = dsts;
                    this.scatteringRead = isScatteringRead;
                    this.pendingRead = (PendingFuture<Number,Object>)result;
                    updateEvents();
                }

                // schedule timeout
                if (timeout > 0L) {
                    Future<?> timeoutTask =
                        port.schedule(readTimeoutTask, timeout, unit);
                    ((PendingFuture<V,A>)result).setTimeoutTask(timeoutTask);
                }
                return result;
            }

            // data available
            enableReading();

            // result type is Long or Integer
            if (isScatteringRead) {
                result = (CompletedFuture<V,A>)CompletedFuture
                    .withResult(this, Long.valueOf(n), attachment);
            } else {
                result = (CompletedFuture<V,A>)CompletedFuture
                    .withResult(this, Integer.valueOf(n), attachment);
            }
        } catch (Throwable x) {
            enableReading();
            if (x instanceof ClosedChannelException)
                x = new AsynchronousCloseException();
            result = CompletedFuture.withFailure(this, x, attachment);
        } finally {
            end();
        }

        if (invokeDirect) {
            Invoker.invokeDirect(myGroupAndInvokeCount, handler, result);
        } else {
            Invoker.invokeIndirectly(handler, result);
        }
        return result;
    }

    // -- write --

    private void finishWrite(PendingFuture<Number,Object> result,
                             boolean invokeDirect)
    {
        PendingFuture<Number,Object> pending = null;
        try {
            begin();

            ByteBuffer[] srcs = writeBuffers;
            int n;
            if (srcs.length == 1) {
                n = IOUtil.write(fd, srcs[0], -1, nd, null);
            } else {
                n = (int)IOUtil.write(fd, srcs, nd);
            }
            if (n == IOStatus.UNAVAILABLE) {
                // spurious wakeup, is this possible?
                pending = result;
                return;
            }

            // allow buffer(s) to be GC'ed.
            writeBuffers = null;

            // allow another write to be initiated
            boolean wasGatheringWrite = gatheringWrite;
            enableWriting();

            // result is a Long or Integer
            if (wasGatheringWrite) {
                result.setResult(Long.valueOf(n));
            } else {
                result.setResult(Integer.valueOf(n));
            }

        } catch (Throwable x) {
            enableWriting();
            if (x instanceof ClosedChannelException)
                x = new AsynchronousCloseException();
            result.setFailure(x);
        } finally {
            // restart poll in case of concurrent read
            synchronized (this) {
                if (pending != null)
                    this.pendingWrite = pending;
                updateEvents();
            }
            end();
        }
        if (invokeDirect) {
            Invoker.invoke(result.handler(), result);
        } else {
            Invoker.invokeIndirectly(result.handler(), result);
        }
    }

    private Runnable writeTimeoutTask = new Runnable() {
        public void run() {
            PendingFuture<Number,Object> result = grabPendingWrite();
            if (result == null)
                return;     // already completed

            // kill further writing before releasing waiters
            enableWriting(true);

            // set completed and invoke handler
            result.setFailure(new InterruptedByTimeoutException());
            Invoker.invokeIndirectly(result.handler(), result);
        }
    };

    /**
     * Initiates a read or scattering read operation
     */
    @Override
    @SuppressWarnings("unchecked")
    <V extends Number,A> Future<V> writeImpl(ByteBuffer[] srcs,
                                             boolean isGatheringWrite,
                                             long timeout,
                                             TimeUnit unit,
                                             A attachment,
                                             CompletionHandler<V,? super A> handler)
    {
        Invoker.GroupAndInvokeCount myGroupAndInvokeCount =
            Invoker.getGroupAndInvokeCount();
        boolean invokeDirect = Invoker.mayInvokeDirect(myGroupAndInvokeCount, port);
        boolean attemptWrite = (handler == null) || invokeDirect ||
            !port.isFixedThreadPool();  // okay to attempt read with user thread pool

        AbstractFuture<V,A> result;
        try {
            begin();

            int n;
            if (attemptWrite) {
                if (isGatheringWrite) {
                    n = (int)IOUtil.write(fd, srcs, nd);
                } else {
                    n = IOUtil.write(fd, srcs[0], -1, nd, null);
                }
            } else {
                n = IOStatus.UNAVAILABLE;
            }

            if (n == IOStatus.UNAVAILABLE) {
                result = new PendingFuture<V,A>(this, handler, attachment, OpType.WRITE);

                // update evetns so that read will complete asynchronously
                synchronized (updateLock) {
                    this.writeBuffers = srcs;
                    this.gatheringWrite = isGatheringWrite;
                    this.pendingWrite = (PendingFuture<Number,Object>)result;
                    updateEvents();
                }

                // schedule timeout
                if (timeout > 0L) {
                    Future<?> timeoutTask =
                        port.schedule(writeTimeoutTask, timeout, unit);
                    ((PendingFuture<V,A>)result).setTimeoutTask(timeoutTask);
                }
                return result;
            }

            // data available
            enableWriting();
            if (isGatheringWrite) {
                result = (CompletedFuture<V,A>)CompletedFuture
                    .withResult(this, Long.valueOf(n), attachment);
            } else {
                result = (CompletedFuture<V,A>)CompletedFuture
                    .withResult(this, Integer.valueOf(n), attachment);
            }
        } catch (Throwable x) {
            enableWriting();
            if (x instanceof ClosedChannelException)
                x = new AsynchronousCloseException();
            result = CompletedFuture.withFailure(this, x, attachment);
        } finally {
            end();
        }
        if (invokeDirect) {
            Invoker.invokeDirect(myGroupAndInvokeCount, handler, result);
        } else {
            Invoker.invokeIndirectly(handler, result);
        }
        return result;
    }

    // -- Native methods --

    private static native void checkConnect(int fdVal) throws IOException;

    static {
        Util.load();
    }
}