You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by uc...@apache.org on 2015/02/23 10:23:12 UTC

[3/3] flink git commit: [FLINK-1505] [distributed runtime] Separate reader API from result consumption

[FLINK-1505] [distributed runtime] Separate reader API from result consumption

This closes #428.


Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/5232c56b
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/5232c56b
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/5232c56b

Branch: refs/heads/master
Commit: 5232c56b13b7e13e2cf10dbe818c221f5557426d
Parents: a911559
Author: Ufuk Celebi <uc...@apache.org>
Authored: Tue Feb 10 15:05:44 2015 +0100
Committer: Ufuk Celebi <uc...@apache.org>
Committed: Mon Feb 23 10:22:51 2015 +0100

----------------------------------------------------------------------
 .../flink/runtime/execution/Environment.java    |  18 +-
 .../runtime/execution/RuntimeEnvironment.java   |  37 +-
 .../runtime/io/network/NetworkEnvironment.java  |  20 +-
 .../io/network/api/TaskEventHandler.java        |  59 +++
 .../io/network/api/reader/AbstractReader.java   | 146 ++++++
 .../api/reader/AbstractRecordReader.java        |  73 +--
 .../io/network/api/reader/BufferReader.java     | 484 +------------------
 .../io/network/api/reader/BufferReaderBase.java |  92 ----
 .../network/api/reader/MutableRecordReader.java |   5 +-
 .../io/network/api/reader/ReaderBase.java       |  15 +-
 .../io/network/api/reader/RecordReader.java     |   5 +-
 .../network/api/reader/UnionBufferReader.java   | 298 ------------
 .../io/network/api/writer/BufferWriter.java     |   6 +-
 .../partition/consumer/BufferOrEvent.java       |  74 +++
 .../partition/consumer/InputChannel.java        |  26 +-
 .../network/partition/consumer/InputGate.java   |  40 ++
 .../partition/consumer/LocalInputChannel.java   |  35 +-
 .../partition/consumer/RemoteInputChannel.java  |  27 +-
 .../partition/consumer/SingleInputGate.java     | 397 +++++++++++++++
 .../partition/consumer/UnionInputGate.java      | 205 ++++++++
 .../partition/consumer/UnknownInputChannel.java |  28 +-
 .../task/IterationSynchronizationSinkTask.java  |   4 +-
 .../flink/runtime/operators/DataSinkTask.java   |   7 +-
 .../runtime/operators/RegularPactTask.java      |  22 +-
 .../apache/flink/runtime/taskmanager/Task.java  |   8 +-
 .../util/event/EventNotificationHandler.java    |  57 ---
 .../flink/runtime/taskmanager/TaskManager.scala |   2 +-
 .../network/api/reader/AbstractReaderTest.java  | 186 +++++++
 .../io/network/api/reader/BufferReaderTest.java | 190 ++------
 .../IteratorWrappingMockSingleInputGate.java    | 103 ++++
 .../io/network/api/reader/MockBufferReader.java | 126 -----
 .../api/reader/MockIteratorBufferReader.java    | 107 ----
 .../api/reader/UnionBufferReaderTest.java       | 139 ------
 .../api/serialization/EventSerializerTest.java  |  43 +-
 .../io/network/partition/MockConsumer.java      | 100 ----
 .../partition/MockNotificationListener.java     |  52 --
 .../io/network/partition/MockProducer.java      | 106 ----
 .../partition/consumer/SingleInputGateTest.java | 103 ++++
 .../partition/consumer/UnionInputGateTest.java  |  62 +++
 .../queue/PipelinedPartitionQueueTest.java      |   6 +-
 .../runtime/io/network/util/MockConsumer.java   | 100 ++++
 .../io/network/util/MockInputChannel.java       | 130 +++++
 .../network/util/MockNotificationListener.java  |  52 ++
 .../runtime/io/network/util/MockProducer.java   | 106 ++++
 .../io/network/util/MockSingleInputGate.java    | 137 ++++++
 .../runtime/io/network/util/TestTaskEvent.java  |  64 +++
 .../runtime/operators/DataSinkTaskTest.java     |   6 +-
 .../operators/testutils/MockEnvironment.java    |  22 +-
 .../operators/testutils/TaskTestBase.java       |  10 +-
 .../event/EventNotificationHandlerTest.java     |  97 ----
 .../util/event/TaskEventHandlerTest.java        |  98 ++++
 .../apache/flink/runtime/jobmanager/Tasks.scala |  21 +-
 .../api/streamvertex/CoStreamVertex.java        |  23 +-
 .../api/streamvertex/InputHandler.java          |  10 +-
 .../flink/streaming/io/CoRecordReader.java      | 101 ++--
 .../streaming/io/IndexedMutableReader.java      |  10 +-
 .../streaming/io/IndexedReaderIterator.java     |  17 +-
 .../flink/streaming/util/MockContext.java       |   5 -
 .../runtime/NetworkStackThroughputITCase.java   |   4 +-
 59 files changed, 2374 insertions(+), 2152 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
index c45a941..fc2d2c8 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
@@ -23,8 +23,8 @@ import org.apache.flink.configuration.Configuration;
 import org.apache.flink.core.fs.Path;
 import org.apache.flink.runtime.broadcast.BroadcastVariableManager;
 import org.apache.flink.runtime.io.disk.iomanager.IOManager;
-import org.apache.flink.runtime.io.network.api.reader.BufferReader;
 import org.apache.flink.runtime.io.network.api.writer.BufferWriter;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
 import org.apache.flink.runtime.jobgraph.JobGraph;
 import org.apache.flink.runtime.jobgraph.JobID;
 import org.apache.flink.runtime.jobgraph.JobVertexID;
