001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.examples.utils.wake; 020 021import org.apache.reef.wake.EventHandler; 022 023import java.util.ArrayList; 024import java.util.List; 025 026/** 027 * An EventHandler that blocks until a set number of Events has been received. 028 * Once they have been received, the downstream event handler is called with an 029 * Iterable of the events spooled. 030 * 031 * @param <T> 032 */ 033public final class BlockingEventHandler<T> implements EventHandler<T> { 034 035 private final int expectedSize; 036 private List<T> events = new ArrayList<>(); 037 private final EventHandler<Iterable<T>> destination; 038 039 public BlockingEventHandler(final int expectedSize, final EventHandler<Iterable<T>> destination) { 040 this.expectedSize = expectedSize; 041 this.destination = destination; 042 } 043 044 @Override 045 public void onNext(final T event) { 046 if (this.isComplete()) { 047 throw new IllegalStateException("Received more Events than expected"); 048 } 049 this.events.add(event); 050 if (this.isComplete()) { 051 this.destination.onNext(events); 052 this.reset(); 053 } 054 } 055 056 private boolean isComplete() { 057 return this.events.size() >= expectedSize; 058 } 059 060 private void reset() { 061 this.events = new ArrayList<>(); 062 } 063}