File: Identity.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (177 lines) | stat: -rw-r--r-- 7,158 bytes parent folder | download | duplicates (16)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
/*
 * Copyright (c) 2008, 2016, Oracle and/or its affiliates. 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.
 *
 * 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,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/* @test
 * @bug 4607272 6842687
 * @summary Unit test for AsynchronousChannelGroup
 * @key randomness
 */

import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.io.IOException;

/**
 * Tests that the completion handler is invoked by a thread with
 * the expected identity.
 */

public class Identity {
    static final Random rand = new Random();
    static final CountDownLatch done = new CountDownLatch(1);
    static final AtomicBoolean failed = new AtomicBoolean(false);

    static void fail(String msg) {
        failed.set(true);
        done.countDown();
        throw new RuntimeException(msg);
    }

    // thread-local identifies the thread
    private static final ThreadLocal<Integer> myGroup =
        new ThreadLocal<Integer>() {
            @Override protected Integer initialValue() {
                return Integer.valueOf(-1);
            }
        };

    // creates a ThreadFactory that constructs groups with the given identity
    static final ThreadFactory createThreadFactory(final int groupId) {
        return new ThreadFactory() {
            @Override
            public Thread newThread(final Runnable r) {
                Thread t = new Thread(new Runnable() {
                    public void run() {
                        myGroup.set(groupId);
                        r.run();
                    }});
                t.setDaemon(true);
                return t;
            }
        };
    }

    public static void main(String[] args) throws Exception {
        // create 3-10 channels, each in its own group
        final int groupCount = 3 + rand.nextInt(8);
        final AsynchronousChannelGroup[] groups = new AsynchronousChannelGroup[groupCount];
        final AsynchronousSocketChannel[] channels = new AsynchronousSocketChannel[groupCount];

        // create listener to accept connections
        try (final AsynchronousServerSocketChannel listener =
                AsynchronousServerSocketChannel.open()) {

            listener.bind(new InetSocketAddress(0));
            listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
                public void completed(final AsynchronousSocketChannel ch, Void att) {
                    listener.accept((Void)null, this);
                    final ByteBuffer buf = ByteBuffer.allocate(100);
                    ch.read(buf, ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
                        public void completed(Integer bytesRead, AsynchronousSocketChannel ch) {
                            if (bytesRead < 0) {
                                try { ch.close(); } catch (IOException ignore) { }
                            } else {
                                buf.clear();
                                ch.read(buf, ch, this);
                            }
                        }
                        public void failed(Throwable exc, AsynchronousSocketChannel ch) {
                            try { ch.close(); } catch (IOException ignore) { }
                        }
                    });
                }
                public void failed(Throwable exc, Void att) {
                }
            });
            int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
            SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), port);

            for (int i=0; i<groupCount; i++) {
                ThreadFactory factory = createThreadFactory(i);
                AsynchronousChannelGroup group;
                if (rand.nextBoolean()) {
                    int nThreads = 1 + rand.nextInt(10);
                    group = AsynchronousChannelGroup.withFixedThreadPool(nThreads, factory);
                } else {
                    ExecutorService pool = Executors.newCachedThreadPool(factory);
                    group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
                }
                groups[i] = group;

                // create channel in group and connect it to the server
                AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(group);
                ch.connect(sa).get();
                channels[i] = ch;
            }

            // randomly write to each channel, ensuring that the completion handler
            // is always invoked by a thread with the right identity.
            final AtomicInteger writeCount = new AtomicInteger(100);
            channels[0].write(getBuffer(), 0, new CompletionHandler<Integer,Integer>() {
                public void completed(Integer bytesWritten, Integer groupId) {
                    if (bytesWritten != 1)
                        fail("Expected 1 byte to be written");
                    if (!myGroup.get().equals(groupId))
                        fail("Handler invoked by thread with the wrong identity");
                    if (writeCount.decrementAndGet() > 0) {
                        int id = rand.nextInt(groupCount);
                        channels[id].write(getBuffer(), id, this);
                    } else {
                        done.countDown();
                    }
                }
                public void failed(Throwable exc, Integer groupId) {
                    fail(exc.getMessage());
                }
            });

            // wait until done
            done.await();
        } finally {
            // clean-up
            for (AsynchronousSocketChannel ch: channels)
                ch.close();
            for (AsynchronousChannelGroup group: groups)
                group.shutdownNow();

            if (failed.get())
                throw new RuntimeException("Test failed - see log for details");
        }
    }

    static ByteBuffer getBuffer() {
        ByteBuffer buf;
        if (rand.nextBoolean()) {
            buf = ByteBuffer.allocateDirect(1);
        } else {
            buf = ByteBuffer.allocate(1);
        }
        buf.put((byte)0);
        buf.flip();
        return buf;
    }
}