@@ -50,10 +50,10 @@ public interface Environment {
 	 * @return the ID of the job from the original job graph
 	 */
 	JobID getJobID();
-	
+
 	/**
 	 * Gets the ID of the jobVertex that this task corresponds to.
-	 * 
+	 *
 	 * @return The JobVertexID of this task.
 	 */
 	JobVertexID getJobVertexId();
@@ -130,18 +130,12 @@ public interface Environment {
 
 	BroadcastVariableManager getBroadcastVariableManager();
 
-	// ------------------------------------------------------------------------
-	// Runtime result writers and readers
-	// ------------------------------------------------------------------------
-	// The environment sets up buffer-oriented writers and readers, which the
-	// user can use to produce and consume results.
-	// ------------------------------------------------------------------------
-
 	BufferWriter getWriter(int index);
 
 	BufferWriter[] getAllWriters();
 
-	BufferReader getReader(int index);
+	InputGate getInputGate(int index);
+
+	InputGate[] getAllInputGates();
 
-	BufferReader[] getAllReaders();
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/RuntimeEnvironment.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/execution/RuntimeEnvironment.java b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/RuntimeEnvironment.java
index 85c0e8e..4fa4907 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/execution/RuntimeEnvironment.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/RuntimeEnvironment.java
@@ -27,9 +27,10 @@ import org.apache.flink.runtime.deployment.PartitionDeploymentDescriptor;
 import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor;
 import org.apache.flink.runtime.io.disk.iomanager.IOManager;
 import org.apache.flink.runtime.io.network.NetworkEnvironment;
-import org.apache.flink.runtime.io.network.api.reader.BufferReader;
 import org.apache.flink.runtime.io.network.api.writer.BufferWriter;
 import org.apache.flink.runtime.io.network.partition.IntermediateResultPartition;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
+import org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate;
 import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
 import org.apache.flink.runtime.jobgraph.JobID;
 import org.apache.flink.runtime.jobgraph.JobVertexID;
@@ -95,9 +96,9 @@ public class RuntimeEnvironment implements Environment, Runnable {
 
 	private final BufferWriter[] writers;
 
-	private final BufferReader[] readers;
+	private final SingleInputGate[] inputGates;
 
-	private final Map<IntermediateDataSetID, BufferReader> readersById = new HashMap<IntermediateDataSetID, BufferReader>();
+	private final Map<IntermediateDataSetID, SingleInputGate> inputGatesById = new HashMap<IntermediateDataSetID, SingleInputGate>();
 
 	public RuntimeEnvironment(
 			ActorRef jobManager, Task owner, TaskDeploymentDescriptor tdd, ClassLoader userCodeClassLoader,
@@ -128,15 +129,18 @@ public class RuntimeEnvironment implements Environment, Runnable {
 			// Consumed intermediate result partitions
 			final List<PartitionConsumerDeploymentDescriptor> consumedPartitions = tdd.getConsumedPartitions();
 
-			this.readers = new BufferReader[consumedPartitions.size()];
+			this.inputGates = new SingleInputGate[consumedPartitions.size()];
 
-			for (int i = 0; i < readers.length; i++) {
-				readers[i] = BufferReader.create(this, networkEnvironment, consumedPartitions.get(i));
+			for (int i = 0; i < inputGates.length; i++) {
+				inputGates[i] = SingleInputGate.create(networkEnvironment, consumedPartitions.get(i));
 
-				// The readers are organized by key for task updates/channel updates at runtime
-				readersById.put(readers[i].getConsumedResultId(), readers[i]);
+				// The input gates are organized by key for task updates/channel updates at runtime
+				inputGatesById.put(inputGates[i].getConsumedResultId(), inputGates[i]);
 			}
 
+			this.jobConfiguration = tdd.getJobConfiguration();
+			this.taskConfiguration = tdd.getTaskConfiguration();
+
 			// ----------------------------------------------------------------
 			// Invokable setup
 			// ----------------------------------------------------------------
@@ -163,9 +167,6 @@ public class RuntimeEnvironment implements Environment, Runnable {
 				throw new Exception("Could not instantiate the invokable class.", t);
 			}
 
-			this.jobConfiguration = tdd.getJobConfiguration();
-			this.taskConfiguration = tdd.getTaskConfiguration();
-
 			this.invokable.setEnvironment(this);
 			this.invokable.registerInputOutput();
 		}
@@ -361,23 +362,23 @@ public class RuntimeEnvironment implements Environment, Runnable {
 	}
 
 	@Override
-	public BufferReader getReader(int index) {
-		checkElementIndex(index, readers.length, "Illegal environment reader request.");
+	public InputGate getInputGate(int index) {
+		checkElementIndex(index, inputGates.length);
 
-		return readers[index];
+		return inputGates[index];
 	}
 
 	@Override
-	public BufferReader[] getAllReaders() {
-		return readers;
+	public SingleInputGate[] getAllInputGates() {
+		return inputGates;
 	}
 
 	public IntermediateResultPartition[] getProducedPartitions() {
 		return producedPartitions;
 	}
 
-	public BufferReader getReaderById(IntermediateDataSetID id) {
-		return readersById.get(id);
+	public SingleInputGate getInputGateById(IntermediateDataSetID id) {
+		return inputGatesById.get(id);
 	}
 
 	@Override

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/NetworkEnvironment.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/NetworkEnvironment.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/NetworkEnvironment.java
index 74a448a..2a8d6d4 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/NetworkEnvironment.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/NetworkEnvironment.java
@@ -21,7 +21,6 @@ package org.apache.flink.runtime.io.network;
 import akka.actor.ActorRef;
 import akka.util.Timeout;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.io.network.api.reader.BufferReader;
 import org.apache.flink.runtime.io.network.api.writer.BufferWriter;
 import org.apache.flink.runtime.io.network.buffer.BufferPool;
 import org.apache.flink.runtime.io.network.buffer.NetworkBufferPool;
@@ -29,6 +28,7 @@ import org.apache.flink.runtime.io.network.netty.NettyConfig;
 import org.apache.flink.runtime.io.network.netty.NettyConnectionManager;
 import org.apache.flink.runtime.io.network.partition.IntermediateResultPartition;
 import org.apache.flink.runtime.io.network.partition.IntermediateResultPartitionManager;
+import org.apache.flink.runtime.io.network.partition.consumer.SingleInputGate;
 import org.apache.flink.runtime.taskmanager.NetworkEnvironmentConfiguration;
 import org.apache.flink.runtime.taskmanager.Task;
 import org.apache.flink.runtime.taskmanager.TaskManager;
@@ -154,14 +154,14 @@ public class NetworkEnvironment {
 		}
 
 		// Setup the buffer pool for each buffer reader
-		final BufferReader[] readers = task.getReaders();
+		final SingleInputGate[] inputGates = task.getInputGates();
 
-		for (BufferReader reader : readers) {
+		for (SingleInputGate gate : inputGates) {
 			BufferPool bufferPool = null;
 
 			try {
-				bufferPool = networkBufferPool.createBufferPool(reader.getNumberOfInputChannels(), false);
-				reader.setBufferPool(bufferPool);
+				bufferPool = networkBufferPool.createBufferPool(gate.getNumberOfInputChannels(), false);
+				gate.setBufferPool(bufferPool);
 			}
 			catch (Throwable t) {
 				if (bufferPool != null) {
@@ -191,13 +191,13 @@ public class NetworkEnvironment {
 
 		taskEventDispatcher.unregisterWriters(executionId);
 
-		final BufferReader[] readers = task.getReaders();
+		final SingleInputGate[] inputGates = task.getInputGates();
 
-		if (readers != null) {
-			for (BufferReader reader : readers) {
+		if (inputGates != null) {
+			for (SingleInputGate gate : inputGates) {
 				try {
-					if (reader != null) {
-						reader.releaseAllResources();
+					if (gate != null) {
+						gate.releaseAllResources();
 					}
 				}
 				catch (IOException e) {

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/TaskEventHandler.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/TaskEventHandler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/TaskEventHandler.java
new file mode 100644
index 0000000..95fce96
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/TaskEventHandler.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.runtime.io.network.api;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Multimap;
+import org.apache.flink.runtime.event.task.TaskEvent;
+import org.apache.flink.runtime.util.event.EventListener;
+
+/**
+ * The event handler manages {@link EventListener} instances and allows to
+ * to publish events to them.
+ */
+public class TaskEventHandler {
+
+	// Listeners for each event type
+	private final Multimap<Class<? extends TaskEvent>, EventListener<TaskEvent>> listeners = HashMultimap.create();
+
+	public void subscribe(EventListener<TaskEvent> listener, Class<? extends TaskEvent> eventType) {
+		synchronized (listeners) {
+			listeners.put(eventType, listener);
+		}
+	}
+
+	public void unsubscribe(EventListener<TaskEvent> listener, Class<? extends TaskEvent> eventType) {
+		synchronized (listeners) {
+			listeners.remove(eventType, listener);
+		}
+	}
+
+	/**
+	 * Publishes the task event to all subscribed event listeners..
+	 *
+	 * @param event The event to publish.
+	 */
+	public void publish(TaskEvent event) {
+		synchronized (listeners) {
+			for (EventListener<TaskEvent> listener : listeners.get(event.getClass())) {
+				listener.onEvent(event);
+			}
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractReader.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractReader.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractReader.java
new file mode 100644
index 0000000..1bfca84
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractReader.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.runtime.io.network.api.reader;
+
+import org.apache.flink.runtime.event.task.AbstractEvent;
+import org.apache.flink.runtime.event.task.TaskEvent;
+import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent;
+import org.apache.flink.runtime.io.network.api.EndOfSuperstepEvent;
+import org.apache.flink.runtime.io.network.api.TaskEventHandler;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
+import org.apache.flink.runtime.util.event.EventListener;
+
+import java.io.IOException;
+
+import static com.google.common.base.Preconditions.checkState;
+
+/**
+ * A basic reader implementation, which wraps an input gate and handles events.
+ */
+public abstract class AbstractReader implements ReaderBase {
+
+	/** The input gate to read from. */
+	protected final InputGate inputGate;
+
+	/** The task event handler to manage task event subscriptions. */
+	private final TaskEventHandler taskEventHandler = new TaskEventHandler();
+
+	/** Flag indicating whether this reader allows iteration events. */
+	private boolean isIterative;
+
+	/**
+	 * The current number of end of superstep events (reset for each superstep). A superstep is
+	 * finished after an end of superstep event has been received for each input channel.
+	 */
+	private int currentNumberOfEndOfSuperstepEvents;
+
+	protected AbstractReader(InputGate inputGate) {
+		this.inputGate = inputGate;
+	}
+
+	@Override
+	public boolean isFinished() {
+		return inputGate.isFinished();
+	}
+
+	// ------------------------------------------------------------------------
+	// Events
+	// ------------------------------------------------------------------------
+
+	@Override
+	public void registerTaskEventListener(EventListener<TaskEvent> listener, Class<? extends TaskEvent> eventType) {
+		taskEventHandler.subscribe(listener, eventType);
+	}
+
+	@Override
+	public void sendTaskEvent(TaskEvent event) throws IOException {
+		inputGate.sendTaskEvent(event);
+	}
+
+	/**
+	 * Handles the event and returns whether the reader reached an end-of-stream event (either the
+	 * end of the whole stream or the end of an superstep).
+	 */
+	protected boolean handleEvent(AbstractEvent event) throws IOException {
+		final Class<?> eventType = event.getClass();
+
+		try {
+			// ------------------------------------------------------------
+			// Runtime events
+			// ------------------------------------------------------------
+
+			// This event is also checked at the (single) input gate to release the respective
+			// channel, at which it was received.
+			if (eventType == EndOfPartitionEvent.class) {
+				return true;
+			}
+			else if (eventType == EndOfSuperstepEvent.class) {
+				return incrementEndOfSuperstepEventAndCheck();
+			}
+
+			// ------------------------------------------------------------
+			// Task events (user)
+			// ------------------------------------------------------------
+			else if (event instanceof TaskEvent) {
+				taskEventHandler.publish((TaskEvent) event);
+
+				return false;
+			}
+			else {
+				throw new IllegalStateException("Received unexpected event of type " + eventType + " at reader.");
+			}
+		}
+		catch (Throwable t) {
+			throw new IOException("Error while handling event of type " + eventType + ": " + t.getMessage(), t);
+		}
+	}
+
+	// ------------------------------------------------------------------------
+	// Iterations
+	// ------------------------------------------------------------------------
+
+	@Override
+	public void setIterativeReader() {
+		isIterative = true;
+	}
+
+	@Override
+	public void startNextSuperstep() {
+		checkState(isIterative, "Tried to start next superstep in a non-iterative reader.");
+		checkState(currentNumberOfEndOfSuperstepEvents == inputGate.getNumberOfInputChannels(), "Tried to start next superstep before reaching end of previous superstep.");
+
+		currentNumberOfEndOfSuperstepEvents = 0;
+	}
+
+	@Override
+	public boolean hasReachedEndOfSuperstep() {
+		if (isIterative) {
+			return currentNumberOfEndOfSuperstepEvents == inputGate.getNumberOfInputChannels();
+		}
+
+		return false;
+	}
+
+	private boolean incrementEndOfSuperstepEventAndCheck() {
+		checkState(isIterative, "Tried to increment superstep count in a non-iterative reader.");
+		checkState(currentNumberOfEndOfSuperstepEvents + 1 <= inputGate.getNumberOfInputChannels(), "Received too many (" + currentNumberOfEndOfSuperstepEvents + ") end of superstep events.");
+
+		return ++currentNumberOfEndOfSuperstepEvents == inputGate.getNumberOfInputChannels();
+	}
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractRecordReader.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractRecordReader.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractRecordReader.java
index 2ee3256..e70b6ee 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractRecordReader.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/AbstractRecordReader.java
@@ -19,26 +19,23 @@
 package org.apache.flink.runtime.io.network.api.reader;
 
 import org.apache.flink.core.io.IOReadableWritable;
-import org.apache.flink.runtime.event.task.TaskEvent;
 import org.apache.flink.runtime.io.network.api.serialization.RecordDeserializer;
 import org.apache.flink.runtime.io.network.api.serialization.RecordDeserializer.DeserializationResult;
 import org.apache.flink.runtime.io.network.buffer.Buffer;
+import org.apache.flink.runtime.io.network.partition.consumer.BufferOrEvent;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
 import org.apache.flink.runtime.io.network.serialization.SpillingAdaptiveSpanningRecordDeserializer;
-import org.apache.flink.runtime.util.event.EventListener;
 
 import java.io.IOException;
 
 /**
- * A record-oriented runtime result reader, which wraps a {@link BufferReaderBase}.
+ * A record-oriented reader.
  * <p>
- * This abstract base class is used by both the mutable and immutable record
- * reader.
+ * This abstract base class is used by both the mutable and immutable record readers.
  *
  * @param <T> The type of the record that can be read with this record reader.
  */
-abstract class AbstractRecordReader<T extends IOReadableWritable> implements ReaderBase {
-
-	private final BufferReaderBase reader;
+abstract class AbstractRecordReader<T extends IOReadableWritable> extends AbstractReader implements ReaderBase {
 
 	private final RecordDeserializer<T>[] recordDeserializers;
 
@@ -46,11 +43,11 @@ abstract class AbstractRecordReader<T extends IOReadableWritable> implements Rea
 
 	private boolean isFinished;
 
-	protected AbstractRecordReader(BufferReaderBase reader) {
-		this.reader = reader;
+	protected AbstractRecordReader(InputGate inputGate) {
+		super(inputGate);
 
 		// Initialize one deserializer per input channel
-		this.recordDeserializers = new SpillingAdaptiveSpanningRecordDeserializer[reader.getNumberOfInputChannels()];
+		this.recordDeserializers = new SpillingAdaptiveSpanningRecordDeserializer[inputGate.getNumberOfInputChannels()];
 		for (int i = 0; i < recordDeserializers.length; i++) {
 			recordDeserializers[i] = new SpillingAdaptiveSpanningRecordDeserializer<T>();
 		}
@@ -75,25 +72,23 @@ abstract class AbstractRecordReader<T extends IOReadableWritable> implements Rea
 				}
 			}
 
-			final Buffer nextBuffer = reader.getNextBufferBlocking();
-			final int channelIndex = reader.getChannelIndexOfLastBuffer();
+			final BufferOrEvent bufferOrEvent = inputGate.getNextBufferOrEvent();
 
-			if (nextBuffer == null) {
-				if (reader.isFinished()) {
+			if (bufferOrEvent.isBuffer()) {
+				currentRecordDeserializer = recordDeserializers[bufferOrEvent.getChannelIndex()];
+				currentRecordDeserializer.setNextBuffer(bufferOrEvent.getBuffer());
+			}
+			else if (handleEvent(bufferOrEvent.getEvent())) {
+				if (inputGate.isFinished()) {
 					isFinished = true;
+
 					return false;
 				}
-				else if (reader.hasReachedEndOfSuperstep()) {
+				else if (hasReachedEndOfSuperstep()) {
+
 					return false;
-				}
-				else {
-					// More data is coming...
-					continue;
-				}
+				} // else: More data is coming...
 			}
-
-			currentRecordDeserializer = recordDeserializers[channelIndex];
-			currentRecordDeserializer.setNextBuffer(nextBuffer);
 		}
 	}
 
@@ -105,34 +100,4 @@ abstract class AbstractRecordReader<T extends IOReadableWritable> implements Rea
 			}
 		}
 	}
-
-	@Override
-	public void sendTaskEvent(TaskEvent event) throws IOException, InterruptedException {
-		reader.sendTaskEvent(event);
-	}
-
-	@Override
-	public boolean isFinished() {
-		return reader.isFinished();
-	}
-
-	@Override
-	public void subscribeToTaskEvent(EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType) {
-		reader.subscribeToTaskEvent(eventListener, eventType);
-	}
-
-	@Override
-	public void setIterativeReader() {
-		reader.setIterativeReader();
-	}
-
-	@Override
-	public void startNextSuperstep() {
-		reader.startNextSuperstep();
-	}
-
-	@Override
-	public boolean hasReachedEndOfSuperstep() {
-		return reader.hasReachedEndOfSuperstep();
-	}
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReader.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReader.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReader.java
index fca27fa..ca59609 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReader.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReader.java
@@ -18,489 +18,33 @@
 
 package org.apache.flink.runtime.io.network.api.reader;
 
-import com.google.common.collect.Maps;
-import org.apache.flink.runtime.deployment.PartitionConsumerDeploymentDescriptor;
-import org.apache.flink.runtime.deployment.PartitionInfo;
-import org.apache.flink.runtime.deployment.PartitionInfo.PartitionLocation;
-import org.apache.flink.runtime.event.task.AbstractEvent;
-import org.apache.flink.runtime.event.task.TaskEvent;
-import org.apache.flink.runtime.execution.RuntimeEnvironment;
-import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.io.network.ConnectionManager;
-import org.apache.flink.runtime.io.network.NetworkEnvironment;
-import org.apache.flink.runtime.io.network.RemoteAddress;
-import org.apache.flink.runtime.io.network.TaskEventDispatcher;
-import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent;
-import org.apache.flink.runtime.io.network.api.EndOfSuperstepEvent;
-import org.apache.flink.runtime.io.network.api.serialization.EventSerializer;
 import org.apache.flink.runtime.io.network.buffer.Buffer;
-import org.apache.flink.runtime.io.network.buffer.BufferPool;
-import org.apache.flink.runtime.io.network.buffer.BufferProvider;
-import org.apache.flink.runtime.io.network.partition.IntermediateResultPartitionProvider;
-import org.apache.flink.runtime.io.network.partition.consumer.InputChannel;
-import org.apache.flink.runtime.io.network.partition.consumer.LocalInputChannel;
-import org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel;
-import org.apache.flink.runtime.io.network.partition.consumer.UnknownInputChannel;
-import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
-import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
-import org.apache.flink.runtime.util.event.EventListener;
-import org.apache.flink.runtime.util.event.EventNotificationHandler;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.flink.runtime.io.network.partition.consumer.BufferOrEvent;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
 
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-public final class BufferReader implements BufferReaderBase {
-
-	private static final Logger LOG = LoggerFactory.getLogger(BufferReader.class);
-
-	private final Object requestLock = new Object();
-
-	private final RuntimeEnvironment environment;
-
-	private final NetworkEnvironment networkEnvironment;
-
-	private final EventNotificationHandler<TaskEvent> taskEventHandler = new EventNotificationHandler<TaskEvent>();
-
-	private final IntermediateDataSetID consumedResultId;
-
-	private final int totalNumberOfInputChannels;
-
-	private final int queueToRequest;
-
-	private final Map<IntermediateResultPartitionID, InputChannel> inputChannels;
-
-	private BufferPool bufferPool;
-
-	private boolean isReleased;
-
-	private boolean isTaskEvent;
-
-	// ------------------------------------------------------------------------
-
-	private final BlockingQueue<InputChannel> inputChannelsWithData = new LinkedBlockingQueue<InputChannel>();
-
-	private final AtomicReference<EventListener<BufferReaderBase>> readerListener = new AtomicReference<EventListener<BufferReaderBase>>(null);
-
-	private final List<TaskEvent> pendingEvents = new ArrayList<TaskEvent>();
-
-	private int numberOfUninitializedChannels;
-
-	// ------------------------------------------------------------------------
-
-	private boolean isIterativeReader;
-
-	private int currentNumEndOfSuperstepEvents;
-
-	private int channelIndexOfLastReadBuffer = -1;
-
-	private boolean hasRequestedPartitions = false;
-
-	public BufferReader(RuntimeEnvironment environment, NetworkEnvironment networkEnvironment, IntermediateDataSetID consumedResultId, int numberOfInputChannels, int queueToRequest) {
-
-		this.consumedResultId = checkNotNull(consumedResultId);
-		// Note: the environment is not fully initialized yet
-		this.environment = checkNotNull(environment);
-
-		this.networkEnvironment = networkEnvironment;
-
-		checkArgument(numberOfInputChannels >= 0);
-		this.totalNumberOfInputChannels = numberOfInputChannels;
-
-		checkArgument(queueToRequest >= 0);
-		this.queueToRequest = queueToRequest;
-
-		this.inputChannels = Maps.newHashMapWithExpectedSize(numberOfInputChannels);
-	}
-
-	// ------------------------------------------------------------------------
-	// Properties
-	// ------------------------------------------------------------------------
-
-	public void setBufferPool(BufferPool bufferPool) {
-		checkArgument(bufferPool.getNumberOfRequiredMemorySegments() == totalNumberOfInputChannels, "Buffer pool has not enough buffers for this reader.");
-		checkState(this.bufferPool == null, "Buffer pool has already been set for reader.");
-
-		this.bufferPool = checkNotNull(bufferPool);
-	}
-
-	public IntermediateDataSetID getConsumedResultId() {
-		return consumedResultId;
-	}
-
-	public String getTaskNameWithSubtasks() {
-		return environment.getTaskNameWithSubtasks();
-	}
-
-	public IntermediateResultPartitionProvider getIntermediateResultPartitionProvider() {
-		return networkEnvironment.getPartitionManager();
-	}
-
-	public TaskEventDispatcher getTaskEventDispatcher() {
-		return networkEnvironment.getTaskEventDispatcher();
-	}
-
-	public ConnectionManager getConnectionManager() {
-		return networkEnvironment.getConnectionManager();
-	}
-
-	/**
-	 * Returns the total number of input channels for this reader.
-	 * <p>
-	 * Note: This number might be smaller the current number of input channels
-	 * of the reader as channels are possibly updated during runtime.
-	 */
-	@Override
-	public int getNumberOfInputChannels() {
-		return totalNumberOfInputChannels;
-	}
-
-	public BufferProvider getBufferProvider() {
-		return bufferPool;
-	}
-
-	public void setInputChannel(IntermediateResultPartitionID partitionId, InputChannel inputChannel) {
-		synchronized (requestLock) {
-			if (inputChannels.put(checkNotNull(partitionId), checkNotNull(inputChannel)) == null &&
-					inputChannel.getClass() == UnknownInputChannel.class) {
-
-				numberOfUninitializedChannels++;
-			}
-		}
-	}
-
-	public void updateInputChannel(PartitionInfo partitionInfo) throws IOException {
-		synchronized (requestLock) {
-			if (isReleased) {
-				// There was a race with a task failure/cancel
-				return;
-			}
-
-			final IntermediateResultPartitionID partitionId = partitionInfo.getPartitionId();
-
-			InputChannel current = inputChannels.get(partitionId);
-
-			if (current.getClass() == UnknownInputChannel.class) {
-				UnknownInputChannel unknownChannel = (UnknownInputChannel) current;
-
-				InputChannel newChannel;
-
-				if (partitionInfo.getProducerLocation() == PartitionLocation.REMOTE) {
-					newChannel = unknownChannel.toRemoteInputChannel(partitionInfo.getProducerAddress());
-				}
-				else if (partitionInfo.getProducerLocation() == PartitionLocation.LOCAL) {
-					newChannel = unknownChannel.toLocalInputChannel();
-				}
-				else {
-					throw new IllegalStateException("Tried to update unknown channel with unknown channel.");
-				}
-
-				inputChannels.put(partitionId, newChannel);
-
-
-				newChannel.requestIntermediateResultPartition(queueToRequest);
-
-				for (TaskEvent event : pendingEvents) {
-					newChannel.sendTaskEvent(event);
-				}
-
-				if (--numberOfUninitializedChannels == 0) {
-					pendingEvents.clear();
-				}
-			}
-		}
-	}
-
-	// ------------------------------------------------------------------------
-	// Consume
-	// ------------------------------------------------------------------------
-
-	@Override
-	public void requestPartitionsOnce() throws IOException {
-		if (!hasRequestedPartitions) {
-			// Sanity check
-			if (totalNumberOfInputChannels != inputChannels.size()) {
-				throw new IllegalStateException("Mismatch between number of total input channels and the currently number of set input channels.");
-			}
-
-			synchronized (requestLock) {
-				for (InputChannel inputChannel : inputChannels.values()) {
-					inputChannel.requestIntermediateResultPartition(queueToRequest);
-				}
-			}
+/**
+ * A buffer-oriented reader.
+ */
+public final class BufferReader extends AbstractReader {
 
-			hasRequestedPartitions = true;
-		}
+	public BufferReader(InputGate gate) {
+		super(gate);
 	}
 
-	@Override
-	public Buffer getNextBufferBlocking() throws IOException, InterruptedException {
-		requestPartitionsOnce();
-
+	public Buffer getNextBuffer() throws IOException, InterruptedException {
 		while (true) {
-			if (Thread.interrupted()) {
-				throw new InterruptedException();
-			}
+			final BufferOrEvent bufferOrEvent = inputGate.getNextBufferOrEvent();
 
-			// Possibly block until data is available at one of the input channels
-			InputChannel currentChannel = null;
-			while (currentChannel == null) {
-				currentChannel = inputChannelsWithData.poll(2000, TimeUnit.MILLISECONDS);
-			}
-
-			isTaskEvent = false;
-
-			final Buffer buffer = currentChannel.getNextBuffer();
-
-			if (buffer == null) {
-				throw new IllegalStateException("Bug in reader logic: queried for a buffer although none was available.");
-			}
-
-			if (buffer.isBuffer()) {
-				channelIndexOfLastReadBuffer = currentChannel.getChannelIndex();
-				return buffer;
+			if (bufferOrEvent.isBuffer()) {
+				return bufferOrEvent.getBuffer();
 			}
 			else {
-				try {
-					final AbstractEvent event = EventSerializer.fromBuffer(buffer, getClass().getClassLoader());
-
-					// ------------------------------------------------------------
-					// Runtime events
-					// ------------------------------------------------------------
-					// Note: We can not assume that every channel will be finished
-					// with an according event. In failure cases or iterations the
-					// consumer task finishes earlier and has to release all
-					// resources.
-					// ------------------------------------------------------------
-					if (event.getClass() == EndOfPartitionEvent.class) {
-						currentChannel.releaseAllResources();
-
-						return null;
-					}
-					else if (event.getClass() == EndOfSuperstepEvent.class) {
-						incrementEndOfSuperstepEventAndCheck();
-
-						return null;
-					}
-					// ------------------------------------------------------------
-					// Task events (user)
-					// ------------------------------------------------------------
-					else if (event instanceof TaskEvent) {
-						taskEventHandler.publish((TaskEvent) event);
-
-						isTaskEvent = true;
-
-						return null;
-					}
-					else {
-						throw new IllegalStateException("Received unexpected event " + event + " from input channel " + currentChannel + ".");
-					}
-				}
-				catch (Throwable t) {
-					throw new IOException("Error while reading event: " + t.getMessage(), t);
-				}
-				finally {
-					buffer.recycle();
-				}
-			}
-		}
-	}
-
-	@Override
-	public Buffer getNextBuffer(Buffer exchangeBuffer) {
-		throw new UnsupportedOperationException("Buffer exchange when reading data is not yet supported.");
-	}
-
-	@Override
-	public int getChannelIndexOfLastBuffer() {
-		return channelIndexOfLastReadBuffer;
-	}
-
-	@Override
-	public boolean isTaskEvent() {
-		return isTaskEvent;
-	}
-
-	@Override
-	public boolean isFinished() {
-		synchronized (requestLock) {
-			for (InputChannel inputChannel : inputChannels.values()) {
-				if (!inputChannel.isReleased()) {
-					return false;
-				}
-			}
-		}
-
-		return true;
-	}
-
-	public void releaseAllResources() throws IOException {
-		synchronized (requestLock) {
-			if (!isReleased) {
-				try {
-					for (InputChannel inputChannel : inputChannels.values()) {
-						try {
-							inputChannel.releaseAllResources();
-						}
-						catch (IOException e) {
-							LOG.warn("Error during release of channel resources: " + e.getMessage(), e);
-						}
-					}
-
-					// The buffer pool can actually be destroyed immediately after the
-					// reader received all of the data from the input channels.
-					if (bufferPool != null) {
-						bufferPool.destroy();
-					}
-				}
-				finally {
-					isReleased = true;
+				if (handleEvent(bufferOrEvent.getEvent())) {
+					return null;
 				}
 			}
 		}
 	}
-
-	// ------------------------------------------------------------------------
-	// Channel notifications
-	// ------------------------------------------------------------------------
-
-	public void onAvailableInputChannel(InputChannel inputChannel) {
-		inputChannelsWithData.add(inputChannel);
-
-		if (readerListener.get() != null) {
-			readerListener.get().onEvent(this);
-		}
-	}
-
-	@Override
-	public void subscribeToReader(EventListener<BufferReaderBase> listener) {
-		if (!this.readerListener.compareAndSet(null, listener)) {
-			throw new IllegalStateException(listener + " is already registered as a record availability listener");
-		}
-	}
-
-	// ------------------------------------------------------------------------
-	// Task events
-	// ------------------------------------------------------------------------
-
-	@Override
-	public void sendTaskEvent(TaskEvent event) throws IOException, InterruptedException {
-		// This can be improved by just serializing the event once for all
-		// remote input channels.
-		synchronized (requestLock) {
-			for (InputChannel inputChannel : inputChannels.values()) {
-				inputChannel.sendTaskEvent(event);
-			}
-
-			if (numberOfUninitializedChannels > 0) {
-				pendingEvents.add(event);
-			}
-		}
-	}
-
-	@Override
-	public void subscribeToTaskEvent(EventListener<TaskEvent> listener, Class<? extends TaskEvent> eventType) {
-		taskEventHandler.subscribe(listener, eventType);
-	}
-
-	// ------------------------------------------------------------------------
-	// Iteration end of superstep events
-	// ------------------------------------------------------------------------
-
-	@Override
-	public void setIterativeReader() {
-		isIterativeReader = true;
-	}
-
-	@Override
-	public void startNextSuperstep() {
-		checkState(isIterativeReader, "Tried to start next superstep in a non-iterative reader.");
-		checkState(currentNumEndOfSuperstepEvents == totalNumberOfInputChannels,
-				"Tried to start next superstep before reaching end of previous superstep.");
-
-		currentNumEndOfSuperstepEvents = 0;
-	}
-
-	@Override
-	public boolean hasReachedEndOfSuperstep() {
-		return currentNumEndOfSuperstepEvents == totalNumberOfInputChannels;
-	}
-
-	private boolean incrementEndOfSuperstepEventAndCheck() {
-		checkState(isIterativeReader, "Received end of superstep event in a non-iterative reader.");
-
-		currentNumEndOfSuperstepEvents++;
-
-		checkState(currentNumEndOfSuperstepEvents <= totalNumberOfInputChannels,
-				"Received too many (" + currentNumEndOfSuperstepEvents + ") end of superstep events.");
-
-		return currentNumEndOfSuperstepEvents == totalNumberOfInputChannels;
-	}
-
-	// ------------------------------------------------------------------------
-
-	@Override
-	public String toString() {
-		return String.format("BufferReader %s [task: %s, current/total number of input channels: %d/%d]",
-				consumedResultId, getTaskNameWithSubtasks(), inputChannels.size(), totalNumberOfInputChannels);
-	}
-
-	public static BufferReader create(RuntimeEnvironment runtimeEnvironment, NetworkEnvironment networkEnvironment, PartitionConsumerDeploymentDescriptor desc) {
-		// The consumed intermediate data set (all partitions are part of this data set)
-		final IntermediateDataSetID resultId = desc.getResultId();
-
-		// The queue to request from each consumed partition
-		final int queueIndex = desc.getQueueIndex();
-
-		// There is one input channel for each consumed partition
-		final PartitionInfo[] partitions = desc.getPartitions();
-		final int numberOfInputChannels = partitions.length;
-
-		final BufferReader reader = new BufferReader(runtimeEnvironment, networkEnvironment, resultId, numberOfInputChannels, queueIndex);
-
-		// Create input channels
-		final InputChannel[] inputChannels = new InputChannel[numberOfInputChannels];
-
-		int channelIndex = 0;
-
-		for (PartitionInfo partition : partitions) {
-			final ExecutionAttemptID producerExecutionId = partition.getProducerExecutionId();
-			final IntermediateResultPartitionID partitionId = partition.getPartitionId();
-
-			final PartitionLocation producerLocation = partition.getProducerLocation();
-
-			switch (producerLocation) {
-				case LOCAL:
-					inputChannels[channelIndex] = new LocalInputChannel(channelIndex, producerExecutionId, partitionId, reader);
-					break;
-
-				case REMOTE:
-					final RemoteAddress producerAddress = checkNotNull(partition.getProducerAddress(), "Missing producer address for remote intermediate result partition.");
-
-					inputChannels[channelIndex] = new RemoteInputChannel(channelIndex, producerExecutionId, partitionId, reader, producerAddress);
-					break;
-
-				case UNKNOWN:
-					inputChannels[channelIndex] = new UnknownInputChannel(channelIndex, producerExecutionId, partitionId, reader);
-					break;
-			}
-
-			reader.setInputChannel(partitionId, inputChannels[channelIndex]);
-
-			channelIndex++;
-		}
-
-		return reader;
-	}
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReaderBase.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReaderBase.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReaderBase.java
deleted file mode 100644
index d1dbefd..0000000
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/BufferReaderBase.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.flink.runtime.io.network.api.reader;
-
-import org.apache.flink.runtime.io.network.buffer.Buffer;
-import org.apache.flink.runtime.io.network.partition.consumer.InputChannel;
-import org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel;
-import org.apache.flink.runtime.util.event.EventListener;
-
-import java.io.IOException;
-
-/**
- * A buffer-oriented runtime result reader.
- * <p>
- * {@link BufferReaderBase} is the runtime API for consuming results. Events
- * are handled by the reader and users can query for buffers with
- * {@link #getNextBufferBlocking()} or {@link #getNextBuffer(Buffer)}.
- * <p>
- * <strong>Important</strong>: If {@link #getNextBufferBlocking()} is used, it is
- * necessary to release the returned buffers with {@link Buffer#recycle()}
- * after they are consumed.
- */
-public interface BufferReaderBase extends ReaderBase {
-
-	/**
-	 * Returns the next queued {@link Buffer} from one of the {@link RemoteInputChannel}
-	 * instances attached to this reader. The are no ordering guarantees with
-	 * respect to which channel is queried for data.
-	 * <p>
-	 * <strong>Important</strong>: it is necessary to release buffers, which
-	 * are returned by the reader via {@link Buffer#recycle()}, because they
-	 * are a pooled resource. If not recycled, the network stack will run out
-	 * of buffers and deadlock.
-	 *
-	 * @see #getChannelIndexOfLastBuffer()
-	 */
-	Buffer getNextBufferBlocking() throws IOException, InterruptedException;
-
-	/**
-	 * {@link #getNextBufferBlocking()} requires the user to quickly recycle the
-	 * returned buffer. For a fully buffer-oriented runtime, we need to
-	 * support a variant of this method, which allows buffers to be exchanged
-	 * in order to save unnecessary memory copies between buffer pools.
-	 * <p>
-	 * Currently this is not a problem, because the only "users" of the buffer-
-	 * oriented API are the record-oriented readers, which immediately
-	 * deserialize the buffer and recycle it.
-	 */
-	Buffer getNextBuffer(Buffer exchangeBuffer) throws IOException, InterruptedException;
-
-	/**
-	 * Returns a channel index for the last {@link Buffer} instance returned by
-	 * {@link #getNextBufferBlocking()} or {@link #getNextBuffer(Buffer)}.
-	 * <p>
-	 * The returned index is guaranteed to be the same for all buffers read by
-	 * the same {@link RemoteInputChannel} instance. This is useful when data spans
-	 * multiple buffers returned by this reader.
-	 * <p>
-	 * Initially returns <code>-1</code> and if multiple readers are unioned,
-	 * the local channel indexes are mapped to the sequence from 0 to n-1.
-	 */
-	int getChannelIndexOfLastBuffer();
-
-	/**
-	 * Returns the total number of {@link InputChannel} instances, from which this
-	 * reader gets its data.
-	 */
-	int getNumberOfInputChannels();
-
-	boolean isTaskEvent();
-
-	void subscribeToReader(EventListener<BufferReaderBase> listener);
-
-	void requestPartitionsOnce() throws IOException;
-
-}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/MutableRecordReader.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/MutableRecordReader.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/MutableRecordReader.java
index 75d4f21..d7cc7e9 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/MutableRecordReader.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/MutableRecordReader.java
@@ -19,13 +19,14 @@
 package org.apache.flink.runtime.io.network.api.reader;
 
 import org.apache.flink.core.io.IOReadableWritable;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
 
 import java.io.IOException;
 
 public class MutableRecordReader<T extends IOReadableWritable> extends AbstractRecordReader<T> implements MutableReader<T> {
 
-	public MutableRecordReader(BufferReaderBase reader) {
-		super(reader);
+	public MutableRecordReader(InputGate inputGate) {
+		super(inputGate);
 	}
 
 	@Override

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/ReaderBase.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/ReaderBase.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/ReaderBase.java
index bb6ec44..2a0a6df 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/ReaderBase.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/ReaderBase.java
@@ -24,23 +24,22 @@ import org.apache.flink.runtime.event.task.TaskEvent;
 import org.apache.flink.runtime.util.event.EventListener;
 
 /**
- * The basic API every reader (both buffer- and record-oriented) has to support.
+ * The basic API for every reader.
  */
 public interface ReaderBase {
 
-	// ------------------------------------------------------------------------
-	// Properties
-	// ------------------------------------------------------------------------
-
+	/**
+	 * Returns whether the reader has consumed the input.
+	 */
 	boolean isFinished();
 
 	// ------------------------------------------------------------------------
-	// Events
+	// Task events
 	// ------------------------------------------------------------------------
 
-	void subscribeToTaskEvent(EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType);
+	void sendTaskEvent(TaskEvent event) throws IOException;
 
-	void sendTaskEvent(TaskEvent event) throws IOException, InterruptedException;
+	void registerTaskEventListener(EventListener<TaskEvent> listener, Class<? extends TaskEvent> eventType);
 
 	// ------------------------------------------------------------------------
 	// Iterations

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/RecordReader.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/RecordReader.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/RecordReader.java
index db992a5..b1395e3 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/RecordReader.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/RecordReader.java
@@ -19,6 +19,7 @@
 package org.apache.flink.runtime.io.network.api.reader;
 
 import org.apache.flink.core.io.IOReadableWritable;
+import org.apache.flink.runtime.io.network.partition.consumer.InputGate;
 
 import java.io.IOException;
 
@@ -28,8 +29,8 @@ public class RecordReader<T extends IOReadableWritable> extends AbstractRecordRe
 
 	private T currentRecord;
 
-	public RecordReader(BufferReaderBase reader, Class<T> recordType) {
-		super(reader);
+	public RecordReader(InputGate inputGate, Class<T> recordType) {
+		super(inputGate);
 
 		this.recordType = recordType;
 	}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/UnionBufferReader.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/UnionBufferReader.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/UnionBufferReader.java
deleted file mode 100644
index 241e212..0000000
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/reader/UnionBufferReader.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.flink.runtime.io.network.api.reader;
-
-import org.apache.flink.runtime.event.task.TaskEvent;
-import org.apache.flink.runtime.io.network.buffer.Buffer;
-import org.apache.flink.runtime.util.event.EventListener;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-/**
- * A buffer-oriented reader, which unions multiple {@link BufferReader}
- * instances.
- */
-public class UnionBufferReader implements BufferReaderBase {
-
-	private final BufferReaderBase[] readers;
-
-	private final DataAvailabilityListener dataAvailabilityListener;
-
-	// Set of readers, which are not closed yet
-	private final Set<BufferReaderBase> remainingReaders;
-
-	// Logical channel index offset for each reader
-	private final Map<BufferReaderBase, Integer> readerToIndexOffsetMap = new HashMap<BufferReaderBase, Integer>();
-
-	private int totalNumInputChannels;
-
-	private BufferReaderBase currentReader;
-
-	private int currentReaderChannelIndexOffset;
-
-	private int channelIndexOfLastReadBuffer = -1;
-
-	private boolean isIterative;
-
-	private boolean hasRequestedPartitions;
-
-	private boolean isTaskEvent;
-
-	public UnionBufferReader(BufferReaderBase... readers) {
-		checkNotNull(readers);
-		checkArgument(readers.length >= 2, "Union buffer reader must be initialized with at least two individual buffer readers");
-
-		this.readers = readers;
-		this.remainingReaders = new HashSet<BufferReaderBase>(readers.length + 1, 1.0F);
-
-		this.dataAvailabilityListener = new DataAvailabilityListener(this);
-
-		int currentChannelIndexOffset = 0;
-
-		for (int i = 0; i < readers.length; i++) {
-			BufferReaderBase reader = readers[i];
-
-			reader.subscribeToReader(dataAvailabilityListener);
-
-			remainingReaders.add(reader);
-			readerToIndexOffsetMap.put(reader, currentChannelIndexOffset);
-
-			totalNumInputChannels += reader.getNumberOfInputChannels();
-			currentChannelIndexOffset += reader.getNumberOfInputChannels();
-		}
-	}
-
-	@Override
-	public void requestPartitionsOnce() throws IOException {
-		if (!hasRequestedPartitions) {
-			for (BufferReaderBase reader : readers) {
-				reader.requestPartitionsOnce();
-			}
-
-			hasRequestedPartitions = true;
-		}
-	}
-
-
-	@Override
-	public Buffer getNextBufferBlocking() throws IOException, InterruptedException {
-		requestPartitionsOnce();
-
-		do {
-			if (currentReader == null) {
-				// Finished when all readers are finished
-				if (isFinished()) {
-					dataAvailabilityListener.clear();
-					return null;
-				}
-				// Finished with superstep when all readers finished superstep
-				else if (isIterative && remainingReaders.isEmpty()) {
-					resetRemainingReaders();
-					return null;
-				}
-				else {
-					while (true) {
-						currentReader = dataAvailabilityListener.getNextReaderBlocking();
-						currentReaderChannelIndexOffset = readerToIndexOffsetMap.get(currentReader);
-
-						if (isIterative && !remainingReaders.contains(currentReader)) {
-							// If the current reader already received its end
-							// of superstep event and notified the union reader
-							// about newer data *before* all other readers have
-							// done so, we delay this notifications.
-							dataAvailabilityListener.addReader(currentReader);
-						}
-						else {
-							break;
-						}
-					}
-				}
-			}
-
-			Buffer buffer = currentReader.getNextBufferBlocking();
-			channelIndexOfLastReadBuffer = currentReaderChannelIndexOffset + currentReader.getChannelIndexOfLastBuffer();
-
-			isTaskEvent = false;
-
-			if (buffer == null) {
-				if (currentReader.isFinished() || currentReader.hasReachedEndOfSuperstep()) {
-					remainingReaders.remove(currentReader);
-				}
-
-				currentReader = null;
-
-				return null;
-			}
-			else {
-				currentReader = null;
-				return buffer;
-			}
-		} while (true);
-	}
-
-	@Override
-	public Buffer getNextBuffer(Buffer exchangeBuffer) throws IOException, InterruptedException {
-		throw new UnsupportedOperationException("Buffer exchange when reading data is not yet supported.");
-	}
-
-	@Override
-	public int getChannelIndexOfLastBuffer() {
-		return channelIndexOfLastReadBuffer;
-	}
-
-	@Override
-	public int getNumberOfInputChannels() {
-		return totalNumInputChannels;
-	}
-
-	@Override
-	public boolean isTaskEvent() {
-		return isTaskEvent;
-	}
-
-	@Override
-	public void subscribeToReader(EventListener<BufferReaderBase> listener) {
-		dataAvailabilityListener.registerListener(listener);
-	}
-
-	@Override
-	public boolean isFinished() {
-		for (BufferReaderBase reader : readers) {
-			if (!reader.isFinished()) {
-				return false;
-			}
-		}
-
-		return true;
-	}
-
-	private void resetRemainingReaders() {
-		checkState(isIterative, "Tried to reset remaining reader with non-iterative reader.");
-		checkState(remainingReaders.isEmpty(), "Tried to reset remaining readers, but there are some remaining readers.");
-		for (BufferReaderBase reader : readers) {
-			remainingReaders.add(reader);
-		}
-	}
-
-	// ------------------------------------------------------------------------
-	// TaskEvents
-	// ------------------------------------------------------------------------
-
-	@Override
-	public void subscribeToTaskEvent(EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType) {
-		for (BufferReaderBase reader : readers) {
-			reader.subscribeToTaskEvent(eventListener, eventType);
-		}
-	}
-
-	@Override
-	public void sendTaskEvent(TaskEvent event) throws IOException, InterruptedException {
-		for (BufferReaderBase reader : readers) {
-			reader.sendTaskEvent(event);
-		}
-	}
-
-	// ------------------------------------------------------------------------
-	// Iteration end of superstep events
-	// ------------------------------------------------------------------------
-
-	@Override
-	public void setIterativeReader() {
-		isIterative = true;
-
-		for (BufferReaderBase reader : readers) {
-			reader.setIterativeReader();
-		}
-	}
-
-	@Override
-	public void startNextSuperstep() {
-		for (BufferReaderBase reader : readers) {
-			reader.startNextSuperstep();
-		}
-	}
-
-	@Override
-	public boolean hasReachedEndOfSuperstep() {
-		for (BufferReaderBase reader : readers) {
-			if (!reader.hasReachedEndOfSuperstep()) {
-				return false;
-			}
-		}
-
-		return true;
-	}
-
-	// ------------------------------------------------------------------------
-	// Data availability notifications
-	// ------------------------------------------------------------------------
-
-	private static class DataAvailabilityListener implements EventListener<BufferReaderBase> {
-
-		private final UnionBufferReader unionReader;
-
-		private final BlockingQueue<BufferReaderBase> readersWithData = new LinkedBlockingQueue<BufferReaderBase>();
-
-		private volatile EventListener<BufferReaderBase> registeredListener;
-
-		private DataAvailabilityListener(UnionBufferReader unionReader) {
-			this.unionReader = unionReader;
-		}
-
-		@Override
-		public void onEvent(BufferReaderBase reader) {
-			readersWithData.add(reader);
-
-			if (registeredListener != null) {
-				registeredListener.onEvent(unionReader);
-			}
-		}
-
-		BufferReaderBase getNextReaderBlocking() throws InterruptedException {
-			return readersWithData.take();
-		}
-
-		void addReader(BufferReaderBase reader) {
-			readersWithData.add(reader);
-		}
-
-		void clear() {
-			readersWithData.clear();
-		}
-
-		void registerListener(EventListener<BufferReaderBase> listener) {
-			if (registeredListener == null) {
-				registeredListener = listener;
-			}
-			else {
-				throw new IllegalStateException("Already registered listener.");
-			}
-		}
-	}
-}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/writer/BufferWriter.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/writer/BufferWriter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/writer/BufferWriter.java
index 6cb1831..b9c6d33 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/writer/BufferWriter.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/writer/BufferWriter.java
@@ -27,7 +27,7 @@ import org.apache.flink.runtime.io.network.buffer.BufferProvider;
 import org.apache.flink.runtime.io.network.partition.IntermediateResultPartition;
 import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
 import org.apache.flink.runtime.util.event.EventListener;
-import org.apache.flink.runtime.util.event.EventNotificationHandler;
+import org.apache.flink.runtime.io.network.api.TaskEventHandler;
 
 import java.io.IOException;
 
@@ -44,7 +44,7 @@ public final class BufferWriter implements EventListener<TaskEvent> {
 
 	private final IntermediateResultPartition partition;
 
-	private final EventNotificationHandler<TaskEvent> taskEventHandler = new EventNotificationHandler<TaskEvent>();
+	private final TaskEventHandler taskEventHandler = new TaskEventHandler();
 
 	public BufferWriter(IntermediateResultPartition partition) {
 		this.partition = partition;
@@ -104,7 +104,7 @@ public final class BufferWriter implements EventListener<TaskEvent> {
 	// Event handling
 	// ------------------------------------------------------------------------
 
-	public EventNotificationHandler<TaskEvent> getTaskEventHandler() {
+	public TaskEventHandler getTaskEventHandler() {
 		return taskEventHandler;
 	}
 

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/BufferOrEvent.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/BufferOrEvent.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/BufferOrEvent.java
new file mode 100644
index 0000000..032772c
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/BufferOrEvent.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.runtime.io.network.partition.consumer;
+
+import org.apache.flink.runtime.event.task.AbstractEvent;
+import org.apache.flink.runtime.io.network.buffer.Buffer;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+/**
+ * Either type for {@link Buffer} or {@link AbstractEvent} instances tagged with the channel index,
+ * from which they were received.
+ */
+public class BufferOrEvent {
+
+	private final Buffer buffer;
+
+	private final AbstractEvent event;
+
+	private int channelIndex;
+
+	public BufferOrEvent(Buffer buffer, int channelIndex) {
+		this.buffer = buffer;
+		this.event = null;
+		this.channelIndex = channelIndex;
+	}
+
+	public BufferOrEvent(AbstractEvent event, int channelIndex) {
+		this.buffer = null;
+		this.event = event;
+		this.channelIndex = channelIndex;
+	}
+
+	public boolean isBuffer() {
+		return buffer != null;
+	}
+
+	public boolean isEvent() {
+		return event != null;
+	}
+
+	public Buffer getBuffer() {
+		return buffer;
+	}
+
+	public AbstractEvent getEvent() {
+		return event;
+	}
+
+	public int getChannelIndex() {
+		return channelIndex;
+	}
+
+	public void setChannelIndex(int channelIndex) {
+		checkArgument(channelIndex >= 0);
+		this.channelIndex = channelIndex;
+	}
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputChannel.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputChannel.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputChannel.java
index ea8f459..31b67ca 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputChannel.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputChannel.java
@@ -20,7 +20,6 @@ package org.apache.flink.runtime.io.network.partition.consumer;
 
 import org.apache.flink.runtime.event.task.TaskEvent;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.io.network.api.reader.BufferReader;
 import org.apache.flink.runtime.io.network.buffer.Buffer;
 import org.apache.flink.runtime.io.network.partition.queue.IntermediateResultPartitionQueue;
 import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
@@ -28,7 +27,7 @@ import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
 import java.io.IOException;
 
 /**
- * An input channel is the consumer of a single queue of an {@link IntermediateResultPartitionQueue}.
+ * An input channel is the consumer of a single subpartition of an {@link IntermediateResultPartitionQueue}.
  * <p>
  * For each channel, the consumption life cycle is as follows:
  * <ol>
@@ -45,13 +44,13 @@ public abstract class InputChannel {
 
 	protected final IntermediateResultPartitionID partitionId;
 
-	protected final BufferReader reader;
+	protected final SingleInputGate inputGate;
 
-	protected InputChannel(int channelIndex, ExecutionAttemptID producerExecutionId, IntermediateResultPartitionID partitionId, BufferReader reader) {
+	protected InputChannel(SingleInputGate inputGate, int channelIndex, ExecutionAttemptID producerExecutionId, IntermediateResultPartitionID partitionId) {
+		this.inputGate = inputGate;
 		this.channelIndex = channelIndex;
 		this.producerExecutionId = producerExecutionId;
 		this.partitionId = partitionId;
-		this.reader = reader;
 	}
 
 	// ------------------------------------------------------------------------
@@ -76,11 +75,10 @@ public abstract class InputChannel {
 	}
 
 	/**
-	 * Notifies the {@link BufferReader}, which consumes this input channel
-	 * about an available {@link Buffer} instance.
+	 * Notifies the owning {@link SingleInputGate} about an available {@link Buffer} instance.
 	 */
-	protected void notifyReaderAboutAvailableBuffer() {
-		reader.onAvailableInputChannel(this);
+	protected void notifyAvailableBuffer() {
+		inputGate.onAvailableBuffer(this);
 	}
 
 	// ------------------------------------------------------------------------
@@ -97,7 +95,7 @@ public abstract class InputChannel {
 	public abstract void requestIntermediateResultPartition(int queueIndex) throws IOException;
 
 	/**
-	 * Returns the next buffer from the consumed queue.
+	 * Returns the next buffer from the consumed subpartition.
 	 */
 	public abstract Buffer getNextBuffer() throws IOException;
 
@@ -106,10 +104,12 @@ public abstract class InputChannel {
 	// ------------------------------------------------------------------------
 
 	/**
-	 * Sends a {@link TaskEvent} back to the partition producer.
+	 * Sends a {@link TaskEvent} back to the task producing the consumed result partition.
 	 * <p>
-	 * <strong>Important</strong>: This only works if the producer task is
-	 * running at the same time.
+	 * <strong>Important</strong>: The producing task has to be running to receive backwards events.
+	 * This means that the result type needs to be pipelined and the task logic has to ensure that
+	 * the producer will wait for all backwards events. Otherwise, this will lead to an Exception
+	 * at runtime.
 	 */
 	public abstract void sendTaskEvent(TaskEvent event) throws IOException;
 

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java
new file mode 100644
index 0000000..8d28084
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.runtime.io.network.partition.consumer;
+
+import org.apache.flink.runtime.event.task.TaskEvent;
+import org.apache.flink.runtime.util.event.EventListener;
+
+import java.io.IOException;
+
+public interface InputGate {
+
+	public int getNumberOfInputChannels();
+
+	public boolean isFinished();
+
+	public void requestPartitions() throws IOException;
+
+	public BufferOrEvent getNextBufferOrEvent() throws IOException, InterruptedException;
+
+	public void sendTaskEvent(TaskEvent event) throws IOException;
+
+	public void registerListener(EventListener<InputGate> listener);
+
+}

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/LocalInputChannel.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/LocalInputChannel.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/LocalInputChannel.java
index 150aaea..8b58234 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/LocalInputChannel.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/LocalInputChannel.java
@@ -21,8 +21,9 @@ package org.apache.flink.runtime.io.network.partition.consumer;
 import com.google.common.base.Optional;
 import org.apache.flink.runtime.event.task.TaskEvent;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
-import org.apache.flink.runtime.io.network.api.reader.BufferReader;
+import org.apache.flink.runtime.io.network.TaskEventDispatcher;
 import org.apache.flink.runtime.io.network.buffer.Buffer;
+import org.apache.flink.runtime.io.network.partition.IntermediateResultPartitionManager;
 import org.apache.flink.runtime.io.network.partition.queue.IntermediateResultPartitionQueueIterator;
 import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID;
 import org.apache.flink.runtime.util.event.NotificationListener;
@@ -31,23 +32,37 @@ import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 
+import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
 
 /**
- * An input channel, which requests a local partition queue.
+ * An input channel, which requests a local subpartition.
  */
 public class LocalInputChannel extends InputChannel implements NotificationListener {
 
 	private static final Logger LOG = LoggerFactory.getLogger(LocalInputChannel.class);
 
+	private final IntermediateResultPartitionManager partitionManager;
+
+	private final TaskEventDispatcher taskEventDispatcher;
+
 	private IntermediateResultPartitionQueueIterator queueIterator;
 
 	private boolean isReleased;
 
-	private Buffer lookAhead;
+	private volatile Buffer lookAhead;
+
+	public LocalInputChannel(
+			SingleInputGate gate, int channelIndex,
+			ExecutionAttemptID producerExecutionId,
+			IntermediateResultPartitionID partitionId,
+			IntermediateResultPartitionManager partitionManager,
+			TaskEventDispatcher taskEventDispatcher) {
+
+		super(gate, channelIndex, producerExecutionId, partitionId);
 
-	public LocalInputChannel(int channelIndex, ExecutionAttemptID producerExecutionId, IntermediateResultPartitionID partitionId, BufferReader reader) {
-		super(channelIndex, producerExecutionId, partitionId, reader);
+		this.partitionManager = checkNotNull(partitionManager);
+		this.taskEventDispatcher = checkNotNull(taskEventDispatcher);
 	}
 
 	// ------------------------------------------------------------------------
@@ -61,8 +76,8 @@ public class LocalInputChannel extends InputChannel implements NotificationListe
 				LOG.debug("Requesting queue {} from LOCAL partition {}.", partitionId, queueIndex);
 			}
 
-			queueIterator = reader.getIntermediateResultPartitionProvider()
-					.getIntermediateResultPartitionIterator(producerExecutionId, partitionId, queueIndex, Optional.of(reader.getBufferProvider()));
+			queueIterator = partitionManager.getIntermediateResultPartitionIterator(
+					producerExecutionId, partitionId, queueIndex, Optional.of(inputGate.getBufferProvider()));
 
 			getNextLookAhead();
 		}
@@ -93,7 +108,7 @@ public class LocalInputChannel extends InputChannel implements NotificationListe
 	public void sendTaskEvent(TaskEvent event) throws IOException {
 		checkState(queueIterator != null, "Tried to send task event to producer before requesting a queue.");
 
-		if (!reader.getTaskEventDispatcher().publish(producerExecutionId, partitionId, event)) {
+		if (!taskEventDispatcher.publish(producerExecutionId, partitionId, event)) {
 			throw new IOException("Error while publishing event " + event + " to producer. The producer could not be found.");
 		}
 	}
@@ -139,7 +154,7 @@ public class LocalInputChannel extends InputChannel implements NotificationListe
 
 	@Override
 	public void onNotification() {
-		notifyReaderAboutAvailableBuffer();
+		notifyAvailableBuffer();
 	}
 
 	// ------------------------------------------------------------------------
@@ -149,7 +164,7 @@ public class LocalInputChannel extends InputChannel implements NotificationListe
 			lookAhead = queueIterator.getNextBuffer();
 
 			if (lookAhead != null) {
-				notifyReaderAboutAvailableBuffer();
+				notifyAvailableBuffer();
 				break;
 			}
 

http://git-wip-us.apache.org/repos/asf/flink/blob/5232c56b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java
index 616a8a5..002c90e 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java
@@ -20,8 +20,8 @@ package org.apache.flink.runtime.io.network.partition.consumer;
 
 import org.apache.flink.runtime.event.task.TaskEvent;
 import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
+import org.apache.flink.runtime.io.network.ConnectionManager;
 import org.apache.flink.runtime.io.network.RemoteAddress;
-import org.apache.flink.runtime.io.network.api.reader.BufferReader;
 import org.apache.flink.runtime.io.network.buffer.Buffer;
 import org.apache.flink.runtime.io.network.buffer.BufferProvider;
 import org.apache.flink.runtime.io.network.netty.PartitionRequestClient;
@@ -35,6 +35,7 @@ import java.util.Queue;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 
+import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
 
 /**
@@ -58,21 +59,25 @@ public class RemoteInputChannel extends InputChannel {
 
 	private int expectedSequenceNumber = 0;
 
+	private ConnectionManager connectionManager;
+
 	public RemoteInputChannel(
+			SingleInputGate gate,
 			int channelIndex,
 			ExecutionAttemptID producerExecutionId,
 			IntermediateResultPartitionID partitionId,
-			BufferReader reader,
-			RemoteAddress producerAddress) {
+			RemoteAddress producerAddress,
+			ConnectionManager connectionManager) {
 
-		super(channelIndex, producerExecutionId, partitionId, reader);
+		super(gate, channelIndex, producerExecutionId, partitionId);
 
 		/**
 		 * This ID is used by the {@link PartitionRequestClient} to distinguish
 		 * between receivers, which share the same TCP connection.
 		 */
 		this.id = new InputChannelID();
-		this.producerAddress = producerAddress;
+		this.producerAddress = checkNotNull(producerAddress);
+		this.connectionManager = checkNotNull(connectionManager);
 	}
 
 	// ------------------------------------------------------------------------
@@ -86,7 +91,7 @@ public class RemoteInputChannel extends InputChannel {
 				LOG.debug("Requesting queue {} from REMOTE partition {}.", partitionId, queueIndex);
 			}
 
-			partitionRequestClient = reader.getConnectionManager().createPartitionRequestClient(producerAddress);
+			partitionRequestClient = connectionManager.createPartitionRequestClient(producerAddress);
 
 			partitionRequestClient.requestIntermediateResultPartition(producerExecutionId, partitionId, queueIndex, this);
 		}
@@ -171,7 +176,7 @@ public class RemoteInputChannel extends InputChannel {
 			return null;
 		}
 
-		return reader.getBufferProvider();
+		return inputGate.getBufferProvider();
 	}
 
 	public void onBuffer(Buffer buffer, int sequenceNumber) {
@@ -184,7 +189,7 @@ public class RemoteInputChannel extends InputChannel {
 						receivedBuffers.add(buffer);
 						expectedSequenceNumber++;
 
-						notifyReaderAboutAvailableBuffer();
+						notifyAvailableBuffer();
 
 						success = true;
 
@@ -205,7 +210,7 @@ public class RemoteInputChannel extends InputChannel {
 
 	public void onError(Throwable error) {
 		if (ioError.compareAndSet(null, error instanceof IOException ? (IOException) error : new IOException(error))) {
-			notifyReaderAboutAvailableBuffer();
+			notifyAvailableBuffer();
 		}
 	}
 
@@ -215,8 +220,8 @@ public class RemoteInputChannel extends InputChannel {
 		IOException error = ioError.get();
 
 		if (error != null) {
-			throw new IOException(String.format("%s at remote input channel of task '%s': %s].",
-					error.getClass().getName(), reader.getTaskNameWithSubtasks(), error.getMessage()));
+			throw new IOException(String.format("%s at remote input channel: %s].",
+					error.getClass().getName(), error.getMessage()));
 		}
 	}