SharingThreadTest.java 12.7 KB
Newer Older
1
/*
X
xdono 已提交
2
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
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
 * 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 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.
 */

/*
 * @test SharingThreadTest.java 1.3 08/01/22
 * @bug 5108776
 * @summary Basic test for EventClient to see internal thread management.
 * @author Shanliang JIANG
 * @run clean SharingThreadTest
 * @run build SharingThreadTest
 * @run main SharingThreadTest
 */

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.event.EventClient;
import javax.management.event.EventClientDelegate;
import javax.management.event.EventClientDelegateMBean;
import javax.management.event.FetchingEventRelay;
import javax.management.event.RMIPushEventRelay;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;


public class SharingThreadTest {

    private static MBeanServer mbeanServer = MBeanServerFactory.createMBeanServer();
    private static ObjectName emitter;
    private static NotificationEmitter emitterImpl;
    private static JMXServiceURL url;
    private static JMXConnectorServer server;


    private static int toSend = 10;
    private static final long bigWaiting = 6000;
    private static int counter = 0;
    private static int jobs = 10;
    private static int endedJobs = 0;

73 74
    private static volatile String failure;

75
    private static Executor sharedExecutor = new ThreadPoolExecutor(0, 1, 1000,
76
            TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(jobs));
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
            //Executors.newFixedThreadPool(1);

    public static void main(String[] args) throws Exception {
        System.out.println(">>> Test on sharing threads for multiple EventClient.");

        // for 1.5
        if (System.getProperty("java.version").startsWith("1.5") &&
                !mbeanServer.isRegistered(EventClientDelegateMBean.OBJECT_NAME)) {
            System.out.print("Working on "+System.getProperty("java.version")+
                    " register "+EventClientDelegateMBean.OBJECT_NAME);

            mbeanServer.registerMBean(EventClientDelegate.
                    getEventClientDelegate(mbeanServer),
                    EventClientDelegateMBean.OBJECT_NAME);

            sharedExecutor = new ThreadPoolExecutor(1, 1, 1000,
93
            TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(jobs));
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
        }

        emitter = new ObjectName("Default:name=NotificationEmitter");
        emitterImpl = new NotificationEmitter();
        mbeanServer.registerMBean(emitterImpl, emitter);

        String[] types = new String[]{"PushEventRelay", "FetchingEventRelay"};
        String[] protos = new String[]{"rmi", "iiop", "jmxmp"};
        for (String prot : protos) {
            url = new JMXServiceURL(prot, null, 0);

            try {
                server =
                        JMXConnectorServerFactory.newJMXConnectorServer(url,
                        null, mbeanServer);
                server.start();
            } catch (Exception e) {
                System.out.println(">>> Skip "+prot+", not support.");
                continue;
            }

            url = server.getAddress();

            // noise
            Thread noise = new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        emitterImpl.sendNotif(1, null);
                        try {
                            Thread.sleep(10);
                        } catch (Exception e) {
                            // OK
                        }
                    }
                }
            });
            noise.setDaemon(true);
            noise.start();

            try {
                for (String type: types) {
                    System.out.println("\n\n>>> Testing "+type+" on "+url+" ...");
136 137 138 139 140 141
                    JMXConnector conn = newConn();
                    try {
                        testType(type, conn);
                    } finally {
                        conn.close();
                        System.out.println(">>> Testing "+type+" on "+url+" ... done");
142 143 144 145 146 147 148 149
                    }
                }
            } finally {
                server.stop();
            }
        }
    }

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
    private static void testType(String type, JMXConnector conn) throws Exception {
        Thread[] threads = new Thread[jobs];
        for (int i=0; i<jobs; i++) {
            threads[i] = new Thread(new Job(type, conn));
            threads[i].setDaemon(true);
            threads[i].start();
        }

        // to wait
        long toWait = bigWaiting*jobs;
        long stopTime = System.currentTimeMillis() + toWait;

        synchronized(SharingThreadTest.class) {
            while (endedJobs < jobs && toWait > 0 && failure == null) {
                SharingThreadTest.class.wait(toWait);
                toWait = stopTime - System.currentTimeMillis();
            }
        }

        if (endedJobs != jobs && failure == null) {
            throw new RuntimeException("Need to set bigger waiting timeout?");
        }

        endedJobs = 0;
    }

