001    /**
002     * Copyright (C) 2012 FuseSource, Inc.
003     * http://fusesource.com
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    
018    package org.fusesource.hawtdispatch.example;
019    
020    import org.fusesource.hawtdispatch.*;
021    
022    import java.util.concurrent.CountDownLatch;
023    import java.util.concurrent.Semaphore;
024    
025    import static org.fusesource.hawtdispatch.Dispatch.*;
026    
027    /**
028     * <p>
029     * </p>
030     *
031     * @author <a href="http://hiramchirino.com">Hiram Chirino</a>
032     */
033    public class CustomDispatchSourceJava {
034        public static void main(String[] args) throws Exception {
035            run();
036        }
037    
038        public static void run() throws Exception {
039            final Semaphore done = new Semaphore(1-(1000*1000));
040    
041            DispatchQueue queue = createQueue();
042            final CustomDispatchSource<Integer, Integer> source = createSource(EventAggregators.INTEGER_ADD, queue);
043            source.setEventHandler(new Task() {
044                public void run() {
045                    int count = source.getData();
046                    System.out.println("got: " + count);
047                    done.release(count);
048                }
049            });
050            source.resume();
051    
052            // Produce 1,000,000 concurrent merge events
053            for (int i = 0; i < 1000; i++) {
054                getGlobalQueue().execute(new Task() {
055                    public void run() {
056                        for (int j = 0; j < 1000; j++) {
057                            source.merge(1);
058                        }
059                    }
060                });
061            }
062    
063            // Wait for all the event to arrive.
064            done.acquire();
065        }
066    }