You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by se...@apache.org on 2015/09/21 23:34:42 UTC

[1/4] flink git commit: [FLINK-2649] [scala shell] Fix unclosed stream in case of an error in JarHelper#unjar()

Repository: flink
Updated Branches:
  refs/heads/master 63d9800ee -> 5e6175d6e


[FLINK-2649] [scala shell] Fix unclosed stream in case of an error in JarHelper#unjar()

This closes #1151


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

Branch: refs/heads/master
Commit: 5e6175d6eadf62d7493e0b2d3c925c802f95ae69
Parents: f3809d8
Author: Ted <yu...@gmail.com>
Authored: Sun Sep 20 09:47:43 2015 -0700
Committer: Stephan Ewen <se...@apache.org>
Committed: Mon Sep 21 23:18:04 2015 +0200

----------------------------------------------------------------------
 .../main/java/org/apache/flink/api/java/JarHelper.java   | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/5e6175d6/flink-staging/flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java
----------------------------------------------------------------------
diff --git a/flink-staging/flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java b/flink-staging/flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java
index 5def4b0..e085c25 100644
--- a/flink-staging/flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java
+++ b/flink-staging/flink-scala-shell/src/main/java/org/apache/flink/api/java/JarHelper.java
@@ -123,11 +123,14 @@ public class JarHelper
 		}
 		FileOutputStream fos = new FileOutputStream(destFile);
 		dest = new BufferedOutputStream(fos, BUFFER_SIZE);
-		while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
-		dest.write(data, 0, count);
+		try {
+			while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
+				dest.write(data, 0, count);
+			}
+			dest.flush();
+		} finally {
+			dest.close();
 		}
-		dest.flush();
-		dest.close();
 		if (entry.getTime() != -1) {destFile.setLastModified(entry.getTime());}
 	}
 	jis.close();


[4/4] flink git commit: [FLINK-2710] [streaming] Fix and improve SocketTextStreamFunction and SocketTextStreamFunctionTest

Posted by se...@apache.org.
[FLINK-2710] [streaming] Fix and improve SocketTextStreamFunction and SocketTextStreamFunctionTest


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

Branch: refs/heads/master
Commit: bd74baef5d0d23ce29ff71bb67f12bd32219ff7b
Parents: 63d9800
Author: Stephan Ewen <se...@apache.org>
Authored: Mon Sep 21 19:37:18 2015 +0200
Committer: Stephan Ewen <se...@apache.org>
Committed: Mon Sep 21 23:18:04 2015 +0200

----------------------------------------------------------------------
 .../source/SocketTextStreamFunction.java        | 189 ++++-----
 .../source/SocketTextStreamFunctionTest.java    | 420 +++++++++++++------
 2 files changed, 383 insertions(+), 226 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/bd74baef/flink-staging/flink-streaming/flink-streaming-core/src/main/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunction.java
----------------------------------------------------------------------
diff --git a/flink-staging/flink-streaming/flink-streaming-core/src/main/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunction.java b/flink-staging/flink-streaming/flink-streaming-core/src/main/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunction.java
index 6e7bcf6..9310b71 100644
--- a/flink-staging/flink-streaming/flink-streaming-core/src/main/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunction.java
+++ b/flink-staging/flink-streaming/flink-streaming-core/src/main/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunction.java
@@ -17,133 +17,130 @@
 
 package org.apache.flink.streaming.api.functions.source;
 
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.ConnectException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketException;
+import org.apache.flink.runtime.util.IOUtils;
 