176
    public static class Job implements Runnable {
177
        public Job(String type, JMXConnector conn) {
178
            this.type = type;
179
            this.conn = conn;
180 181 182
        }
        public void run() {
            try {
183
                test(type, conn);
184 185 186 187 188 189 190 191

                synchronized(SharingThreadTest.class) {
                    endedJobs++;
                    if (endedJobs>=jobs) {
                        SharingThreadTest.class.notify();
                    }
                }
            } catch (RuntimeException re) {
192
                re.printStackTrace(System.out);
193 194 195 196 197 198 199
                throw re;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        private final String type;
200
        private final JMXConnector conn;
201 202
    }

203
    private static void test(String type, JMXConnector conn) throws Exception {
204 205 206 207 208 209
        String id = getId();

        Listener listener = new Listener(id);
        Filter filter = new Filter(id);

        //newConn();
210
        EventClient ec = newEventClient(type, conn);
211 212 213 214 215 216 217 218 219 220 221 222

        System.out.println(">>> ("+id+") To receive notifications "+toSend);
        ec.addNotificationListener(emitter,
                listener, filter, null);

        emitterImpl.sendNotif(toSend, id);
        listener.waitNotifs(bigWaiting, toSend);
        if (listener.received != toSend) {
            throw new RuntimeException(">>> ("+id+") Expected to receive: "
                    +toSend+", but got: "+listener.received);
        }

223
        ec.close();
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    }

//--------------------------
// private classes
//--------------------------

    private static class Listener implements NotificationListener {
        public Listener(String id) {
            this.id = id;
        }
        public void handleNotification(Notification notif, Object handback) {
            if (!id.equals(notif.getUserData())) {
                System.out.println("("+id+") Filter error, my id is: "+id+
                        ", but got "+notif.getUserData());
                System.exit(1);
            }
            System.out.println("("+id+") received "+notif.getSequenceNumber());
241
            synchronized (this) {
242 243 244 245 246
                received++;

                if (sequenceNB < 0) {
                    sequenceNB = notif.getSequenceNumber();
                } else if(++sequenceNB != notif.getSequenceNumber()) {
247
                    fail("(" + id + ") Wrong sequence number, expected: "
248 249
                            +sequenceNB+", but got: "+notif.getSequenceNumber());
                }
250
                if (received >= toSend || failure != null) {
251 252 253 254 255 256 257 258 259
                    this.notify();
                }
            }
        }

        public void waitNotifs(long timeout, int nb) throws Exception {
            long toWait = timeout;
            long stopTime = System.currentTimeMillis() + timeout;
            synchronized(this) {
260
                while (received < nb && toWait > 0 && failure == null) {
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
                    this.wait(toWait);
                    toWait = stopTime - System.currentTimeMillis();
                }
            }
        }

        private String id;
        private int received = 0;

        private long sequenceNB = -1;
    }

    private static class Filter implements NotificationFilter {
        public Filter(String id) {
            this.id = id;
        }

        public boolean isNotificationEnabled(Notification n) {
            return id.equals(n.getUserData());
        }
        private String id;
    }

    public static class NotificationEmitter extends NotificationBroadcasterSupport
            implements NotificationEmitterMBean {

        /**
         * Send Notification objects.
         *
         * @param nb The number of notifications to send
         */
        public void sendNotif(int nb, String userData) {
            new Thread(new SendJob(nb, userData)).start();
        }

        private class SendJob implements Runnable {
            public SendJob(int nb, String userData) {
                this.nb = nb;
                this.userData = userData;
            }

            public void run() {
                if (userData != null) {
                    System.out.println(">>> ("+userData+") sending "+nb);
                }
306
                long sequenceNumber = 0;
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
                for (int i = 0; i<nb; i++) {
                    Notification notif = new Notification(myType, emitter,
                            sequenceNumber++);
                    notif.setUserData(userData);
                    sendNotification(notif);
                    Thread.yield();
                    try {
                        Thread.sleep(1);
                    } catch (Exception e) {}
                }
                if (userData != null) {
                    System.out.println(">>> ("+userData+") sending done");
                }
            }
            private int nb;
            private String userData;
        }
        private final String myType = "notification.my_notification";
    }

    public interface NotificationEmitterMBean {
        public void sendNotif(int nb, String userData);
    }

331 332
    private static JMXConnector newConn() throws IOException {
        return JMXConnectorFactory.connect(url);
333 334
    }

335 336
    private static EventClient newEventClient(String type, JMXConnector conn)
            throws Exception {
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        EventClientDelegateMBean proxy =
                EventClientDelegate.getProxy(conn.getMBeanServerConnection());
        if (type.equals("PushEventRelay")) {
            return new EventClient(proxy,
                    new RMIPushEventRelay(proxy), sharedExecutor, null, 600);
        } else if (type.equals("FetchingEventRelay")) {
            return new EventClient(proxy,
                    new FetchingEventRelay(proxy,
                    FetchingEventRelay.DEFAULT_BUFFER_SIZE,
                    10,
                    FetchingEventRelay.DEFAULT_MAX_NOTIFICATIONS,
                    sharedExecutor),
                    null, null, 600);
        } else {
            throw new RuntimeException("Wrong event client type: "+type);
        }
    }

    private static String getId() {
        synchronized(SharingThreadTest.class) {
            return String.valueOf(counter++);
        }
    }
360 361 362 363 364

    private static void fail(String msg) {
        System.out.println("FAIL: " + msg);
        failure = msg;
    }
365
}