You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by pw...@apache.org on 2013/09/25 02:14:46 UTC

svn commit: r2978 [11/12] - in /dev/incubator/spark/spark-0.8.0-incubating-rc6-docs: ./ css/ img/ js/ js/vendor/

Added: dev/incubator/spark/spark-0.8.0-incubating-rc6-docs/streaming-programming-guide.html
==============================================================================
--- dev/incubator/spark/spark-0.8.0-incubating-rc6-docs/streaming-programming-guide.html (added)
+++ dev/incubator/spark/spark-0.8.0-incubating-rc6-docs/streaming-programming-guide.html Wed Sep 25 00:14:43 2013
@@ -0,0 +1,758 @@
+<!DOCTYPE html>
+<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
+<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
+<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
+<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
+    <head>
+        <meta charset="utf-8">
+        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
+        <title>Spark Streaming Programming Guide - Spark 0.8.0 Documentation</title>
+        <meta name="description" content="">
+
+        <link rel="stylesheet" href="css/bootstrap.min.css">
+        <style>
+            body {
+                padding-top: 60px;
+                padding-bottom: 40px;
+            }
+        </style>
+        <meta name="viewport" content="width=device-width">
+        <link rel="stylesheet" href="css/bootstrap-responsive.min.css">
+        <link rel="stylesheet" href="css/main.css">
+
+        <script src="js/vendor/modernizr-2.6.1-respond-1.1.0.min.js"></script>
+        
+        <link rel="stylesheet" href="css/pygments-default.css">
+
+        <!-- Google analytics script -->
+        <script type="text/javascript">
+          /*
+          var _gaq = _gaq || [];
+          _gaq.push(['_setAccount', 'UA-32518208-1']);
+          _gaq.push(['_trackPageview']);
+
+          (function() {
+            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+          })();
+          */
+        </script>
+
+    </head>
+    <body>
+        <!--[if lt IE 7]>
+            <p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p>
+        <![endif]-->
+
+        <!-- This code is taken from http://twitter.github.com/bootstrap/examples/hero.html -->
+
+        <div class="navbar navbar-fixed-top" id="topbar">
+            <div class="navbar-inner">
+                <div class="container">
+                    <div class="brand"><a href="index.html">
+                      <img src="img/spark-logo-hd.png" style="height:50px;"/></a><span class="version">0.8.0</span>
+                    </div>
+                    <ul class="nav">
+                        <!--TODO(andyk): Add class="active" attribute to li some how.-->
+                        <li><a href="index.html">Overview</a></li>
+
+                        <li class="dropdown">
+                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Programming Guides<b class="caret"></b></a>
+                            <ul class="dropdown-menu">
+                                <li><a href="quick-start.html">Quick Start</a></li>
+                                <li><a href="scala-programming-guide.html">Spark in Scala</a></li>
+                                <li><a href="java-programming-guide.html">Spark in Java</a></li>
+                                <li><a href="python-programming-guide.html">Spark in Python</a></li>
+                                <li class="divider"></li>
+                                <li><a href="streaming-programming-guide.html">Spark Streaming</a></li>
+                                <li><a href="mllib-guide.html">MLlib (Machine Learning)</a></li>
+                                <li><a href="bagel-programming-guide.html">Bagel (Pregel on Spark)</a></li>
+                            </ul>
+                        </li>
+                        
+                        <li class="dropdown">
+                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Docs<b class="caret"></b></a>
+                            <ul class="dropdown-menu">
+                                <li><a href="api/core/index.html">Spark Core for Java/Scala</a></li>
+                                <li><a href="api/pyspark/index.html">Spark Core for Python</a></li>
+                                <li class="divider"></li>
+                                <li><a href="api/streaming/index.html">Spark Streaming</a></li>
+                                <li><a href="api/mllib/index.html">MLlib (Machine Learning)</a></li>
+                                <li><a href="api/bagel/index.html">Bagel (Pregel on Spark)</a></li>
+                            </ul>
+                        </li>
+
+                        <li class="dropdown">
+                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Deploying<b class="caret"></b></a>
+                            <ul class="dropdown-menu">
+                                <li><a href="cluster-overview.html">Overview</a></li>
+                                <li><a href="ec2-scripts.html">Amazon EC2</a></li>
+                                <li><a href="spark-standalone.html">Standalone Mode</a></li>
+                                <li><a href="running-on-mesos.html">Mesos</a></li>
+                                <li><a href="running-on-yarn.html">YARN</a></li>
+                            </ul>
+                        </li>
+
+                        <li class="dropdown">
+                            <a href="api.html" class="dropdown-toggle" data-toggle="dropdown">More<b class="caret"></b></a>
+                            <ul class="dropdown-menu">
+                                <li><a href="configuration.html">Configuration</a></li>
+                                <li><a href="monitoring.html">Monitoring</a></li>
+                                <li><a href="tuning.html">Tuning Guide</a></li>
+                                <li><a href="hadoop-third-party-distributions.html">Running with CDH/HDP</a></li>
+                                <li><a href="hardware-provisioning.html">Hardware Provisioning</a></li>
+                                <li><a href="job-scheduling.html">Job Scheduling</a></li>
+                                <li class="divider"></li>
+                                <li><a href="building-with-maven.html">Building Spark with Maven</a></li>
+                                <li><a href="https://cwiki.apache.org/confluence/display/SPARK/Contributing+to+Spark">Contributing to Spark</a></li>
+                            </ul>
+                        </li>
+                    </ul>
+                    <!--<p class="navbar-text pull-right"><span class="version-text">v0.8.0</span></p>-->
+                </div>
+            </div>
+        </div>
+
+        <div class="container" id="content">
+          <h1 class="title">Spark Streaming Programming Guide</h1>
+
+          <ul id="markdown-toc">
+  <li><a href="#overview">Overview</a></li>
+  <li><a href="#linking-with-spark-streaming">Linking with Spark Streaming</a></li>
+  <li><a href="#initializing-spark-streaming">Initializing Spark Streaming</a></li>
+  <li><a href="#attaching-input-sources---inputdstreams">Attaching Input Sources - InputDStreams</a></li>
+  <li><a href="#dstream-operations">DStream Operations</a>    <ul>
+      <li><a href="#transformations">Transformations</a></li>
+      <li><a href="#output-operations">Output Operations</a></li>
+    </ul>
+  </li>
+  <li><a href="#starting-the-streaming-computation">Starting the Streaming computation</a></li>
+  <li><a href="#example">Example</a></li>
+  <li><a href="#dstream-persistence">DStream Persistence</a></li>
+  <li><a href="#rdd-checkpointing-within-dstreams">RDD Checkpointing within DStreams</a>    <ul>
+      <li><a href="#custom-receivers">Custom Receivers</a></li>
+    </ul>
+  </li>
+  <li><a href="#performance-tuning">Performance Tuning</a>    <ul>
+      <li><a href="#reducing-the-processing-time-of-each-batch">Reducing the Processing Time of each Batch</a>        <ul>
+          <li><a href="#level-of-parallelism">Level of Parallelism</a></li>
+          <li><a href="#data-serialization">Data Serialization</a></li>
+          <li><a href="#task-launching-overheads">Task Launching Overheads</a></li>
+        </ul>
+      </li>
+      <li><a href="#setting-the-right-batch-size">Setting the Right Batch Size</a></li>
+      <li><a href="#operation">24/7 Operation</a></li>
+      <li><a href="#memory-tuning">Memory Tuning</a></li>
+    </ul>
+  </li>
+  <li><a href="#fault-tolerance-properties">Fault-tolerance Properties</a>    <ul>
+      <li><a href="#failure-of-a-worker-node">Failure of a Worker Node</a></li>
+      <li><a href="#failure-of-the-driver-node">Failure of the Driver Node</a></li>
+    </ul>
+  </li>
+  <li><a href="#java-api">Java API</a></li>
+  <li><a href="#where-to-go-from-here">Where to Go from Here</a></li>
+</ul>
+
+<h1 id="overview">Overview</h1>
+<p>A Spark Streaming application is very similar to a Spark application; it consists of a <em>driver program</em> that runs the user&#8217;s <code>main</code> function and continuous executes various <em>parallel operations</em> on input streams of data. The main abstraction Spark Streaming provides is a <em>discretized stream</em> (DStream), which is a continuous sequence of RDDs (distributed collections of elements) representing a continuous stream of data. DStreams can be created from live incoming data (such as data from a socket, Kafka, etc.) or can be generated by transforming existing DStreams using parallel operators like <code>map</code>, <code>reduce</code>, and <code>window</code>. The basic processing model is as follows: 
+(i) While a Spark Streaming driver program is running, the system receives data from various sources and and divides it into batches. Each batch of data is treated as an RDD, that is, an immutable parallel collection of data. These input RDDs are saved in memory and replicated to two nodes for fault-tolerance. This sequence of RDDs is collectively called an InputDStream.
+(ii) Data received by InputDStreams are processed using DStream operations. Since all data is represented as RDDs and all DStream operations as RDD operations, data is automatically recovered in the event of node failures.  </p>
+
+<p>This guide shows some how to start programming with DStreams. </p>
+
+<h1 id="linking-with-spark-streaming">Linking with Spark Streaming</h1>
+
+<p>Add the following SBT or Maven dependency to your project to use Spark Streaming:</p>
+
+<pre><code>groupId = org.apache.spark
+artifactId = spark-streaming_2.9.3
+version = 0.8.0-incubating
+</code></pre>
+
+<h1 id="initializing-spark-streaming">Initializing Spark Streaming</h1>
+<p>The first thing a Spark Streaming program must do is create a <code>StreamingContext</code> object, which tells Spark how to access a cluster. A <code>StreamingContext</code> can be created by using</p>
+
+<div class="highlight"><pre><code class="scala"><span class="k">new</span> <span class="nc">StreamingContext</span><span class="o">(</span><span class="n">master</span><span class="o">,</span> <span class="n">appName</span><span class="o">,</span> <span class="n">batchDuration</span><span class="o">,</span> <span class="o">[</span><span class="kt">sparkHome</span><span class="o">],</span> <span class="o">[</span><span class="kt">jars</span><span class="o">])</span>
+</code></pre></div>
+
+<p>The <code>master</code> parameter is a standard <a href="scala-programming-guide.html#master-urls">Spark cluster URL</a> and can be &#8220;local&#8221; for local testing. The <code>appName</code> is a name of your program, which will be shown on your cluster&#8217;s web UI. The <code>batchDuration</code> is the size of the batches (as explained earlier). This must be set carefully such that the cluster can keep up with the processing of the data streams. Start with something conservative like 5 seconds. See the <a href="#setting-the-right-batch-size">Performance Tuning</a> section for a detailed discussion. Finally, <code>sparkHome</code> and <code>jars</code> are necessary when running on a cluster to specify the location of your code, as described in the <a href="scala-programming-guide.html#deploying-code-on-a-cluster">Spark programming guide</a>.</p>
+
+<p>This constructor creates a SparkContext for your job as well, which can be accessed with <code>streamingContext.sparkContext</code>.</p>
+
+<h1 id="attaching-input-sources---inputdstreams">Attaching Input Sources - InputDStreams</h1>
+<p>The StreamingContext is used to creating InputDStreams from input sources:</p>
+
+<div class="highlight"><pre><code class="scala"><span class="c1">// Assuming ssc is the StreamingContext</span>
+<span class="n">ssc</span><span class="o">.</span><span class="n">textFileStream</span><span class="o">(</span><span class="n">directory</span><span class="o">)</span>      <span class="c1">// Creates a stream by monitoring and processing new files in a HDFS directory</span>
+<span class="n">ssc</span><span class="o">.</span><span class="n">socketStream</span><span class="o">(</span><span class="n">hostname</span><span class="o">,</span> <span class="n">port</span><span class="o">)</span>   <span class="c1">// Creates a stream that uses a TCP socket to read data from hostname:port</span>
+</code></pre></div>
+
+<p>We also provide a input streams for Kafka, Flume, Akka actor, etc. For a complete list of input streams, take a look at the <a href="api/streaming/index.html#org.apache.spark.streaming.StreamingContext">StreamingContext API documentation</a>.</p>
+
+<h1 id="dstream-operations">DStream Operations</h1>
+<p>Data received from the input streams can be processed using <em>DStream operations</em>. There are two kinds of operations - <em>transformations</em> and <em>output operations</em>. Similar to RDD transformations, DStream transformations operate on one or more DStreams to create new DStreams with transformed data. After applying a sequence of transformations to the input streams, you&#8217;ll need to call the output operations, which writies data out to an external source. </p>
+
+<h2 id="transformations">Transformations</h2>
+
+<p>DStreams support many of the transformations available on normal Spark RDD&#8217;s:</p>
+
+<table class="table">
+<tr><th style="width:30%">Transformation</th><th>Meaning</th></tr>
+<tr>
+  <td> <b>map</b>(<i>func</i>) </td>
+  <td> Returns a new DStream formed by passing each element of the source DStream through a function <i>func</i>. </td>
+</tr>
+<tr>
+  <td> <b>filter</b>(<i>func</i>) </td>
+  <td> Returns a new DStream formed by selecting those elements of the source DStream on which <i>func</i> returns true. </td>
+</tr>
+<tr>
+  <td> <b>flatMap</b>(<i>func</i>) </td>
+  <td> Similar to map, but each input item can be mapped to 0 or more output items (so <i>func</i> should return a <code>Seq</code> rather than a single item). </td>
+</tr>
+<tr>
+  <td> <b>mapPartitions</b>(<i>func</i>) </td>
+  <td> Similar to map, but runs separately on each partition (block) of the DStream, so <i>func</i> must be of type
+    Iterator[T] =&gt; Iterator[U] when running on an DStream of type T. </td>
+</tr>
+<tr>
+  <td> <b>union</b>(<i>otherStream</i>) </td>
+  <td> Return a new DStream that contains the union of the elements in the source DStream and the argument DStream. </td>
+</tr>
+<tr>
+  <td> <b>count</b>() </td>
+  <td> Returns a new DStream of single-element RDDs by counting the number of elements in each RDD of the source DStream.  </td>
+</tr>
+<tr>
+  <td> <b>reduce</b>(<i>func</i>) </td>
+  <td> Returns a new DStream of single-element RDDs by aggregating the elements in each RDD of the source DStream using a function <i>func</i> (which takes two arguments and returns one). The function should be associative so that it can be computed in parallel. </td>
+</tr>
+<tr>
+  <td> <b>countByValue</b>() </td>
+  <td> When called on a DStream of elements of type K, returns a new DStream of (K, Long) pairs where the value of each key is its frequency in each RDD of the source DStream.  </td>
+</tr>
+<tr>
+  <td> <b>groupByKey</b>([<i>numTasks</i>]) </td>
+  <td> When called on a DStream of (K, V) pairs, returns a new DStream of (K, Seq[V]) pairs by grouping together all the values of each key in the RDDs of the source DStream. <br />
+  <b>Note:</b> By default, this uses Spark's default number of parallel tasks (2 for local machine, 8 for a cluster) to do the grouping. You can pass an optional <code>numTasks</code> argument to set a different number of tasks.
+</td>
+</tr>
+<tr>
+  <td> <b>reduceByKey</b>(<i>func</i>, [<i>numTasks</i>]) </td>
+  <td> When called on a DStream of (K, V) pairs, returns a new DStream of (K, V) pairs where the values for each key are aggregated using the given reduce function. Like in <code>groupByKey</code>, the number of reduce tasks is configurable through an optional second argument. </td>
+</tr>
+<tr>
+  <td> <b>join</b>(<i>otherStream</i>, [<i>numTasks</i>]) </td>
+  <td> When called on two DStreams of (K, V) and (K, W) pairs, returns a new DStream of (K, (V, W)) pairs with all pairs of elements for each key. </td>
+</tr>
+<tr>
+  <td> <b>cogroup</b>(<i>otherStream</i>, [<i>numTasks</i>]) </td>
+  <td> When called on DStream of (K, V) and (K, W) pairs, returns a new DStream of (K, Seq[V], Seq[W]) tuples.</td>
+</tr>
+<tr>
+  <td> <b>transform</b>(<i>func</i>) </td>
+  <td> Returns a new DStream by applying func (a RDD-to-RDD function) to every RDD of the stream. This can be used to do arbitrary RDD operations on the DStream. </td>
+</tr>
+<tr>
+  <td> <b>updateStateByKey</b>(<i>func</i>) </td>
+  <td> Return a new "state" DStream where the state for each key is updated by applying the given function on the previous state of the key and the new values of each key. This can be used to track session state by using the session-id as the key and updating the session state as new data is received.</td>
+</tr>
+
+</table>
+
+<p>Spark Streaming features windowed computations, which allow you to apply transformations over a sliding window of data. All window functions take a <i>windowDuration</i>, which represents the width of the window and a <i>slideTime</i>, which represents the frequency during which the window is calculated.</p>
+
+<table class="table">
+<tr><th style="width:30%">Transformation</th><th>Meaning</th></tr>
+<tr>
+  <td> <b>window</b>(<i>windowDuration</i>, slideDuration) </td>
+  <td> Return a new DStream which is computed based on windowed batches of the source DStream. <i>windowDuration</i> is the width of the window and <i>slideTime</i> is the frequency during which the window is calculated. Both times must be multiples of the batch interval.
+  </td>
+</tr>
+<tr>
+  <td> <b>countByWindow</b>(<i>windowDuration</i>, slideDuration) </td>
+  <td> Return a sliding count of elements in the stream. <i>windowDuration</i> and <i>slideDuration</i> are exactly as defined in <code>window()</code>.
+  </td>
+</tr>
+<tr>
+  <td> <b>reduceByWindow</b>(<i>func</i>, <i>windowDuration</i>, <i>slideDuration</i>) </td>
+  <td> Return a new single-element stream, created by aggregating elements in the stream over a sliding interval using <i>func</i>. The function should be associative so that it can be computed correctly in parallel. <i>windowDuration</i> and <i>slideDuration</i> are exactly as defined in <code>window()</code>.
+  </td>
+</tr>
+<tr>
+  <td> <b>groupByKeyAndWindow</b>(<i>windowDuration</i>, <i>slideDuration</i>, [<i>numTasks</i>])
+  </td>
+  <td> When called on a DStream of (K, V) pairs, returns a new DStream of (K, Seq[V]) pairs by grouping together values of each key over batches in a sliding window. <br />
+<b>Note:</b> By default, this uses Spark's default number of parallel tasks (2 for local machine, 8 for a cluster) to do the grouping. You can pass an optional <code>numTasks</code> argument to set a different number of tasks.</td>
+</tr>
+<tr>
+  <td> <b>reduceByKeyAndWindow</b>(<i>func</i>, <i>windowDuration</i>, <i>slideDuration</i>, [<i>numTasks</i>]) </td>
+  <td> When called on a DStream of (K, V) pairs, returns a new DStream of (K, V) pairs where the values for each key are aggregated using the given reduce function <i>func</i> over batches in a sliding window. Like in <code>groupByKeyAndWindow</code>, the number of reduce tasks is configurable through an optional second argument.
+ <i>windowDuration</i> and <i>slideDuration</i> are exactly as defined in <code>window()</code>.
+</td> 
+</tr>
+<tr>
+  <td> <b>reduceByKeyAndWindow</b>(<i>func</i>, <i>invFunc</i>, <i>windowDuration</i>, <i>slideDuration</i>, [<i>numTasks</i>]) </td>
+  <td> A more efficient version of the above <code>reduceByKeyAndWindow()</code> where the reduce value of each window is calculated
+  incrementally using the reduce values of the previous window. This is done by reducing the new data that enter the sliding window, and "inverse reducing" the old data that leave the window. An example would be that of "adding" and "subtracting" counts of keys as the window slides. However, it is applicable to only "invertible reduce functions", that is, those reduce functions which have a corresponding "inverse reduce" function (taken as parameter <i>invFunc</i>. Like in <code>groupByKeyAndWindow</code>, the number of reduce tasks is configurable through an optional second argument.
+ <i>windowDuration</i> and <i>slideDuration</i> are exactly as defined in <code>window()</code>.
+</td>
+</tr>
+<tr>
+  <td> <b>countByValueAndWindow</b>(<i>windowDuration</i>, <i>slideDuration</i>, [<i>numTasks</i>]) </td>
+  <td> When called on a DStream of (K, V) pairs, returns a new DStream of (K, Long) pairs where the value of each key is its frequency within a sliding window. Like in <code>groupByKeyAndWindow</code>, the number of reduce tasks is configurable through an optional second argument.
+ <i>windowDuration</i> and <i>slideDuration</i> are exactly as defined in <code>window()</code>.
+</td>
+</tr>
+
+</table>
+
+<p>A complete list of DStream operations is available in the API documentation of <a href="api/streaming/index.html#org.apache.spark.streaming.DStream">DStream</a> and <a href="api/streaming/index.html#org.apache.spark.streaming.PairDStreamFunctions">PairDStreamFunctions</a>.</p>
+
+<h2 id="output-operations">Output Operations</h2>
+<p>When an output operator is called, it triggers the computation of a stream. Currently the following output operators are defined:</p>
+
+<table class="table">
+<tr><th style="width:30%">Operator</th><th>Meaning</th></tr>
+<tr>
+  <td> <b>foreach</b>(<i>func</i>) </td>
+  <td> The fundamental output operator. Applies a function, <i>func</i>, to each RDD generated from the stream. This function should have side effects, such as printing output, saving the RDD to external files, or writing it over the network to an external system. </td>
+</tr>
+
+<tr>
+  <td> <b>print</b>() </td>
+  <td> Prints first ten elements of every batch of data in a DStream on the driver. </td>
+</tr>
+
+<tr>
+  <td> <b>saveAsObjectFiles</b>(<i>prefix</i>, [<i>suffix</i>]) </td>
+  <td> Save this DStream's contents as a <code>SequenceFile</code> of serialized objects. The file name at each batch interval is generated based on <i>prefix</i> and <i>suffix</i>: <i>"prefix-TIME_IN_MS[.suffix]"</i>.
+  </td>
+</tr>
+
+<tr>
+  <td> <b>saveAsTextFiles</b>(<i>prefix</i>, [<i>suffix</i>]) </td>
+  <td> Save this DStream's contents as a text files. The file name at each batch interval is generated based on <i>prefix</i> and <i>suffix</i>: <i>"prefix-TIME_IN_MS[.suffix]"</i>. </td>
+</tr>
+
+<tr>
+  <td> <b>saveAsHadoopFiles</b>(<i>prefix</i>, [<i>suffix</i>]) </td>
+  <td> Save this DStream's contents as a Hadoop file. The file name at each batch interval is generated based on <i>prefix</i> and <i>suffix</i>: <i>"prefix-TIME_IN_MS[.suffix]"</i>. </td>
+</tr>
+
+</table>
+
+<h1 id="starting-the-streaming-computation">Starting the Streaming computation</h1>
+<p>All the above DStream operations are completely lazy, that is, the operations will start executing only after the context is started by using</p>
+
+<div class="highlight"><pre><code class="scala"><span class="n">ssc</span><span class="o">.</span><span class="n">start</span><span class="o">()</span>
+</code></pre></div>
+
+<p>Conversely, the computation can be stopped by using</p>
+
+<div class="highlight"><pre><code class="scala"><span class="n">ssc</span><span class="o">.</span><span class="n">stop</span><span class="o">()</span>
+</code></pre></div>
+
+<h1 id="example">Example</h1>
+<p>A simple example to start off is the <a href="https://github.com/apache/incubator-spark/tree/master/examples/src/main/scala/spark/streaming/examples/NetworkWordCount.scala">NetworkWordCount</a>. This example counts the words received from a network server every second. Given below is the relevant sections of the source code. You can find the full source code in <code>&lt;Spark repo&gt;/streaming/src/main/scala/spark/streaming/examples/NetworkWordCount.scala</code> .</p>
+
+<div class="highlight"><pre><code class="scala"><span class="k">import</span> <span class="nn">org.apache.spark.streaming.</span><span class="o">{</span><span class="nc">Seconds</span><span class="o">,</span> <span class="nc">StreamingContext</span><span class="o">}</span>
+<span class="k">import</span> <span class="nn">StreamingContext._</span>
+<span class="o">...</span>
+
+<span class="c1">// Create the context and set up a network input stream to receive from a host:port</span>
+<span class="k">val</span> <span class="n">ssc</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">StreamingContext</span><span class="o">(</span><span class="n">args</span><span class="o">(</span><span class="mi">0</span><span class="o">),</span> <span class="s">&quot;NetworkWordCount&quot;</span><span class="o">,</span> <span class="nc">Seconds</span><span class="o">(</span><span class="mi">1</span><span class="o">))</span>
+<span class="k">val</span> <span class="n">lines</span> <span class="k">=</span> <span class="n">ssc</span><span class="o">.</span><span class="n">socketTextStream</span><span class="o">(</span><span class="n">args</span><span class="o">(</span><span class="mi">1</span><span class="o">),</span> <span class="n">args</span><span class="o">(</span><span class="mi">2</span><span class="o">).</span><span class="n">toInt</span><span class="o">)</span>
+
+<span class="c1">// Split the lines into words, count them, and print some of the counts on the master</span>
+<span class="k">val</span> <span class="n">words</span> <span class="k">=</span> <span class="n">lines</span><span class="o">.</span><span class="n">flatMap</span><span class="o">(</span><span class="k">_</span><span class="o">.</span><span class="n">split</span><span class="o">(</span><span class="s">&quot; &quot;</span><span class="o">))</span>
+<span class="k">val</span> <span class="n">wordCounts</span> <span class="k">=</span> <span class="n">words</span><span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">x</span> <span class="k">=&gt;</span> <span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="mi">1</span><span class="o">)).</span><span class="n">reduceByKey</span><span class="o">(</span><span class="k">_</span> <span class="o">+</span> <span class="k">_</span><span class="o">)</span>
+<span class="n">wordCounts</span><span class="o">.</span><span class="n">print</span><span class="o">()</span>
+
+<span class="c1">// Start the computation</span>
+<span class="n">ssc</span><span class="o">.</span><span class="n">start</span><span class="o">()</span>
+</code></pre></div>
+
+<p>The <code>socketTextStream</code> returns a DStream of lines received from a TCP socket-based source. The <code>lines</code> DStream is <em>transformed</em> into a DStream using the <code>flatMap</code> operation, where each line is split into words. This <code>words</code> DStream is then mapped to a DStream of <code>(word, 1)</code> pairs, which is finally reduced to get the word counts. <code>wordCounts.print()</code> will print 10 of the counts generated every second.</p>
+
+<p>To run this example on your local machine, you need to first run a Netcat server by using</p>
+
+<div class="highlight"><pre><code class="bash"><span class="nv">$ </span>nc -lk 9999
+</code></pre></div>
+
+<p>Then, in a different terminal, you can start NetworkWordCount by using</p>
+
+<div class="highlight"><pre><code class="bash"><span class="nv">$ </span>./run-example org.apache.spark.streaming.examples.NetworkWordCount <span class="nb">local</span><span class="o">[</span>2<span class="o">]</span> localhost 9999
+</code></pre></div>
+
+<p>This will make NetworkWordCount connect to the netcat server. Any lines typed in the terminal running the netcat server will be counted and printed on screen.</p>
+
+<table>
+<td>
+
+<div class="highlight"><pre><code class="bash"><span class="c"># TERMINAL 1</span>
+<span class="c"># RUNNING NETCAT</span>
+
+<span class="nv">$ </span>nc -lk 9999
+hello world
+
+
+
+
+
+...
+</code></pre></div>
+
+</td>
+<td>
+
+<div class="highlight"><pre><code class="bash"><span class="c"># TERMINAL 2: RUNNING NetworkWordCount</span>
+...
+2012-12-31 18:47:10,446 INFO SparkContext: Job finished: run at ThreadPoolExecutor.java:886, took 0.038817 s
+-------------------------------------------
+Time: 1357008430000 ms
+-------------------------------------------
+<span class="o">(</span>hello,1<span class="o">)</span>
+<span class="o">(</span>world,1<span class="o">)</span>
+
+2012-12-31 18:47:10,447 INFO JobManager: Total delay: 0.44700 s <span class="k">for </span>job 8 <span class="o">(</span>execution: 0.44000 s<span class="o">)</span>
+...
+</code></pre></div>
+
+</td>
+</table>
+
+<p>You can find more examples in <code>&lt;Spark repo&gt;/streaming/src/main/scala/spark/streaming/examples/</code>. They can be run in the similar manner using <code>./run-example org.apache.spark.streaming.examples....</code> . Executing without any parameter would give the required parameter list. Further explanation to run them can be found in comments in the files.</p>
+
+<h1 id="dstream-persistence">DStream Persistence</h1>
+<p>Similar to RDDs, DStreams also allow developers to persist the stream&#8217;s data in memory. That is, using <code>persist()</code> method on a DStream would automatically persist every RDD of that DStream in memory. This is useful if the data in the DStream will be computed multiple times (e.g., multiple operations on the same data). For window-based operations like <code>reduceByWindow</code> and <code>reduceByKeyAndWindow</code> and state-based operations like <code>updateStateByKey</code>, this is implicitly true. Hence, DStreams generated by window-based operations are automatically persisted in memory, without the developer calling <code>persist()</code>.</p>
+
+<p>For input streams that receive data from the network (that is, subclasses of NetworkInputDStream like FlumeInputDStream and KafkaInputDStream), the default persistence level is set to replicate the data to two nodes for fault-tolerance.</p>
+
+<p>Note that, unlike RDDs, the default persistence level of DStreams keeps the data serialized in memory. This is further discussed in the <a href="#memory-tuning">Performance Tuning</a> section. More information on different persistence levels can be found in <a href="scala-programming-guide.html#rdd-persistence">Spark Programming Guide</a>.</p>
+
+<h1 id="rdd-checkpointing-within-dstreams">RDD Checkpointing within DStreams</h1>
+<p>A <em>stateful operation</em> is one which operates over multiple batches of data. This includes all window-based operations and the <code>updateStateByKey</code> operation. </p>
+
+<p>Because stateful operations have a dependency on previous batches of data, they continuously accumulate metadata over time. To clear this metadata, streaming supports periodic <em>checkpointing</em> by saving intermediate data to HDFS. Note that checkpointing also incurs the cost of saving to HDFS which may cause the corresponding batch to take longer to process. Hence, the interval of checkpointing needs to be set carefully. At small batch sizes (say 1 second), checkpointing every batch may significantly reduce operation throughput. Conversely, checkpointing too slowly causes the lineage and task sizes to grow which may have detrimental effects. Typically, a checkpoint interval of 5 - 10 times of sliding interval of a DStream is good setting to try.</p>
+
+<p>To enable checkpointing, the developer has to provide the HDFS path to which RDD will be saved. This is done by using</p>
+
+<div class="highlight"><pre><code class="scala"><span class="n">ssc</span><span class="o">.</span><span class="n">checkpoint</span><span class="o">(</span><span class="n">hdfsPath</span><span class="o">)</span> <span class="c1">// assuming ssc is the StreamingContext</span>
+</code></pre></div>
+
+<p>The interval of checkpointing of a DStream can be set by using</p>
+
+<div class="highlight"><pre><code class="scala"><span class="n">dstream</span><span class="o">.</span><span class="n">checkpoint</span><span class="o">(</span><span class="n">checkpointInterval</span><span class="o">)</span> <span class="c1">// checkpointInterval must be a multiple of slide duration of dstream</span>
+</code></pre></div>
+
+<p>For DStreams that must be checkpointed (that is, DStreams created by <code>updateStateByKey</code> and <code>reduceByKeyAndWindow</code> with inverse function), the checkpoint interval of the DStream is by default set to a multiple of the DStream&#8217;s sliding interval such that its at least 10 seconds.</p>
+
+<h2 id="custom-receivers">Custom Receivers</h2>
+<p>Spark comes with a built in support for most common usage scenarios where input stream source can be either a network socket stream to support for a few message queues. Apart from that it is also possible to supply your own custom receiver via a convenient API. Find more details at <a href="streaming-custom-receivers.html">Custom Receiver Guide</a>.</p>
+
+<h1 id="performance-tuning">Performance Tuning</h1>
+<p>Getting the best performance of a Spark Streaming application on a cluster requires a bit of tuning. This section explains a number of the parameters and configurations that can tuned to improve the performance of you application. At a high level, you need to consider two things:</p>
+<ol>
+<li>Reducing the processing time of each batch of data by efficiently using cluster resources.</li>
+<li>Setting the right batch size such that the data processing can keep up with the data ingestion.</li>
+</ol>
+
+<h2 id="reducing-the-processing-time-of-each-batch">Reducing the Processing Time of each Batch</h2>
+<p>There are a number of optimizations that can be done in Spark to minimize the processing time of each batch. These have been discussed in detail in <a href="tuning.html">Tuning Guide</a>. This section highlights some of the most important ones.</p>
+
+<h3 id="level-of-parallelism">Level of Parallelism</h3>
+<p>Cluster resources maybe under-utilized if the number of parallel tasks used in any stage of the computation is not high enough. For example, for distributed reduce operations like <code>reduceByKey</code> and <code>reduceByKeyAndWindow</code>, the default number of parallel tasks is 8. You can pass the level of parallelism as an argument (see the <a href="api/streaming/index.html#org.apache.spark.PairDStreamFunctions"><code>PairDStreamFunctions</code></a> documentation), or set the system property <code>spark.default.parallelism</code> to change the default.</p>
+
+<h3 id="data-serialization">Data Serialization</h3>
+<p>The overhead of data serialization can be significant, especially when sub-second batch sizes are to be achieved. There are two aspects to it.</p>
+
+<ul>
+  <li>
+    <p><strong>Serialization of RDD data in Spark</strong>: Please refer to the detailed discussion on data serialization in the <a href="tuning.html">Tuning Guide</a>. However, note that unlike Spark, by default RDDs are persisted as serialized byte arrays to minimize pauses related to GC.</p>
+  </li>
+  <li>
+    <p><strong>Serialization of input data</strong>: To ingest external data into Spark, data received as bytes (say, from the network) needs to deserialized from bytes and re-serialized into Spark&#8217;s serialization format. Hence, the deserialization overhead of input data may be a bottleneck.</p>
+  </li>
+</ul>
+
+<h3 id="task-launching-overheads">Task Launching Overheads</h3>
+<p>If the number of tasks launched per second is high (say, 50 or more per second), then the overhead of sending out tasks to the slaves maybe significant and will make it hard to achieve sub-second latencies. The overhead can be reduced by the following changes:</p>
+
+<ul>
+  <li>
+    <p><strong>Task Serialization</strong>: Using Kryo serialization for serializing tasks can reduced the task sizes, and therefore reduce the time taken to send them to the slaves.</p>
+  </li>
+  <li>
+    <p><strong>Execution mode</strong>: Running Spark in Standalone mode or coarse-grained Mesos mode leads to better task launch times than the fine-grained Mesos mode. Please refer to the <a href="running-on-mesos.html">Running on Mesos guide</a> for more details.
+These changes may reduce batch processing time by 100s of milliseconds, thus allowing sub-second batch size to be viable.</p>
+  </li>
+</ul>
+
+<h2 id="setting-the-right-batch-size">Setting the Right Batch Size</h2>
+<p>For a Spark Streaming application running on a cluster to be stable, the processing of the data streams must keep up with the rate of ingestion of the data streams. Depending on the type of computation, the batch size used may have significant impact on the rate of ingestion that can be sustained by the Spark Streaming application on a fixed cluster resources. For example, let us consider the earlier WordCountNetwork example. For a particular data rate, the system may be able to keep up with reporting word counts every 2 seconds (i.e., batch size of 2 seconds), but not every 500 milliseconds.</p>
+
+<p>A good approach to figure out the right batch size for your application is to test it with a conservative batch size (say, 5-10 seconds) and a low data rate. To verify whether the system is able to keep up with data rate, you can check the value of the end-to-end delay experienced by each processed batch (in the Spark master logs, find the line having the phrase &#8220;Total delay&#8221;). If the delay is maintained to be less than the batch size, then system is stable. Otherwise, if the delay is continuously increasing, it means that the system is unable to keep up and it therefore unstable. Once you have an idea of a stable configuration, you can try increasing the data rate and/or reducing the batch size. Note that momentary increase in the delay due to temporary data rate increases maybe fine as long as the delay reduces back to a low value (i.e., less than batch size).</p>
+
+<h2 id="operation">24/7 Operation</h2>
+<p>By default, Spark does not forget any of the metadata (RDDs generated, stages processed, etc.). But for a Spark Streaming application to operate 24/7, it is necessary for Spark to do periodic cleanup of it metadata. This can be enabled by setting the Java system property <code>spark.cleaner.ttl</code> to the number of seconds you want any metadata to persist. For example, setting <code>spark.cleaner.ttl</code> to 600 would cause Spark periodically cleanup all metadata and persisted RDDs that are older than 10 minutes. Note, that this property needs to be set before the SparkContext is created.</p>
+
+<p>This value is closely tied with any window operation that is being used. Any window operation would require the input data to be persisted in memory for at least the duration of the window. Hence it is necessary to set the delay to at least the value of the largest window operation used in the Spark Streaming application. If this delay is set too low, the application will throw an exception saying so.</p>
+
+<h2 id="memory-tuning">Memory Tuning</h2>
+<p>Tuning the memory usage and GC behavior of Spark applications have been discussed in great detail in the <a href="tuning.html">Tuning Guide</a>. It is recommended that you read that. In this section, we highlight a few customizations that are strongly recommended to minimize GC related pauses in Spark Streaming applications and achieving more consistent batch processing times.</p>
+
+<ul>
+  <li>
+    <p><strong>Default persistence level of DStreams</strong>: Unlike RDDs, the default persistence level of DStreams serializes the data in memory (that is, <a href="api/core/index.html#org.apache.spark.storage.StorageLevel$">StorageLevel.MEMORY_ONLY_SER</a> for DStream compared to <a href="api/core/index.html#org.apache.spark.storage.StorageLevel$">StorageLevel.MEMORY_ONLY</a> for RDDs). Even though keeping the data serialized incurs a higher serialization overheads, it significantly reduces GC pauses.</p>
+  </li>
+  <li>
+    <p><strong>Concurrent garbage collector</strong>: Using the concurrent mark-and-sweep GC further minimizes the variability of GC pauses. Even though concurrent GC is known to reduce the overall processing throughput of the system, its use is still recommended to achieve more consistent batch processing times.</p>
+  </li>
+</ul>
+
+<h1 id="fault-tolerance-properties">Fault-tolerance Properties</h1>
+<p>In this section, we are going to discuss the behavior of Spark Streaming application in the event of a node failure. To understand this, let us remember the basic fault-tolerance properties of Spark&#8217;s RDDs.</p>
+
+<ol>
+  <li>An RDD is an immutable, and deterministically re-computable, distributed dataset. Each RDD remembers the lineage of deterministic operations that were used on a fault-tolerant input dataset to create it.</li>
+  <li>If any partition of an RDD is lost due to a worker node failure, then that partition can be re-computed from the original fault-tolerant dataset using the lineage of operations.</li>
+</ol>
+
+<p>Since all data transformations in Spark Streaming are based on RDD operations, as long as the input dataset is present, all intermediate data can recomputed. Keeping these properties in mind, we are going to discuss the failure semantics in more detail.</p>
+
+<h2 id="failure-of-a-worker-node">Failure of a Worker Node</h2>
+
+<p>There are two failure behaviors based on which input sources are used.</p>
+
+<ol>
+  <li><em>Using HDFS files as input source</em> - Since the data is reliably stored on HDFS, all data can re-computed and therefore no data will be lost due to any failure.</li>
+  <li><em>Using any input source that receives data through a network</em> - For network-based data sources like Kafka and Flume, the received input data is replicated in memory between nodes of the cluster (default replication factor is 2). So if a worker node fails, then the system can recompute the lost from the the left over copy of the input data. However, if the worker node where a network receiver was running fails, then a tiny bit of data may be lost, that is, the data received by the system but not yet replicated to other node(s). The receiver will be started on a different node and it will continue to receive data.</li>
+</ol>
+
+<p>Since all data is modeled as RDDs with their lineage of deterministic operations, any recomputation always leads to the same result. As a result, all DStream transformations are guaranteed to have <em>exactly-once</em> semantics. That is, the final transformed result will be same even if there were was a worker node failure. However, output operations (like <code>foreach</code>) have <em>at-least once</em> semantics, that is, the transformed data may get written to an external entity more than once in the event of a worker failure. While this is acceptable for saving to HDFS using the <code>saveAs*Files</code> operations (as the file will simply get over-written by the same data), additional transactions-like mechanisms may be necessary to achieve exactly-once semantics for output operations.</p>
+
+<h2 id="failure-of-the-driver-node">Failure of the Driver Node</h2>
+<p>A system that is required to operate 24/7 needs to be able tolerate the failure of the driver node as well. Spark Streaming does this by saving the state of the DStream computation periodically to a HDFS file, that can be used to restart the streaming computation in the event of a failure of the driver node. This checkpointing is enabled by setting a HDFS directory for checkpointing using <code>ssc.checkpoint(&lt;checkpoint directory&gt;)</code> as described <a href="#rdd-checkpointing-within-dstreams">earlier</a>. To elaborate, the following state is periodically saved to a file.</p>
+
+<ol>
+  <li>The DStream operator graph (input streams, output streams, etc.)</li>
+  <li>The configuration of each DStream (checkpoint interval, etc.)</li>
+  <li>The RDD checkpoint files of each DStream</li>
+</ol>
+
+<p>All this is periodically saved in the file <code>&lt;checkpoint directory&gt;/graph</code>. To recover, a new Streaming Context can be created with this directory by using</p>
+
+<div class="highlight"><pre><code class="scala"><span class="k">val</span> <span class="n">ssc</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">StreamingContext</span><span class="o">(</span><span class="n">checkpointDirectory</span><span class="o">)</span>
+</code></pre></div>
+
+<p>On calling <code>ssc.start()</code> on this new context, the following steps are taken by the system</p>
+
+<ol>
+  <li>Schedule the transformations and output operations for all the time steps between the time when the driver failed and when it last checkpointed. This is also done for those time steps that were previously scheduled but not processed due to the failure. This will make the system recompute all the intermediate data from the checkpointed RDD files, etc.</li>
+  <li>Restart the network receivers, if any, and continue receiving new data.</li>
+</ol>
+
+<p>In the current <em>alpha</em> release, there are two different failure behaviors based on which input sources are used.</p>
+
+<ol>
+  <li><em>Using HDFS files as input source</em> - Since the data is reliably stored on HDFS, all data can re-computed and therefore no data will be lost due to any failure.</li>
+  <li><em>Using any input source that receives data through a network</em> - The received input data is replicated in memory to multiple nodes. Since, all the data in the Spark worker&#8217;s memory is lost when the Spark driver fails, the past input data will not be accessible and driver recovers. Hence, if stateful and window-based operations are used (like <code>updateStateByKey</code>, <code>window</code>, <code>countByValueAndWindow</code>, etc.), then the intermediate state will not be recovered completely.</li>
+</ol>
+
+<p>In future releases, we will support full recoverability for all input sources. Note that for non-stateful transformations like <code>map</code>, <code>count</code>, and <code>reduceByKey</code>, with <em>all</em> input streams, the system, upon restarting, will continue to receive and process new data.</p>
+
+<p>To better understand the behavior of the system under driver failure with a HDFS source, lets consider what will happen with a file input stream Specifically, in the case of the file input stream, it will correctly identify new files that were created while the driver was down and process them in the same way as it would have if the driver had not failed. To explain further in the case of file input stream, we shall use an example. Lets say, files are being generated every second, and a Spark Streaming program reads every new file and output the number of lines in the file. This is what the sequence of outputs would be with and without a driver failure.</p>
+
+<table class="table">
+    <!-- Results table headers -->
+    <tr>
+      <th> Time </th>
+      <th> Number of lines in input file </th>
+      <th> Output without driver failure </th>
+      <th> Output with driver failure </th>
+    </tr>
+    <tr>
+      <td>1</td>
+      <td>10</td>
+      <td>10</td>
+      <td>10</td>
+    </tr>
+    <tr>
+      <td>2</td>
+      <td>20</td>
+      <td>20</td>
+      <td>20</td>
+    </tr>
+    <tr>
+      <td>3</td>
+      <td>30</td>
+      <td>30</td>
+      <td>30</td>
+    </tr>
+    <tr>
+      <td>4</td>
+      <td>40</td>
+      <td>40</td>
+      <td>[DRIVER FAILS]<br />no output</td>
+    </tr>
+    <tr>
+      <td>5</td>
+      <td>50</td>
+      <td>50</td>
+      <td>no output</td>
+    </tr>
+    <tr>
+      <td>6</td>
+      <td>60</td>
+      <td>60</td>
+      <td>no output</td>
+    </tr>
+    <tr>
+      <td>7</td>
+      <td>70</td>
+      <td>70</td>
+      <td>[DRIVER RECOVERS]<br />40, 50, 60, 70</td>
+    </tr>
+    <tr>
+      <td>8</td>
+      <td>80</td>
+      <td>80</td>
+      <td>80</td>
+    </tr>
+    <tr>
+      <td>9</td>
+      <td>90</td>
+      <td>90</td>
+      <td>90</td>
+    </tr>
+    <tr>
+      <td>10</td>
+      <td>100</td>
+      <td>100</td>
+      <td>100</td>
+    </tr>
+</table>
+
+<p>If the driver had crashed in the middle of the processing of time 3, then it will process time 3 and output 30 after recovery.</p>
+
+<h1 id="java-api">Java API</h1>
+
+<p>Similar to <a href="java-programming-guide.html">Spark&#8217;s Java API</a>, we also provide a Java API for Spark Streaming which allows all its features to be accessible from a Java program. This is defined in [org.apache.spark.streaming.api.java] (api/streaming/index.html#org.apache.spark.streaming.api.java.package) package and includes <a href="api/streaming/index.html#org.apache.spark.streaming.api.java.JavaStreamingContext">JavaStreamingContext</a> and <a href="api/streaming/index.html#org.apache.spark.streaming.api.java.JavaDStream">JavaDStream</a> classes that provide the same methods as their Scala counterparts, but take Java functions (that is, Function, and Function2) and return Java data and collection types. Some of the key points to note are:</p>
+
+<ol>
+  <li>Functions for transformations must be implemented as subclasses of <a href="api/core/index.html#org.apache.spark.api.java.function.Function">Function</a> and <a href="api/core/index.html#org.apache.spark.api.java.function.Function2">Function2</a></li>
+  <li>Unlike the Scala API, the Java API handles DStreams for key-value pairs using a separate <a href="api/streaming/index.html#org.apache.spark.streaming.api.java.JavaPairDStream">JavaPairDStream</a> class(similar to <a href="java-programming-guide.html#rdd-classes">JavaRDD and JavaPairRDD</a>. DStream functions like <code>map</code> and <code>filter</code> are implemented separately by JavaDStreams and JavaPairDStream to return DStreams of appropriate types.</li>
+</ol>
+
+<p>Spark&#8217;s <a href="java-programming-guide.html">Java Programming Guide</a> gives more ideas about using the Java API. To extends the ideas presented for the RDDs to DStreams, we present parts of the Java version of the same NetworkWordCount example presented above. The full source code is given at <code>&lt;spark repo&gt;/examples/src/main/java/spark/streaming/examples/JavaNetworkWordCount.java</code></p>
+
+<p>The streaming context and the socket stream from input source is started by using a <code>JavaStreamingContext</code>, that has the same parameters and provides the same input streams as its Scala counterpart.</p>
+
+<div class="highlight"><pre><code class="java"><span class="n">JavaStreamingContext</span> <span class="n">ssc</span> <span class="o">=</span> <span class="k">new</span> <span class="n">JavaStreamingContext</span><span class="o">(</span><span class="n">mesosUrl</span><span class="o">,</span> <span class="s">&quot;NetworkWordCount&quot;</span><span class="o">,</span> <span class="n">Seconds</span><span class="o">(</span><span class="mi">1</span><span class="o">));</span>
+<span class="n">JavaDStream</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">lines</span> <span class="o">=</span> <span class="n">ssc</span><span class="o">.</span><span class="na">socketTextStream</span><span class="o">(</span><span class="n">ip</span><span class="o">,</span> <span class="n">port</span><span class="o">);</span>
+</code></pre></div>
+
+<p>Then the <code>lines</code> are split into words by using the <code>flatMap</code> function and <a href="api/core/index.html#org.apache.spark.api.java.function.FlatMapFunction">FlatMapFunction</a>.</p>
+
+<div class="highlight"><pre><code class="java"><span class="n">JavaDStream</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">words</span> <span class="o">=</span> <span class="n">lines</span><span class="o">.</span><span class="na">flatMap</span><span class="o">(</span>
+  <span class="k">new</span> <span class="n">FlatMapFunction</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;()</span> <span class="o">{</span>
+    <span class="nd">@Override</span>
+    <span class="kd">public</span> <span class="n">Iterable</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="nf">call</span><span class="o">(</span><span class="n">String</span> <span class="n">x</span><span class="o">)</span> <span class="o">{</span>
+      <span class="k">return</span> <span class="n">Lists</span><span class="o">.</span><span class="na">newArrayList</span><span class="o">(</span><span class="n">x</span><span class="o">.</span><span class="na">split</span><span class="o">(</span><span class="s">&quot; &quot;</span><span class="o">));</span>
+    <span class="o">}</span>
+  <span class="o">});</span>
+</code></pre></div>
+
+<p>The <code>words</code> is then mapped to a <a href="api/streaming/index.html#org.apache.spark.streaming.api.java.JavaPairDStream">JavaPairDStream</a> of <code>(word, 1)</code> pairs using <code>map</code> and <a href="api/core/index.html#org.apache.spark.api.java.function.PairFunction">PairFunction</a>. This is  reduced by using <code>reduceByKey</code> and <a href="api/core/index.html#org.apache.spark.api.java.function.Function2">Function2</a>.</p>
+
+<div class="highlight"><pre><code class="java"><span class="n">JavaPairDStream</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;</span> <span class="n">wordCounts</span> <span class="o">=</span> <span class="n">words</span><span class="o">.</span><span class="na">map</span><span class="o">(</span>
+  <span class="k">new</span> <span class="n">PairFunction</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;()</span> <span class="o">{</span>
+    <span class="nd">@Override</span>
+    <span class="kd">public</span> <span class="n">Tuple2</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;</span> <span class="n">call</span><span class="o">(</span><span class="n">String</span> <span class="n">s</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
+      <span class="k">return</span> <span class="k">new</span> <span class="n">Tuple2</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;(</span><span class="n">s</span><span class="o">,</span> <span class="mi">1</span><span class="o">);</span>
+    <span class="o">}</span>
+  <span class="o">}).</span><span class="na">reduceByKey</span><span class="o">(</span>
+  <span class="k">new</span> <span class="n">Function2</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;()</span> <span class="o">{</span>
+    <span class="nd">@Override</span>
+    <span class="kd">public</span> <span class="n">Integer</span> <span class="nf">call</span><span class="o">(</span><span class="n">Integer</span> <span class="n">i1</span><span class="o">,</span> <span class="n">Integer</span> <span class="n">i2</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
+      <span class="k">return</span> <span class="n">i1</span> <span class="o">+</span> <span class="n">i2</span><span class="o">;</span>
+    <span class="o">}</span>
+  <span class="o">});</span>
+</code></pre></div>
+
+<h1 id="where-to-go-from-here">Where to Go from Here</h1>
+
+<ul>
+  <li>API docs - <a href="api/streaming/index.html#org.apache.spark.streaming.package">Scala</a> and <a href="api/streaming/index.html#org.apache.spark.streaming.api.java.package">Java</a></li>
+  <li>More examples - <a href="https://github.com/apache/incubator-spark/tree/master/examples/src/main/scala/spark/streaming/examples">Scala</a> and <a href="https://github.com/apache/incubator-spark/tree/master/examples/src/main/java/spark/streaming/examples">Java</a></li>
+  <li><a href="http://www.eecs.berkeley.edu/Pubs/TechRpts/2012/EECS-2012-259.pdf">Paper describing Spark Streaming</a></li>
+</ul>
+
+            <!-- Main hero unit for a primary marketing message or call to action -->
+            <!--<div class="hero-unit">
+                <h1>Hello, world!</h1>
+                <p>This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
+                <p><a class="btn btn-primary btn-large">Learn more &raquo;</a></p>
+            </div>-->
+
+            <!-- Example row of columns -->
+            <!--<div class="row">
+                <div class="span4">
+                    <h2>Heading</h2>
+                    <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
+                    <p><a class="btn" href="#">View details &raquo;</a></p>
+                </div>
+                <div class="span4">
+                    <h2>Heading</h2>
+                    <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
+                    <p><a class="btn" href="#">View details &raquo;</a></p>
+               </div>
+                <div class="span4">
+                    <h2>Heading</h2>
+                    <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
+                    <p><a class="btn" href="#">View details &raquo;</a></p>
+                </div>
+            </div>
+
+            <hr>-->
+
+            <footer>
+              <hr>
+              <p style="text-align: center; veritcal-align: middle; color: #999;">
+                Apache Spark is an effort undergoing incubation at the Apache Software Foundation.
+                <a href="http://incubator.apache.org">
+                  <img style="margin-left: 20px;" src="img/incubator-logo.png" />
+                </a>
+              </p>
+            </footer>
+
+        </div> <!-- /container -->
+
+        <script src="js/vendor/jquery-1.8.0.min.js"></script>
+        <script src="js/vendor/bootstrap.min.js"></script>
+        <script src="js/main.js"></script>
+        
+        <!-- A script to fix internal hash links because we have an overlapping top bar.
+             Based on https://github.com/twitter/bootstrap/issues/193#issuecomment-2281510 -->
+        <script>
+          $(function() {
+            function maybeScrollToHash() {
+              if (window.location.hash && $(window.location.hash).length) {
+                var newTop = $(window.location.hash).offset().top - $('#topbar').height() - 5;
+                $(window).scrollTop(newTop);
+              }
+            }
+            $(window).bind('hashchange', function() {
+              maybeScrollToHash();
+            });
+            // Scroll now too in case we had opened the page on a hash, but wait 1 ms because some browsers
+            // will try to do *their* initial scroll after running the onReady handler.
+            setTimeout(function() { maybeScrollToHash(); }, 1)
+          })
+        </script>
+
+    </body>
+</html>