-import org.apache.flink.configuration.Configuration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class SocketTextStreamFunction extends RichSourceFunction<String> {
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.InetSocketAddress;
+import java.net.Socket;
 
-	protected static final Logger LOG = LoggerFactory.getLogger(SocketTextStreamFunction.class);
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * A source function that reads strings from a socket. The source will read bytes from the socket stream
+ * and convert them to characters, each byte individually. When the delimiter character is received,
+ * the function will output the current string, and begin a new string.
+ * <p>
+ * The function strips trailing <i>carriage return</i> characters (\r) when the delimiter is the
+ * newline character (\n).
+ * <p>
+ * The function can be set to reconnect to the server socket in case that the stream is closed on the server side.
+ */
+public class SocketTextStreamFunction implements SourceFunction<String> {
 
 	private static final long serialVersionUID = 1L;
+	
+	private static final Logger LOG = LoggerFactory.getLogger(SocketTextStreamFunction.class);
 
-	private String hostname;
-	private int port;
-	private char delimiter;
-	private long maxRetry;
-	private boolean retryForever;
-	private Socket socket;
-	private static final int CONNECTION_TIMEOUT_TIME = 0;
-	static int CONNECTION_RETRY_SLEEP = 1000;
-	protected long retries;
-
-	private volatile boolean isRunning;
+	/** Default delay between successive connection attempts */
+	private static final int DEFAULT_CONNECTION_RETRY_SLEEP = 500;
 
-	public SocketTextStreamFunction(String hostname, int port, char delimiter, long maxRetry) {
-		this.hostname = hostname;
+	/** Default connection timeout when connecting to the server socket (infinite) */
+	private static final int CONNECTION_TIMEOUT_TIME = 0;
+	
+	
+	private final String hostname;
+	private final int port;
+	private final char delimiter;
+	private final long maxNumRetries;
+	private final long delayBetweenRetries;
+	
+	private transient Socket currentSocket;
+	
+	private volatile boolean isRunning = true;
+
+	
+	public SocketTextStreamFunction(String hostname, int port, char delimiter, long maxNumRetries) {
+		this(hostname, port, delimiter, maxNumRetries, DEFAULT_CONNECTION_RETRY_SLEEP);
+	}
+	
+	public SocketTextStreamFunction(String hostname, int port, char delimiter, long maxNumRetries, long delayBetweenRetries) {
+		checkArgument(port > 0 && port < 65536, "port is out of range");
+		checkArgument(maxNumRetries >= -1, "maxNumRetries must be zero or larger (num retries), or -1 (infinite retries)");
+		checkArgument(delayBetweenRetries >= 0, "delayBetweenRetries must be zero or positive");
+		
+		this.hostname = checkNotNull(hostname, "hostname must not be null");
 		this.port = port;
 		this.delimiter = delimiter;
-		this.maxRetry = maxRetry;
-		this.retryForever = maxRetry < 0;
-	}
-
-	@Override
-	public void open(Configuration parameters) throws Exception {
-		super.open(parameters);
-		socket = new Socket();
-		socket.connect(new InetSocketAddress(hostname, port), CONNECTION_TIMEOUT_TIME);
-		isRunning = true;
+		this.maxNumRetries = maxNumRetries;
+		this.delayBetweenRetries = delayBetweenRetries;
 	}
 
 	@Override
 	public void run(SourceContext<String> ctx) throws Exception {
-		streamFromSocket(ctx, socket);
-	}
+		final StringBuilder buffer = new StringBuilder();
+		long attempt = 0;
+		
+		while (isRunning) {
+			
+			try (Socket socket = new Socket()) {
+				currentSocket = socket;
+				
+				LOG.info("Connecting to server socket " + hostname + ':' + port);
+				socket.connect(new InetSocketAddress(hostname, port), CONNECTION_TIMEOUT_TIME);
+				BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 
-	private void streamFromSocket(SourceContext<String> ctx, Socket socket) throws Exception {
-		try {
-			StringBuilder buffer = new StringBuilder();
-			BufferedReader reader = new BufferedReader(new InputStreamReader(
-					socket.getInputStream()));
-
-			while (isRunning) {
 				int data;
-				try {
-					data = reader.read();
-				} catch (SocketException e) {
-					if (!isRunning) {
-						break;
-					} else {
-						throw e;
+				while (isRunning && (data = reader.read()) != -1) {
+					// check if the string is complete
+					if (data != delimiter) {
+						buffer.append((char) data);
 					}
-				}
-
-				if (data == -1) {
-					socket.close();
-					boolean success = false;
-					retries = 0;
-					while ((retries < maxRetry  || retryForever) && !success) {
-						if (!retryForever) {
-							retries++;
-						}
-						LOG.warn("Lost connection to server socket. Retrying in "
-								+ (CONNECTION_RETRY_SLEEP / 1000) + " seconds...");
-						try {
-							socket = new Socket();
-							socket.connect(new InetSocketAddress(hostname, port),
-									CONNECTION_TIMEOUT_TIME);
-							success = true;
-						} catch (ConnectException ce) {
-							Thread.sleep(CONNECTION_RETRY_SLEEP);
-							socket.close();
+					else {
+						// truncate trailing carriage return
+						if (delimiter == '\n' && buffer.length() > 0 && buffer.charAt(buffer.length() - 1) == '\r') {
+							buffer.setLength(buffer.length() - 1);
 						}
+						ctx.collect(buffer.toString());
+						buffer.setLength(0);
 					}
-
-					if (success) {
-						LOG.info("Server socket is reconnected.");
-					} else {
-						LOG.error("Could not reconnect to server socket.");
-						break;
-					}
-					reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
-					continue;
 				}
+			}
 
-				if (data == delimiter) {
-					ctx.collect(buffer.toString());
-					buffer = new StringBuilder();
-				} else if (data != '\r') { // ignore carriage return
-					buffer.append((char) data);
+			// if we dropped out of this loop due to an EOF, sleep and retry
+			if (isRunning) {
+				attempt++;
+				if (maxNumRetries == -1 || attempt < maxNumRetries) {
+					LOG.warn("Lost connection to server socket. Retrying in " + delayBetweenRetries + " msecs...");
+					Thread.sleep(delayBetweenRetries);
+				}
+				else {
+					// this should probably be here, but some examples expect simple exists of the stream source
+					// throw new EOFException("Reached end of stream and reconnects are not enabled.");
+					break;
 				}
 			}
+		}
 
-			if (buffer.length() > 0) {
-				ctx.collect(buffer.toString());
-			}
-		} finally {
-			socket.close();
+		// collect trailing data
+		if (buffer.length() > 0) {
+			ctx.collect(buffer.toString());
 		}
 	}
 
 	@Override
 	public void cancel() {
 		isRunning = false;
-		if (socket != null && !socket.isClosed()) {
-			try {
-				socket.close();
-			} catch (IOException e) {
-				if (LOG.isErrorEnabled()) {
-					LOG.error("Could not close open socket");
-				}
-			}
+		
+		// we need to close the socket as well, because the Thread.interrupt() function will
+		// not wake the thread in the socketStream.read() method when blocked.
+		Socket theSocket = this.currentSocket;
+		if (theSocket != null) {
+			IOUtils.closeSocket(theSocket);
 		}
 	}
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/bd74baef/flink-staging/flink-streaming/flink-streaming-core/src/test/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunctionTest.java
----------------------------------------------------------------------
diff --git a/flink-staging/flink-streaming/flink-streaming-core/src/test/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunctionTest.java b/flink-staging/flink-streaming/flink-streaming-core/src/test/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunctionTest.java
index 5f16c00..3398451 100644
--- a/flink-staging/flink-streaming/flink-streaming-core/src/test/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunctionTest.java
+++ b/flink-staging/flink-streaming/flink-streaming-core/src/test/java/org/apache/flink/streaming/api/functions/source/SocketTextStreamFunctionTest.java
@@ -18,172 +18,332 @@
 
 package org.apache.flink.streaming.api.functions.source;
 
-import java.io.DataOutputStream;
-import java.net.Socket;
+import org.apache.commons.io.IOUtils;
 
-import org.apache.flink.configuration.Configuration;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mockito;
+import org.apache.flink.streaming.api.watermark.Watermark;
 
-import static java.lang.Thread.sleep;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.verify;
+import org.junit.Test;
 
+import java.io.EOFException;
+import java.io.OutputStreamWriter;
 import java.net.ServerSocket;
-import java.util.concurrent.atomic.AtomicReference;
+import java.net.Socket;
+
+import static org.junit.Assert.*;
 
 /**
  * Tests for the {@link org.apache.flink.streaming.api.functions.source.SocketTextStreamFunction}.
  */
-public class SocketTextStreamFunctionTest{
+public class SocketTextStreamFunctionTest {
 
-	final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
-	private final String host = "127.0.0.1";
-	private final SourceFunction.SourceContext<String> ctx = Mockito.mock(SourceFunction.SourceContext.class);
+	private static final String LOCALHOST = "127.0.0.1";
 
-	public SocketTextStreamFunctionTest() {
+
+	@Test
+	public void testSocketSourceSimpleOutput() throws Exception {
+		ServerSocket server = new ServerSocket(0);
+		Socket channel = null;
+		
+		try {
+			SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), '\n', 0);
+	
+			SocketSourceThread runner = new SocketSourceThread(source, "test1", "check");
+			runner.start();
+	
+			channel = server.accept();
+			OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());
+			
+			writer.write("test1\n");
+			writer.write("check\n");
+			writer.flush();
+			runner.waitForNumElements(2);
+
+			runner.cancel();
+			runner.interrupt();
+			
+			runner.waitUntilDone();
+			
+			channel.close();
+		}
+		finally {
+			if (channel != null) {
+				IOUtils.closeQuietly(channel);
+			}
+			IOUtils.closeQuietly(server);
+		}
 	}
 
-	class SocketSource extends Thread {
+	@Test
+	public void testExitNoRetries() throws Exception {
+		ServerSocket server = new ServerSocket(0);
+		Socket channel = null;
 
-		SocketTextStreamFunction socketSource;
+		try {
+			SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), '\n', 0);
 
-		public SocketSource(ServerSocket serverSo, int maxRetry) throws Exception {
-			this.socketSource =  new SocketTextStreamFunction(host, serverSo.getLocalPort(), '\n', maxRetry);
-		}
+			SocketSourceThread runner = new SocketSourceThread(source);
+			runner.start();
 
-		public void run() {
+			channel = server.accept();
+			channel.close();
+			
 			try {
-				this.socketSource.open(new Configuration());
-				this.socketSource.run(ctx);
-			}catch(Exception e){
-				error.set(e);
+				runner.waitUntilDone();
+			}
+			catch (Exception e) {
+				assertTrue(e.getCause() instanceof EOFException);
 			}
 		}
-
-		public void cancel(){
-			this.socketSource.cancel();
+		finally {
+			if (channel != null) {
+				IOUtils.closeQuietly(channel);
+			}
+			IOUtils.closeQuietly(server);
 		}
 	}
 
 	@Test
-	public void testSocketSourceRetryForever() throws Exception{
-		error.set(null);
-		ServerSocket serverSo = new ServerSocket(0);
-		SocketSource source = new SocketSource(serverSo, -1);
-		source.start();
-
-		int count = 0;
-		Socket channel;
-		while (count < 100) {
-			channel = serverSo.accept();
-			count++;
+	public void testSocketSourceOutputWithRetries() throws Exception {
+		ServerSocket server = new ServerSocket(0);
+		Socket channel = null;
+
+		try {
+			SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), '\n', 10, 100);
+
+			SocketSourceThread runner = new SocketSourceThread(source, "test1", "check");
+			runner.start();
+
+			// first connection: nothing
+			channel = server.accept();
 			channel.close();
-			assertEquals(0, source.socketSource.retries);
-		}
-		source.cancel();
 
-		if (error.get() != null) {
-			Throwable t = error.get();
-			t.printStackTrace();
-			fail("Error in spawned thread: " + t.getMessage());
-		}
+			// second connection: first string
+			channel = server.accept();
+			OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());
+			writer.write("test1\n");
+			writer.close();
+			channel.close();
+
+			// third connection: nothing
+			channel = server.accept();
+			channel.close();
+
+			// forth connection: second string
+			channel = server.accept();
+			writer = new OutputStreamWriter(channel.getOutputStream());
+			writer.write("check\n");
+			writer.flush();
 
-		assertEquals(100, count);
+			runner.waitForNumElements(2);
+			runner.cancel();
+			runner.waitUntilDone();
+		}
+		finally {
+			if (channel != null) {
+				IOUtils.closeQuietly(channel);
+			}
+			IOUtils.closeQuietly(server);
+		}
 	}
 
 	@Test
-	public void testSocketSourceRetryTenTimes() throws Exception{
-		error.set(null);
-		ServerSocket serverSo = new ServerSocket(0);
-		SocketSource source = new SocketSource(serverSo, 10);
-		source.socketSource.CONNECTION_RETRY_SLEEP = 200;
-
-		assertEquals(0, source.socketSource.retries);
-
-		source.start();
-
-		Socket channel;
-		channel = serverSo.accept();
-		channel.close();
-		serverSo.close();
-		while(source.socketSource.retries < 10){
-			long lastRetry = source.socketSource.retries;
-			sleep(100);
-			assertTrue(source.socketSource.retries >= lastRetry);
-		};
-		assertEquals(10, source.socketSource.retries);
-		source.cancel();
-
-		if (error.get() != null) {
-			Throwable t = error.get();
-			t.printStackTrace();
-			fail("Error in spawned thread: " + t.getMessage());
-		}
+	public void testSocketSourceOutputInfiniteRetries() throws Exception {
+		ServerSocket server = new ServerSocket(0);
+		Socket channel = null;
+
+		try {
+			SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), '\n', -1, 100);
+
+			SocketSourceThread runner = new SocketSourceThread(source, "test1", "check");
+			runner.start();
+
+			// first connection: nothing
+			channel = server.accept();
+			channel.close();
+
+			// second connection: first string
+			channel = server.accept();
+			OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());
+			writer.write("test1\n");
+			writer.close();
+			channel.close();
+
+			// third connection: nothing
+			channel = server.accept();
+			channel.close();
 
-		assertEquals(10, source.socketSource.retries);
+			// forth connection: second string
+			channel = server.accept();
+			writer = new OutputStreamWriter(channel.getOutputStream());
+			writer.write("check\n");
+			writer.flush();
+
+			runner.waitForNumElements(2);
+			runner.cancel();
+			runner.waitUntilDone();
+		}
+		finally {
+			if (channel != null) {
+				IOUtils.closeQuietly(channel);
+			}
+			IOUtils.closeQuietly(server);
+		}
 	}
 
 	@Test
-	public void testSocketSourceNeverRetry() throws Exception{
-		error.set(null);
-		ServerSocket serverSo = new ServerSocket(0);
-		SocketSource source = new SocketSource(serverSo, 0);
-		source.start();
-
-		Socket channel;
-		channel = serverSo.accept();
-		channel.close();
-		serverSo.close();
-		sleep(2000);
-		source.cancel();
-
-		if (error.get() != null) {
-			Throwable t = error.get();
-			t.printStackTrace();
-			fail("Error in spawned thread: " + t.getMessage());
-		}
+	public void testSocketSourceOutputAcrossRetries() throws Exception {
+		ServerSocket server = new ServerSocket(0);
+		Socket channel = null;
+
+		try {
+			SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), '\n', 10, 100);
+
+			SocketSourceThread runner = new SocketSourceThread(source, "test1", "check1", "check2");
+			runner.start();
+
+			// first connection: nothing
+			channel = server.accept();
+			channel.close();
+
+			// second connection: first string
+			channel = server.accept();
+			OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());
+			writer.write("te");
+			writer.close();
+			channel.close();
+
+			// third connection: nothing
+			channel = server.accept();
+			channel.close();
 
-		assertEquals(0, source.socketSource.retries);
+			// forth connection: second string
+			channel = server.accept();
+			writer = new OutputStreamWriter(channel.getOutputStream());
+			writer.write("st1\n");
+			writer.write("check1\n");
+			writer.write("check2\n");
+			writer.flush();
+
+			runner.waitForNumElements(2);
+			runner.cancel();
+			runner.waitUntilDone();
+		}
+		finally {
+			if (channel != null) {
+				IOUtils.closeQuietly(channel);
+			}
+			IOUtils.closeQuietly(server);
+		}
 	}
+	
+	// ------------------------------------------------------------------------
+
+	private static class SocketSourceThread extends Thread {
+		
+		private final Object sync = new Object();
+		
+		private final SocketTextStreamFunction socketSource;
+		
+		private final String[] expectedData;
+		
+		private volatile Throwable error;
+		private volatile int numElementsReceived;
+		private volatile boolean canceled;
+		private volatile boolean done;
+		
+		public SocketSourceThread(SocketTextStreamFunction socketSource, String... expectedData) {
+			this.socketSource = socketSource;
+			this.expectedData = expectedData;
+		}
 
-	@Test
-	public void testSocketSourceRetryTenTimesWithFirstPass() throws Exception{
-		ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
-
-		error.set(null);
-		ServerSocket serverSo = new ServerSocket(0);
-		SocketSource source = new SocketSource(serverSo, 10);
-		source.socketSource.CONNECTION_RETRY_SLEEP = 200;
-
-		assertEquals(0, source.socketSource.retries);
-
-		source.start();
-
-		Socket channel;
-		channel = serverSo.accept();
-		DataOutputStream dataOutputStream = new DataOutputStream(channel.getOutputStream());
-		dataOutputStream.write("testFirstSocketpass\n".getBytes());
-		channel.close();
-		serverSo.close();
-		while(source.socketSource.retries < 10){
-			long lastRetry = source.socketSource.retries;
-			sleep(100);
-			assertTrue(source.socketSource.retries >= lastRetry);
-		};
-		assertEquals(10, source.socketSource.retries);
-		source.cancel();
-
-		verify(ctx).collect(argument.capture());
-
-		if (error.get() != null) {
-			Throwable t = error.get();
-			t.printStackTrace();
-			fail("Error in spawned thread: " + t.getMessage());
+		public void run() {
+			try {
+				SourceFunction.SourceContext<String> ctx = new SourceFunction.SourceContext<String>() {
+					
+					private final Object lock = new Object();
+					
+					@Override
+					public void collect(String element) {
+						int pos = numElementsReceived;
+						
+						// make sure waiter know of us
+						synchronized (sync) {
+							numElementsReceived++;
+							sync.notifyAll();
+						}
+						
+						if (expectedData != null && expectedData.length > pos) {
+							assertEquals(expectedData[pos], element);
+						}
+					}
+
+					@Override
+					public void collectWithTimestamp(String element, long timestamp) {
+						collect(element);
+					}
+
+					@Override
+					public void emitWatermark(Watermark mark) {}
+
+					@Override
+					public Object getCheckpointLock() {
+						return lock;
+					}
+
+					@Override
+					public void close() {}
+				};
+				
+				socketSource.run(ctx);
+			}
+			catch (Throwable t) {
+				synchronized (sync) {
+					if (!canceled) {
+						error = t;
+					}
+					sync.notifyAll();
+				}
+			}
+			finally {
+				synchronized (sync) {
+					done = true;
+					sync.notifyAll();
+				}
+			}
+		}
+		
+		public void cancel() {
+			synchronized (sync) {
+				canceled = true;
+				socketSource.cancel();
+				interrupt();
+			}
 		}
 
-		assertEquals("testFirstSocketpass", argument.getValue());
-		assertEquals(10, source.socketSource.retries);
+		public void waitForNumElements(int numElements) throws InterruptedException {
+			synchronized (sync) {
+				while (error == null && !canceled && !done && numElementsReceived < numElements) {
+					sync.wait();
+				}
+
+				if (error != null) {
+					throw new RuntimeException("Error in source thread", error);
+				}
+				if (canceled) {
+					throw new RuntimeException("canceled");
+				}
+				if (done) {
+					throw new RuntimeException("Exited cleanly before expected number of elements");
+				}
+			}
+		}
+
+		public void waitUntilDone() throws InterruptedException {
+			join();
+
+			if (error != null) {
+				throw new RuntimeException("Error in source thread", error);
+			}
+		}
 	}
 }
\ No newline at end of file


[2/4] flink git commit: [FLINK-2648] [FLINK-2717] [runtime] Harden memory release in sorters against asynchronous canceling

Posted by se...@apache.org.
[FLINK-2648] [FLINK-2717] [runtime] Harden memory release in sorters against asynchronous canceling


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

Branch: refs/heads/master
Commit: 435ee4ebb5ec2ac0086e1a5136125ecc1d7c89a8
Parents: bd74bae
Author: Stephan Ewen <se...@apache.org>
Authored: Mon Sep 21 21:05:45 2015 +0200
Committer: Stephan Ewen <se...@apache.org>
Committed: Mon Sep 21 23:18:04 2015 +0200

----------------------------------------------------------------------
 .../operators/GroupReduceCombineDriver.java     | 28 ++++++---
 .../runtime/operators/ReduceCombineDriver.java  | 26 +++++---
 .../chaining/GroupCombineChainedDriver.java     | 45 ++++++++------
 .../SynchronousChainedCombineDriver.java        | 51 ++++++++--------
 .../operators/sort/FixedLengthRecordSorter.java | 37 +++---------
 .../runtime/operators/sort/InMemorySorter.java  | 22 ++++---
 .../operators/sort/NormalizedKeySorter.java     | 39 +++---------
 .../operators/sort/UnilateralSortMerger.java    | 18 +++---
 .../sort/FixedLengthRecordSorterTest.java       | 32 +++++-----
 .../operators/sort/NormalizedKeySorterTest.java | 63 ++++++++++----------
 10 files changed, 176 insertions(+), 185 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
index 7115a4d..ab46d95 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
@@ -74,10 +74,10 @@ public class GroupReduceCombineDriver<IN, OUT> implements PactDriver<GroupCombin
 
 	private QuickSort sortAlgo = new QuickSort();
 
-	private MemoryManager memManager;
-
 	private Collector<OUT> output;
 
+	private List<MemorySegment> memory;
+
 	private long oversizedRecordCount;
 
 	private volatile boolean running = true;
@@ -115,9 +115,8 @@ public class GroupReduceCombineDriver<IN, OUT> implements PactDriver<GroupCombin
 		if (driverStrategy != DriverStrategy.SORTED_GROUP_COMBINE){
 			throw new Exception("Invalid strategy " + driverStrategy + " for group reduce combiner.");
 		}
-
-		this.memManager = this.taskContext.getMemoryManager();
-		final int numMemoryPages = memManager.computeNumberOfPages(this.taskContext.getTaskConfig().getRelativeMemoryDriver());
+		
+		
 
 		final TypeSerializerFactory<IN> serializerFactory = this.taskContext.getInputSerializer(0);
 		this.serializer = serializerFactory.getSerializer();
@@ -128,8 +127,9 @@ public class GroupReduceCombineDriver<IN, OUT> implements PactDriver<GroupCombin
 		this.combiner = this.taskContext.getStub();
 		this.output = this.taskContext.getOutputCollector();
 
-		final List<MemorySegment> memory = this.memManager.allocatePages(this.taskContext.getOwningNepheleTask(),
-				numMemoryPages);
+		MemoryManager memManager = this.taskContext.getMemoryManager();
+		final int numMemoryPages = memManager.computeNumberOfPages(this.taskContext.getTaskConfig().getRelativeMemoryDriver());
+		this.memory = memManager.allocatePages(this.taskContext.getOwningNepheleTask(), numMemoryPages);
 
 		// instantiate a fix-length in-place sorter, if possible, otherwise the out-of-place sorter
 		if (sortingComparator.supportsSerializationWithKeyNormalization() &&
@@ -218,16 +218,26 @@ public class GroupReduceCombineDriver<IN, OUT> implements PactDriver<GroupCombin
 	@Override
 	public void cleanup() throws Exception {
 		if (this.sorter != null) {
-			this.memManager.release(this.sorter.dispose());
+			this.sorter.dispose();
 		}
+
+		this.taskContext.getMemoryManager().release(this.memory);
 	}
 
 	@Override
 	public void cancel() {
 		this.running = false;
+		
 		if (this.sorter != null) {
-			this.memManager.release(this.sorter.dispose());
+			try {
+				this.sorter.dispose();
+			}
+			catch (Exception e) {
+				// may happen during concurrent modification
+			}
 		}
+
+		this.taskContext.getMemoryManager().release(this.memory);
 	}
 
 	/**

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
index 19557bc..26da0ab 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
@@ -63,12 +63,12 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 	
 	private Collector<T> output;
 	
-	private MemoryManager memManager;
-	
 	private InMemorySorter<T> sorter;
 	
 	private QuickSort sortAlgo = new QuickSort();
 
+	private List<MemorySegment> memory;
+
 	private boolean running;
 
 	private boolean objectReuseEnabled = false;
@@ -105,10 +105,6 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 			throw new Exception("Invalid strategy " + this.taskContext.getTaskConfig().getDriverStrategy() + " for reduce combiner.");
 		}
 		
-		this.memManager = this.taskContext.getMemoryManager();
-		final int numMemoryPages = memManager.computeNumberOfPages(this.taskContext.getTaskConfig()
-				.getRelativeMemoryDriver());
-		
 		// instantiate the serializer / comparator
 		final TypeSerializerFactory<T> serializerFactory = this.taskContext.getInputSerializer(0);
 		this.comparator = this.taskContext.getDriverComparator(0);
@@ -116,7 +112,10 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 		this.reducer = this.taskContext.getStub();
 		this.output = this.taskContext.getOutputCollector();
 
-		final List<MemorySegment> memory = this.memManager.allocatePages(this.taskContext.getOwningNepheleTask(), numMemoryPages);
+		MemoryManager memManager = this.taskContext.getMemoryManager();
+		final int numMemoryPages = memManager.computeNumberOfPages(
+				this.taskContext.getTaskConfig().getRelativeMemoryDriver());
+		this.memory = memManager.allocatePages(this.taskContext.getOwningNepheleTask(), numMemoryPages);
 
 		// instantiate a fix-length in-place sorter, if possible, otherwise the out-of-place sorter
 		if (this.comparator.supportsSerializationWithKeyNormalization() &&
@@ -241,12 +240,21 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 
 	@Override
 	public void cleanup() {
-		this.memManager.release(this.sorter.dispose());
+		this.sorter.dispose();
+		this.taskContext.getMemoryManager().release(this.memory);
 	}
 
 	@Override
 	public void cancel() {
 		this.running = false;
-		this.memManager.release(this.sorter.dispose());
+		
+		try {
+			this.sorter.dispose();
+		}
+		catch (Exception e) {
+			// may happen during concurrent modifications
+		}
+
+		this.taskContext.getMemoryManager().release(this.memory);
 	}
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
index 09f4288..08ad25b 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
@@ -71,15 +71,13 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 
 	private TypeSerializer<IN> serializer;
 
-	private TypeComparator<IN> sortingComparator;
-
 	private TypeComparator<IN> groupingComparator;
 
 	private AbstractInvokable parent;
 
 	private QuickSort sortAlgo = new QuickSort();
 
-	private MemoryManager memManager;
+	private List<MemorySegment> memory;
 
 	private volatile boolean running = true;
 
@@ -102,28 +100,28 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 		final Configuration stubConfig = this.config.getStubParameters();
 		RegularPactTask.openUserCode(this.reducer, stubConfig);
 
-		// ----------------- Set up the asynchronous sorter -------------------------
-
-		this.memManager = this.parent.getEnvironment().getMemoryManager();
-		final int numMemoryPages = memManager.computeNumberOfPages(this.config.getRelativeMemoryDriver());
+		// ----------------- Set up the sorter -------------------------
 
 		// instantiate the serializer / comparator
 		final TypeSerializerFactory<IN> serializerFactory = this.config.getInputSerializer(0, this.userCodeClassLoader);
 		final TypeComparatorFactory<IN> sortingComparatorFactory = this.config.getDriverComparator(0, this.userCodeClassLoader);
 		final TypeComparatorFactory<IN> groupingComparatorFactory = this.config.getDriverComparator(1, this.userCodeClassLoader);
 		this.serializer = serializerFactory.getSerializer();
-		this.sortingComparator = sortingComparatorFactory.createComparator();
+		
+		TypeComparator<IN> sortingComparator = sortingComparatorFactory.createComparator();
 		this.groupingComparator = groupingComparatorFactory.createComparator();
 
-		final List<MemorySegment> memory = this.memManager.allocatePages(this.parent, numMemoryPages);
+		MemoryManager memManager = this.parent.getEnvironment().getMemoryManager();
+		final int numMemoryPages = memManager.computeNumberOfPages(this.config.getRelativeMemoryDriver());
+		this.memory = memManager.allocatePages(this.parent, numMemoryPages);
 
 		// instantiate a fix-length in-place sorter, if possible, otherwise the out-of-place sorter
-		if (this.sortingComparator.supportsSerializationWithKeyNormalization() &&
+		if (sortingComparator.supportsSerializationWithKeyNormalization() &&
 			this.serializer.getLength() > 0 && this.serializer.getLength() <= THRESHOLD_FOR_IN_PLACE_SORTING)
 		{
-			this.sorter = new FixedLengthRecordSorter<IN>(this.serializer, this.sortingComparator, memory);
+			this.sorter = new FixedLengthRecordSorter<IN>(this.serializer, sortingComparator, memory);
 		} else {
-			this.sorter = new NormalizedKeySorter<IN>(this.serializer, this.sortingComparator.duplicate(), memory);
+			this.sorter = new NormalizedKeySorter<IN>(this.serializer, sortingComparator.duplicate(), memory);
 		}
 
 		if (LOG.isDebugEnabled()) {
@@ -133,19 +131,30 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 
 	@Override
 	public void closeTask() throws Exception {
-		this.memManager.release(this.sorter.dispose());
-
-		if (!this.running) {
-			return;
+		if (this.sorter != null) {
+			this.sorter.dispose();
 		}
+		this.parent.getEnvironment().getMemoryManager().release(this.memory);
 
-		RegularPactTask.closeUserCode(this.reducer);
+		if (this.running) {
+			RegularPactTask.closeUserCode(this.reducer);
+		}
 	}
 
 	@Override
 	public void cancelTask() {
 		this.running = false;
-		this.memManager.release(this.sorter.dispose());
+
+		if (this.sorter != null) {
+			try {
+				this.sorter.dispose();
+			}
+			catch (Exception e) {
+				// may happen during concurrent modification
+			}
+		}
+		
+		this.parent.getEnvironment().getMemoryManager().release(this.memory);
 	}
 
 	// --------------------------------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/SynchronousChainedCombineDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/SynchronousChainedCombineDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/SynchronousChainedCombineDriver.java
index 75c1eed..da9698c 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/SynchronousChainedCombineDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/SynchronousChainedCombineDriver.java
@@ -58,9 +58,7 @@ public class SynchronousChainedCombineDriver<IN, OUT> extends ChainedDriver<IN,
 	private static final Logger LOG = LoggerFactory.getLogger(SynchronousChainedCombineDriver.class);
 
 
-	/**
-	 * Fix length records with a length below this threshold will be in-place sorted, if possible.
-	 */
+	/** Fix length records with a length below this threshold will be in-place sorted, if possible. */
 	private static final int THRESHOLD_FOR_IN_PLACE_SORTING = 32;
 
 	// --------------------------------------------------------------------------------------------
@@ -71,16 +69,14 @@ public class SynchronousChainedCombineDriver<IN, OUT> extends ChainedDriver<IN,
 
 	private TypeSerializer<IN> serializer;
 
-	private TypeComparator<IN> sortingComparator;
-
 	private TypeComparator<IN> groupingComparator;
 
 	private AbstractInvokable parent;
 
-	private QuickSort sortAlgo = new QuickSort();
-
-	private MemoryManager memManager;
+	private final QuickSort sortAlgo = new QuickSort();
 
+	private List<MemorySegment> memory;
+	
 	private volatile boolean running = true;
 
 	// --------------------------------------------------------------------------------------------
@@ -102,28 +98,29 @@ public class SynchronousChainedCombineDriver<IN, OUT> extends ChainedDriver<IN,
 		final Configuration stubConfig = this.config.getStubParameters();
 		RegularPactTask.openUserCode(this.combiner, stubConfig);
 
-		// ----------------- Set up the asynchronous sorter -------------------------
-
-		this.memManager = this.parent.getEnvironment().getMemoryManager();
-		final int numMemoryPages = memManager.computeNumberOfPages(this.config.getRelativeMemoryDriver());
+		// ----------------- Set up the sorter -------------------------
 
 		// instantiate the serializer / comparator
 		final TypeSerializerFactory<IN> serializerFactory = this.config.getInputSerializer(0, this.userCodeClassLoader);
 		final TypeComparatorFactory<IN> sortingComparatorFactory = this.config.getDriverComparator(0, this.userCodeClassLoader);
 		final TypeComparatorFactory<IN> groupingComparatorFactory = this.config.getDriverComparator(1, this.userCodeClassLoader);
+		
 		this.serializer = serializerFactory.getSerializer();
-		this.sortingComparator = sortingComparatorFactory.createComparator();
-		this.groupingComparator = groupingComparatorFactory.createComparator();
 
-		final List<MemorySegment> memory = this.memManager.allocatePages(this.parent, numMemoryPages);
+		TypeComparator<IN> sortingComparator = sortingComparatorFactory.createComparator();
+		this.groupingComparator = groupingComparatorFactory.createComparator();
+		
+		MemoryManager memManager = this.parent.getEnvironment().getMemoryManager();
+		final int numMemoryPages = memManager.computeNumberOfPages(this.config.getRelativeMemoryDriver());
+		this.memory = memManager.allocatePages(this.parent, numMemoryPages);
 
 		// instantiate a fix-length in-place sorter, if possible, otherwise the out-of-place sorter
-		if (this.sortingComparator.supportsSerializationWithKeyNormalization() &&
+		if (sortingComparator.supportsSerializationWithKeyNormalization() &&
 			this.serializer.getLength() > 0 && this.serializer.getLength() <= THRESHOLD_FOR_IN_PLACE_SORTING)
 		{
-			this.sorter = new FixedLengthRecordSorter<IN>(this.serializer, this.sortingComparator, memory);
+			this.sorter = new FixedLengthRecordSorter<IN>(this.serializer, sortingComparator, this.memory);
 		} else {
-			this.sorter = new NormalizedKeySorter<IN>(this.serializer, this.sortingComparator.duplicate(), memory);
+			this.sorter = new NormalizedKeySorter<IN>(this.serializer, sortingComparator.duplicate(), this.memory);
 		}
 
 		if (LOG.isDebugEnabled()) {
@@ -133,19 +130,25 @@ public class SynchronousChainedCombineDriver<IN, OUT> extends ChainedDriver<IN,
 
 	@Override
 	public void closeTask() throws Exception {
-		this.memManager.release(this.sorter.dispose());
+		this.sorter.dispose();
+		this.parent.getEnvironment().getMemoryManager().release(this.memory);
 
-		if (!this.running) {
-			return;
+		if (this.running) {
+			RegularPactTask.closeUserCode(this.combiner);
 		}
-
-		RegularPactTask.closeUserCode(this.combiner);
 	}
 
 	@Override
 	public void cancelTask() {
 		this.running = false;
-		this.memManager.release(this.sorter.dispose());
+		try {
+			this.sorter.dispose();
+		}
+		catch (Exception e) {
+			// may happen during concurrent modification when canceling
+		}
+		
+		this.parent.getEnvironment().getMemoryManager().release(this.memory);
 	}
 
 	// --------------------------------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java
index e932592..da96b17 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java
@@ -121,13 +121,7 @@ public final class FixedLengthRecordSorter<T> implements InMemorySorter<T> {
 		this.lastEntryOffset = (this.recordsPerSegment - 1) * this.recordSize;
 		this.swapBuffer = new byte[this.recordSize];
 		
-		if (memory instanceof ArrayList<?>) {
-			this.freeMemory = (ArrayList<MemorySegment>) memory;
-		}
-		else {
-			this.freeMemory = new ArrayList<MemorySegment>(memory.size());
-			this.freeMemory.addAll(memory);
-		}
+		this.freeMemory = new ArrayList<MemorySegment>(memory);
 		
 		// create the buffer collections
 		this.sortBuffer = new ArrayList<MemorySegment>(16);
@@ -174,16 +168,10 @@ public final class FixedLengthRecordSorter<T> implements InMemorySorter<T> {
 		return this.numRecords == 0;
 	}
 	
-	/**
-	 * Collects all memory segments from this sorter.
-	 * 
-	 * @return All memory segments from this sorter.
-	 */
 	@Override
-	public List<MemorySegment> dispose() {
-		this.freeMemory.addAll(this.sortBuffer);
+	public void dispose() {
+		this.freeMemory.clear();
 		this.sortBuffer.clear();
-		return this.freeMemory;
 	}
 	
 	@Override
@@ -195,23 +183,16 @@ public final class FixedLengthRecordSorter<T> implements InMemorySorter<T> {
 	public long getOccupancy() {
 		return this.sortBufferBytes;
 	}
-	
-	@Override
-	public long getNumRecordBytes() {
-		return this.sortBufferBytes;
-	}
 
 	// -------------------------------------------------------------------------
 	// Retrieving and Writing
 	// -------------------------------------------------------------------------
-
-	/**
-	 * Gets the record at the given logical position.
-	 * 
-	 * @param reuse The reuse object to deserialize the record into.
-	 * @param logicalPosition The logical position of the record.
-	 * @throws IOException Thrown, if an exception occurred during deserialization.
-	 */
+	
+	@Override
+	public T getRecord(int logicalPosition) throws IOException {
+		return getRecord(serializer.createInstance(), logicalPosition);
+	}
+	
 	@Override
 	public T getRecord(T reuse, int logicalPosition) throws IOException {
 		final int buffer = logicalPosition / this.recordsPerSegment;

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/InMemorySorter.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/InMemorySorter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/InMemorySorter.java
index 633ec70..a47041b 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/InMemorySorter.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/InMemorySorter.java
@@ -19,9 +19,7 @@
 package org.apache.flink.runtime.operators.sort;
 
 import java.io.IOException;
-import java.util.List;
 
-import org.apache.flink.core.memory.MemorySegment;
 import org.apache.flink.runtime.io.disk.iomanager.ChannelWriterOutputView;
 import org.apache.flink.util.MutableObjectIterator;
 
@@ -43,11 +41,10 @@ public interface InMemorySorter<T> extends IndexedSortable {
 	boolean isEmpty();
 	
 	/**
-	 * Collects all memory segments from this sorter.
-	 * 
-	 * @return All memory segments from this sorter.
+	 * Disposes the sorter.
+	 * This method does not release the memory segments used by the sorter.
 	 */
-	List<MemorySegment> dispose();
+	void dispose();
 	
 	/**
 	 * Gets the total capacity of this sorter, in bytes.
@@ -62,13 +59,14 @@ public interface InMemorySorter<T> extends IndexedSortable {
 	 * @return The number of bytes occupied.
 	 */
 	long getOccupancy();
-	
+
 	/**
-	 * Gets the number of bytes occupied by records only.
-	 * 
-	 * @return The number of bytes occupied by records.
+	 * Gets the record at the given logical position.
+	 *
+	 * @param logicalPosition The logical position of the record.
+	 * @throws IOException Thrown, if an exception occurred during deserialization.
 	 */
-	long getNumRecordBytes();
+	T getRecord(int logicalPosition) throws IOException;
 	
 	/**
 	 * Gets the record at the given logical position.
@@ -114,5 +112,5 @@ public interface InMemorySorter<T> extends IndexedSortable {
 	 * @param num The number of elements to write.
 	 * @throws IOException Thrown, if an I/O exception occurred writing to the output view.
 	 */
-	public void writeToOutput(final ChannelWriterOutputView output, final int start, int num) throws IOException;
+	public void writeToOutput(ChannelWriterOutputView output, int start, int num) throws IOException;
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorter.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorter.java
index c05e518..9e1882c 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorter.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorter.java
@@ -133,14 +133,7 @@ public final class NormalizedKeySorter<T> implements InMemorySorter<T> {
 			throw new IllegalArgumentException("Normalized-Key sorter requires at least " + MIN_REQUIRED_BUFFERS + " memory buffers.");
 		}
 		this.segmentSize = memory.get(0).size();
-		
-		if (memory instanceof ArrayList<?>) {
-			this.freeMemory = (ArrayList<MemorySegment>) memory;
-		}
-		else {
-			this.freeMemory = new ArrayList<MemorySegment>(memory.size());
-			this.freeMemory.addAll(memory);
-		}
+		this.freeMemory = new ArrayList<MemorySegment>(memory);
 		
 		// create the buffer collections
 		this.sortIndex = new ArrayList<MemorySegment>(16);
@@ -220,20 +213,11 @@ public final class NormalizedKeySorter<T> implements InMemorySorter<T> {
 		return this.numRecords == 0;
 	}
 	
-	/**
-	 * Collects all memory segments from this sorter.
-	 * 
-	 * @return All memory segments from this sorter.
-	 */
 	@Override
-	public List<MemorySegment> dispose() {
-		this.freeMemory.addAll(this.sortIndex);
-		this.freeMemory.addAll(this.recordBufferSegments);
-		
+	public void dispose() {
+		this.freeMemory.clear();
 		this.recordBufferSegments.clear();
 		this.sortIndex.clear();
-		
-		return this.freeMemory;
 	}
 	
 	@Override
@@ -245,23 +229,16 @@ public final class NormalizedKeySorter<T> implements InMemorySorter<T> {
 	public long getOccupancy() {
 		return this.currentDataBufferOffset + this.sortIndexBytes;
 	}
-	
-	@Override
-	public long getNumRecordBytes() {
-		return this.currentDataBufferOffset;
-	}
 
 	// -------------------------------------------------------------------------
 	// Retrieving and Writing
 	// -------------------------------------------------------------------------
 
-	/**
-	 * Gets the record at the given logical position.
-	 * 
-	 * @param reuse The target object to deserialize the record into.
-	 * @param logicalPosition The logical position of the record.
-	 * @throws IOException Thrown, if an exception occurred during deserialization.
-	 */
+	@Override
+	public T getRecord(int logicalPosition) throws IOException {
+		return getRecordFromBuffer(readPointer(logicalPosition));
+	}
+	
 	@Override
 	public T getRecord(T reuse, int logicalPosition) throws IOException {
 		return getRecordFromBuffer(reuse, readPointer(logicalPosition));

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/UnilateralSortMerger.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/UnilateralSortMerger.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/UnilateralSortMerger.java
index 32fbb52..13159d9 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/UnilateralSortMerger.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/UnilateralSortMerger.java
@@ -342,7 +342,7 @@ public class UnilateralSortMerger<E> implements Sorter<E> {
 			}
 
 			// add to empty queue
-			CircularElement<E> element = new CircularElement<E>(i, buffer);
+			CircularElement<E> element = new CircularElement<E>(i, buffer, sortSegments);
 			circularQueues.empty.add(element);
 		}
 
@@ -686,15 +686,18 @@ public class UnilateralSortMerger<E> implements Sorter<E> {
 		
 		final int id;
 		final InMemorySorter<E> buffer;
+		final List<MemorySegment> memory;
 
 		public CircularElement() {
 			this.id = -1;
 			this.buffer = null;
+			this.memory = null;
 		}
 
-		public CircularElement(int id, InMemorySorter<E> buffer) {
+		public CircularElement(int id, InMemorySorter<E> buffer, List<MemorySegment> memory) {
 			this.id = id;
 			this.buffer = buffer;
+			this.memory = memory;
 		}
 	}
 
@@ -1199,7 +1202,7 @@ public class UnilateralSortMerger<E> implements Sorter<E> {
 		public void go() throws IOException {
 			
 			final Queue<CircularElement<E>> cache = new ArrayDeque<CircularElement<E>>();
-			CircularElement<E> element = null;
+			CircularElement<E> element;
 			boolean cacheOnly = false;
 			
 			// ------------------- In-Memory Cache ------------------------
@@ -1236,7 +1239,8 @@ public class UnilateralSortMerger<E> implements Sorter<E> {
 				
 				CircularElement<E> circElement;
 				while ((circElement = this.queues.empty.poll()) != null) {
-					memoryForLargeRecordSorting.addAll(circElement.buffer.dispose());
+					circElement.buffer.dispose();
+					memoryForLargeRecordSorting.addAll(circElement.memory);
 				}
 				
 				if (memoryForLargeRecordSorting.isEmpty()) {
@@ -1440,10 +1444,10 @@ public class UnilateralSortMerger<E> implements Sorter<E> {
 		protected final void disposeSortBuffers(boolean releaseMemory) {
 			while (!this.queues.empty.isEmpty()) {
 				try {
-					final InMemorySorter<?> sorter = this.queues.empty.take().buffer;
-					final List<MemorySegment> sorterMem = sorter.dispose();
+					CircularElement<E> element = this.queues.empty.take();
+					element.buffer.dispose();
 					if (releaseMemory) {
-						this.memManager.release(sorterMem);
+						this.memManager.release(element.memory);
 					}
 				}
 				catch (InterruptedException iex) {

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorterTest.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorterTest.java
index f40171a..517bec3 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorterTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorterTest.java
@@ -33,14 +33,12 @@ import org.apache.flink.runtime.operators.testutils.types.IntPair;
 import org.apache.flink.runtime.operators.testutils.types.IntPairComparator;
 import org.apache.flink.runtime.operators.testutils.types.IntPairSerializer;
 import org.apache.flink.util.MutableObjectIterator;
+
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-/**
- * 
- */
 public class FixedLengthRecordSorterTest {
 	
 	private static final long SEED = 649180756312423613L;
@@ -125,7 +123,8 @@ public class FixedLengthRecordSorterTest {
 //		System.out.println("RECORDS " + num);
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
@@ -170,7 +169,8 @@ public class FixedLengthRecordSorterTest {
 		Assert.assertEquals("Incorrect number of records", num, count);
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
@@ -225,7 +225,8 @@ public class FixedLengthRecordSorterTest {
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	/**
@@ -276,7 +277,8 @@ public class FixedLengthRecordSorterTest {
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	/**
@@ -318,7 +320,8 @@ public class FixedLengthRecordSorterTest {
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
@@ -345,11 +348,10 @@ public class FixedLengthRecordSorterTest {
 		MutableObjectIterator<IntPair> iter = sorter.getIterator();
 		IntPair readTarget = new IntPair();
 		
-		int current = 0;
-		int last = 0;
+		int current;
+		int last;
 		
 		iter.next(readTarget);
-		//readTarget.getFieldInto(0, last);
 		last = readTarget.getKey();
 		
 		while ((readTarget = iter.next(readTarget)) != null) {
@@ -359,13 +361,11 @@ public class FixedLengthRecordSorterTest {
 			if (cmp > 0) {
 				Assert.fail("Next key is not larger or equal to previous key.");
 			}
-			
-			int tmp = current;
-			current = last;
-			last = tmp;
+			last = current;
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 }

http://git-wip-us.apache.org/repos/asf/flink/blob/435ee4eb/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorterTest.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorterTest.java
index 3e941dd..f8a8f11 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorterTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/sort/NormalizedKeySorterTest.java
@@ -35,15 +35,15 @@ import org.apache.flink.runtime.operators.testutils.TestData.Generator.KeyMode;
 import org.apache.flink.runtime.operators.testutils.TestData.Generator.ValueMode;
 import org.apache.flink.types.Record;
 import org.apache.flink.util.MutableObjectIterator;
+
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-/**
- */
-public class NormalizedKeySorterTest
-{
+
+public class NormalizedKeySorterTest {
+	
 	private static final long SEED = 649180756312423613L;
 	
 	private static final long SEED2 = 97652436586326573L;
@@ -76,16 +76,14 @@ public class NormalizedKeySorterTest
 		}
 	}
 
-	private NormalizedKeySorter<Record> newSortBuffer(List<MemorySegment> memory) throws Exception
-	{
-		@SuppressWarnings("unchecked")
-		RecordComparator accessors = new RecordComparator(new int[] {0}, new Class[]{Key.class});
+	private NormalizedKeySorter<Record> newSortBuffer(List<MemorySegment> memory) throws Exception {
+		@SuppressWarnings({"unchecked", "rawtypes"})
+		RecordComparator accessors = new RecordComparator(new int[] {0}, new Class[]{ Key.class });
 		return new NormalizedKeySorter<Record>(RecordSerializer.get(), accessors, memory);
 	}
 
 	@Test
-	public void testWriteAndRead() throws Exception
-	{
+	public void testWriteAndRead() throws Exception {
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
 		
@@ -122,12 +120,12 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
-	public void testWriteAndIterator() throws Exception
-	{
+	public void testWriteAndIterator() throws Exception {
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
 		
@@ -161,12 +159,12 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
-	public void testReset() throws Exception
-	{
+	public void testReset() throws Exception {
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
 		
@@ -217,7 +215,8 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	/**
@@ -226,8 +225,7 @@ public class NormalizedKeySorterTest
 	 * and compares for equality.
 	 */
 	@Test
-	public void testSwap() throws Exception
-	{
+	public void testSwap() throws Exception {
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
 		
@@ -270,7 +268,8 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	/**
@@ -279,8 +278,7 @@ public class NormalizedKeySorterTest
 	 * ones.
 	 */
 	@Test
-	public void testCompare() throws Exception
-	{
+	public void testCompare() throws Exception {
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
 		
@@ -314,12 +312,12 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
-	public void testSort() throws Exception
-	{
+	public void testSort() throws Exception {
 		final int NUM_RECORDS = 559273;
 		
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
@@ -364,15 +362,16 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
 	public void testSortShortStringKeys() throws Exception {
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
-		
-		@SuppressWarnings("unchecked")
+
+		@SuppressWarnings({"unchecked", "rawtypes"})
 		RecordComparator accessors = new RecordComparator(new int[] {1}, new Class[]{Value.class});
 		NormalizedKeySorter<Record> sorter = new NormalizedKeySorter<Record>(RecordSerializer.get(), accessors, memory);
 		
@@ -412,7 +411,8 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 	
 	@Test
@@ -420,7 +420,7 @@ public class NormalizedKeySorterTest
 		final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
 		final List<MemorySegment> memory = this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
 		
-		@SuppressWarnings("unchecked")
+		@SuppressWarnings({"unchecked", "rawtypes"})
 		RecordComparator accessors = new RecordComparator(new int[] {1}, new Class[]{Value.class});
 		NormalizedKeySorter<Record> sorter = new NormalizedKeySorter<Record>(RecordSerializer.get(), accessors, memory);
 		
@@ -460,6 +460,7 @@ public class NormalizedKeySorterTest
 		}
 		
 		// release the memory occupied by the buffers
-		this.memoryManager.release(sorter.dispose());
+		sorter.dispose();
+		this.memoryManager.release(memory);
 	}
 }


[3/4] flink git commit: [FLINK-2724] [runtime] Fix object reuse in GroupReduceCombineDriver and ReduceCombineDriver

Posted by se...@apache.org.
[FLINK-2724] [runtime] Fix object reuse in GroupReduceCombineDriver and ReduceCombineDriver


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

Branch: refs/heads/master
Commit: f3809d8272e9b1f611770cdfb71fe17c3feb08e6
Parents: 435ee4e
Author: Stephan Ewen <se...@apache.org>
Authored: Mon Sep 21 21:27:38 2015 +0200
Committer: Stephan Ewen <se...@apache.org>
Committed: Mon Sep 21 23:18:04 2015 +0200

----------------------------------------------------------------------
 .../operators/GroupReduceCombineDriver.java     | 62 +++++++++++++-------
 .../runtime/operators/ReduceCombineDriver.java  | 56 ++++++++++++------
 .../chaining/GroupCombineChainedDriver.java     | 32 ++++------
 3 files changed, 89 insertions(+), 61 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/f3809d82/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
index ab46d95..c6a872c 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java
@@ -157,29 +157,29 @@ public class GroupReduceCombineDriver<IN, OUT> implements PactDriver<GroupCombin
 		final MutableObjectIterator<IN> in = this.taskContext.getInput(0);
 		final TypeSerializer<IN> serializer = this.serializer;
 
-		IN value = serializer.createInstance();
-
-		while (running && (value = in.next(value)) != null) {
-
-			// try writing to the sorter first
-			if (this.sorter.write(value)) {
-				continue;
+		if (objectReuseEnabled) {
+			IN value = serializer.createInstance();
+	
+			while (running && (value = in.next(value)) != null) {
+				// try writing to the sorter first
+				if (this.sorter.write(value)) {
+					continue;
+				}
+	
+				// do the actual sorting, combining, and data writing
+				sortAndCombineAndRetryWrite(value);
 			}
-
-			// do the actual sorting, combining, and data writing
-			sortAndCombine();
-			this.sorter.reset();
-
-			// write the value again
-			if (!this.sorter.write(value)) {
-				
-				++oversizedRecordCount;
-				LOG.debug("Cannot write record to fresh sort buffer, record is too large. " +
-								"Oversized record count: {}", oversizedRecordCount);
-				
-				// simply forward the record. We need to pass it through the combine function to convert it
-				Iterable<IN> input = Collections.singleton(value);
-				this.combiner.combine(input, this.output);
+		}
+		else {
+			IN value;
+			while (running && (value = in.next()) != null) {
+				// try writing to the sorter first
+				if (this.sorter.write(value)) {
+					continue;
+				}
+
+				// do the actual sorting, combining, and data writing
+				sortAndCombineAndRetryWrite(value);
 			}
 		}
 
@@ -214,6 +214,24 @@ public class GroupReduceCombineDriver<IN, OUT> implements PactDriver<GroupCombin
 			}
 		}
 	}
+	
+	private void sortAndCombineAndRetryWrite(IN value) throws Exception {
+		sortAndCombine();
+		this.sorter.reset();
+
+		// write the value again
+		if (!this.sorter.write(value)) {
+
+			++oversizedRecordCount;
+			LOG.debug("Cannot write record to fresh sort buffer, record is too large. " +
+					"Oversized record count: {}", oversizedRecordCount);
+
+			// simply forward the record. We need to pass it through the combine function to convert it
+			Iterable<IN> input = Collections.singleton(value);
+			this.combiner.combine(input, this.output);
+			this.sorter.reset();
+		}
+	}
 
 	@Override
 	public void cleanup() throws Exception {

http://git-wip-us.apache.org/repos/asf/flink/blob/f3809d82/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
index 26da0ab..f990156 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/ReduceCombineDriver.java
@@ -143,22 +143,43 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 		final MutableObjectIterator<T> in = this.taskContext.getInput(0);
 		final TypeSerializer<T> serializer = this.serializer;
 		
-		T value = serializer.createInstance();
+		if (objectReuseEnabled) {
+			T value = serializer.createInstance();
 		
-		while (running && (value = in.next(value)) != null) {
-			
-			// try writing to the sorter first
-			if (this.sorter.write(value)) {
-				continue;
+			while (running && (value = in.next(value)) != null) {
+				
+				// try writing to the sorter first
+				if (this.sorter.write(value)) {
+					continue;
+				}
+		
+				// do the actual sorting, combining, and data writing
+				sortAndCombine();
+				this.sorter.reset();
+				
+				// write the value again
+				if (!this.sorter.write(value)) {
+					throw new IOException("Cannot write record to fresh sort buffer. Record too large.");
+				}
 			}
-	
-			// do the actual sorting, combining, and data writing
-			sortAndCombine();
-			this.sorter.reset();
-			
-			// write the value again
-			if (!this.sorter.write(value)) {
-				throw new IOException("Cannot write record to fresh sort buffer. Record too large.");
+		}
+		else {
+			T value;
+			while (running && (value = in.next()) != null) {
+
+				// try writing to the sorter first
+				if (this.sorter.write(value)) {
+					continue;
+				}
+
+				// do the actual sorting, combining, and data writing
+				sortAndCombine();
+				this.sorter.reset();
+
+				// write the value again
+				if (!this.sorter.write(value)) {
+					throw new IOException("Cannot write record to fresh sort buffer. Record too large.");
+				}
 			}
 		}
 		
@@ -174,11 +195,8 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 			
 			final TypeSerializer<T> serializer = this.serializer;
 			final TypeComparator<T> comparator = this.comparator;
-			
 			final ReduceFunction<T> function = this.reducer;
-			
 			final Collector<T> output = this.output;
-			
 			final MutableObjectIterator<T> input = sorter.getIterator();
 
 			if (objectReuseEnabled) {
@@ -214,7 +232,7 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 					}
 				}
 			} else {
-				T value = input.next(serializer.createInstance());
+				T value = input.next();
 
 				// iterate over key groups
 				while (this.running && value != null) {
@@ -222,7 +240,7 @@ public class ReduceCombineDriver<T> implements PactDriver<ReduceFunction<T>, T>
 					T res = value;
 
 					// iterate within a key group
-					while ((value = input.next(serializer.createInstance())) != null) {
+					while ((value = input.next()) != null) {
 						if (comparator.equalToReference(value)) {
 							// same group, reduce
 							res = function.reduce(res, value);

http://git-wip-us.apache.org/repos/asf/flink/blob/f3809d82/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
index 08ad25b..cf0fc85 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/GroupCombineChainedDriver.java
@@ -48,7 +48,7 @@ import java.util.List;
  * 
  * Acts like a combiner with a custom output type OUT.
  *
- * Sorting and reducing of the elements is performed invididually for each partition without data exchange. This may
+ * Sorting and reducing of the elements is performed individually for each partition without data exchange. This may
  * lead to a partial group reduce.
  *  
  * @param <IN> The data type consumed
@@ -58,9 +58,7 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 
 	private static final Logger LOG = LoggerFactory.getLogger(GroupCombineChainedDriver.class);
 
-	/**
-	 * Fix length records with a length below this threshold will be in-place sorted, if possible.
-	 */
+	/** Fix length records with a length below this threshold will be in-place sorted, if possible. */
 	private static final int THRESHOLD_FOR_IN_PLACE_SORTING = 32;
 
 	// --------------------------------------------------------------------------------------------
@@ -174,23 +172,16 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 			if (this.sorter.write(record)) {
 				return;
 			}
-		} catch (IOException e) {
-			throw new ExceptionInChainedStubException(this.taskName, e);
-		}
 
-		// do the actual sorting
-		try {
+			// do the actual sorting
 			sortAndReduce();
-		} catch (Exception e) {
-			throw new ExceptionInChainedStubException(this.taskName, e);
-		}
-		this.sorter.reset();
-
-		try {
+			this.sorter.reset();
+			
 			if (!this.sorter.write(record)) {
 				throw new IOException("Cannot write record to fresh sort buffer. Record too large.");
 			}
-		} catch (IOException e) {
+		}
+		catch (Exception e) {
 			throw new ExceptionInChainedStubException(this.taskName, e);
 		}
 	}
@@ -215,9 +206,9 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 			if (!sorter.isEmpty()) {
 				this.sortAlgo.sort(sorter);
 				// run the reducer
-				final ReusingKeyGroupedIterator<IN> keyIter = new ReusingKeyGroupedIterator<IN>(sorter.getIterator(), this.serializer, this.groupingComparator);
-
-
+				final ReusingKeyGroupedIterator<IN> keyIter = new ReusingKeyGroupedIterator<IN>(
+						sorter.getIterator(), this.serializer, this.groupingComparator);
+				
 				// cache references on the stack
 				final GroupReduceFunction<IN, OUT> stub = this.reducer;
 				final Collector<OUT> output = this.outputCollector;
@@ -231,7 +222,8 @@ public class GroupCombineChainedDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
 			if (!sorter.isEmpty()) {
 				this.sortAlgo.sort(sorter);
 				// run the reducer
-				final NonReusingKeyGroupedIterator<IN> keyIter = new NonReusingKeyGroupedIterator<IN>(sorter.getIterator(), this.groupingComparator);
+				final NonReusingKeyGroupedIterator<IN> keyIter = new NonReusingKeyGroupedIterator<IN>(
+						sorter.getIterator(), this.groupingComparator);
 
 
 				// cache references on the stack