001    /**
002     *  Copyright (C) 2009, Progress Software Corporation and/or its
003     * subsidiaries or affiliates.  All rights reserved.
004     *
005     * Licensed under the Apache License, Version 2.0 (the "License");
006     * you may not use this file except in compliance with the License.
007     * You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.fusesource.hawtdispatch.example;
018    
019    import org.fusesource.hawtdispatch.*;
020    
021    import java.util.concurrent.CountDownLatch;
022    import java.util.concurrent.Semaphore;
023    
024    import static org.fusesource.hawtdispatch.Dispatch.*;
025    
026    /**
027     * <p>
028     * </p>
029     *
030     * @author <a href="http://hiramchirino.com">Hiram Chirino</a>
031     */
032    public class CustomDispatchSourceJava {
033        public static void main(String[] args) throws Exception {
034            run();
035        }
036    
037        public static void run() throws Exception {
038            final Semaphore done = new Semaphore(1-(1000*1000));
039    
040            DispatchQueue queue = createQueue();
041            final CustomDispatchSource<Integer, Integer> source = createSource(EventAggregators.INTEGER_ADD, queue);
042            source.setEventHandler(new Runnable() {
043                public void run() {
044                    int count = source.getData();
045                    System.out.println("got: " + count);
046                    done.release(count);
047                }
048            });
049            source.resume();
050    
051            // Produce 1,000,000 concurrent merge events
052            for (int i = 0; i < 1000; i++) {
053                getGlobalQueue().execute(new Runnable() {
054                    public void run() {
055                        for (int j = 0; j < 1000; j++) {
056                            source.merge(1);
057                        }
058                    }
059                });
060            }
061    
062            // Wait for all the event to arrive.
063            done.acquire();
064        }
065    }