<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://classes.engineering.wustl.edu/cse231/core/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Miles.p.cushing</id>
	<title>CSE231 Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://classes.engineering.wustl.edu/cse231/core/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Miles.p.cushing"/>
	<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Special:Contributions/Miles.p.cushing"/>
	<updated>2026-11-27T08:09:34Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.34.4</generator>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Fibonacci&amp;diff=2218</id>
		<title>Fibonacci</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Fibonacci&amp;diff=2218"/>
		<updated>2018-07-24T08:05:24Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
It is important to always reduce the work, then parallelize if possible.  In this studio you will build a beautiful, elegant solution to Fibonacci which can be easily parallelized yielding off-the-charts ideal parallelism.  Sadly, it performs terribly since the work is exponential.  It is far better to build a linear or log time algorithm whether or not it can be parallelized.&lt;br /&gt;
&lt;br /&gt;
We will gain experience with the future construct.&lt;br /&gt;
&lt;br /&gt;
We will convert recurrence relations into code.&lt;br /&gt;
&lt;br /&gt;
Additionally, (and of minor importance) we gain experience working with the [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger] class.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
The fibonacci sequence is a mathematical concept often used in computer science as a means to demonstrate iteration and recursion. Although you should be familiar with it from CSE 131, we will use the fibonacci sequence to demonstrate memoization and dynamic programming. Follow these links for a quick recap on [http://classes.engineering.wustl.edu/cse231/core/index.php/FAQ#Unit_2:_Futures.2FAccumulators.2FData_Races.2FMemoization memoization, dynamic programming], and the [https://en.wikipedia.org/wiki/Fibonacci_number fibonacci sequence].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;SjSHVDfXHQ4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://www.scientificamerican.com/video/the-mind-blowing-mathematics-of-sunflowers/ Scientific American Video]: [[File:Fibonacci spiral.jpg|400px]]&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
&amp;lt;youtube&amp;gt;PELL8QxKl4M&amp;lt;/youtube&amp;gt;&lt;br /&gt;
===Parallel Docs===&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#future-edu.wustl.cse231s.v5.api.CheckedCallable- future(body)] &lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html interface Future&amp;lt;V&amp;gt;].  &lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-- get()]&lt;br /&gt;
&lt;br /&gt;
Check out the [[Reference_Page#Future|wiki's reference page]] to see how Future's can be used!&lt;br /&gt;
&lt;br /&gt;
===BigInteger Docs===&lt;br /&gt;
fibonacci(47) is greater than [https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#MAX_VALUE Integer.MAX_VALUE] which would [https://en.wikipedia.org/wiki/Integer_overflow overflow] if we used the [https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html primitive int data type].  We use [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger] instead to prevent this problem.&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#ZERO BigInteger.ZERO]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#ONE BigInteger.ONE]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add-java.math.BigInteger- bi.add(other)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#multiply-java.math.BigInteger- bi.multiply(other)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#valueOf-long- bi.valueOf(val)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#shiftLeft-int- bi.shiftLeft(n)]&lt;br /&gt;
&lt;br /&gt;
=Studio (Required)=&lt;br /&gt;
&lt;br /&gt;
For the required part of the studio, you will be implementing a Fibonacci calculator five different ways. Some will be in parallel, some won't. The goal for each is to simply have it return the nth Fibonacci number that is initially passed through &lt;br /&gt;
&lt;br /&gt;
==RecurrenceRelationSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(\Phi^n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|RecurrenceRelationSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
The first file to complete is the basic recursive solution to Fibonacci. This should be done sequentially, and won't look too different from when you did it back in 131. Remember that instead of adding integers, we are using BigIntegers, so make sure to properly handle those.&lt;br /&gt;
&lt;br /&gt;
===recurrence relation===&lt;br /&gt;
: &amp;lt;math&amp;gt;F_n = F_{n-1} + F_{n-2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===seed values===&lt;br /&gt;
: &amp;lt;math&amp;gt;F_0=0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;F_1=1&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RecurrenceRelationParallelFibonacciCalculator==&lt;br /&gt;
{{WorkCPLIdealParallelism|&amp;lt;math&amp;gt;O(\Phi^n)&amp;lt;/math&amp;gt;|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;|&amp;lt;math&amp;gt;\dfrac{\Phi^n}{n}&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|RecurrenceRelationParallelFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Parallel|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
Now make the solution you just wrote parallel, such that &amp;lt;code&amp;gt;fibonacci(n-1)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;fibonacci(n-2)&amp;lt;/code&amp;gt; are being solved at the same time. Do this by using futures. Make sure to call future.get() at the right time so there is sufficient parallelism.&lt;br /&gt;
&lt;br /&gt;
==MemoizationSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|MemoizationSequentialFibonacciCalculator|fibonacciMemo|fibonacci.studio}}&lt;br /&gt;
{{Sequential|private BigInteger fibonacciMemo(BigInteger[] memos, int n)}}&lt;br /&gt;
&lt;br /&gt;
The recurrence relation algorithm for Fibonacci has a lot of repeated calculations. For example, if we want fibonacci(10), we need to calculate fibonacci(9) and fibonacci(8), but during the calculations of fibonacci(9), we also calculate fibonacci(8), so that part is getting repeated. The bigger the number, the more repetition there is and the larger impact it has on our performance. The smart way to get around this is memoization. By storing our calculation results (in this case, with an array), we can simply refer to the work we've already done rather than doing it again.&lt;br /&gt;
&lt;br /&gt;
Implement the recurrence relation algorithm again (sequentially), but employ memoization this time for the win. Make sure to store your work, and only do more work if it hasn't yet been done.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public BigInteger fibonacci(int n) {&lt;br /&gt;
		BigInteger[] memos = new BigInteger[n + 1];&lt;br /&gt;
		return fibonacciMemo(memos, n);&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT invoke fibonacci from fibonacciMemo.  Invoke fibonacciMemo from fibonacciMemo. }}&lt;br /&gt;
{{Warning | The entire point of memoization is to avoid recalculating the same computation.  Be sure to store the value for each calculation as it is made even if that means splitting up a line of code.}}&lt;br /&gt;
&lt;br /&gt;
==DynamicIterativeSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|DynamicIterativeSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
In the previous algortihms, we've been tackling this problem from the top-down. But that isn't always the easiest way to think about the problem. Imagine you are simply writing out Fibonacci numbers:&lt;br /&gt;
&lt;br /&gt;
: 0, 1, 1, 2, 3, 5, 8, 13...&lt;br /&gt;
&lt;br /&gt;
You (assuming you aren't a human super-computer) start from the very bottom, and keep working the sequence up to your answer. For this class, convert that process of summing the two previous numbers over and over into code. It should be sequential, and ''not have any recursive calls''.&lt;br /&gt;
&lt;br /&gt;
==LinearRecurrenceSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}} &lt;br /&gt;
&lt;br /&gt;
note: can be memoized to {{Work|&amp;lt;math&amp;gt;O(\log{}n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|LinearRecurrenceSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
Thanks to how awesome math is, we can actually solve the ''n''th Fibonacci number without knowing those for n-1 and n-2. We have provided the algorithm below. It is your job to translate this into code. Keep it sequential. &lt;br /&gt;
&lt;br /&gt;
Once you finish with this, make sure to go back and compare the performance speed of all five of these algorithms. The results are very thought-provoking!&lt;br /&gt;
&lt;br /&gt;
===recurrence relation===&lt;br /&gt;
&lt;br /&gt;
: if n is odd&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;k = \dfrac{n+1}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;F_n = (F_{k} \times F_{k}) + (F_{k-1} \times F_{k-1})&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:else&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;k = \dfrac{n}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;F_n = ((2 \times F_{k-1}) + F_{k}) \times F_{k}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===seed values===&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;F_0=0&amp;lt;/math&amp;gt;&lt;br /&gt;
: &amp;lt;math&amp;gt;F_1=1&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT invoke &amp;lt;code&amp;gt;fibonacci(k)&amp;lt;/code&amp;gt; or  &amp;lt;code&amp;gt;fibonacci(k-1)&amp;lt;/code&amp;gt; multiple times if you can catch the result in a variable and reuse it. }}&lt;br /&gt;
{{Tip | There is no need to store k in a BigInteger.  Since it is smaller than n, it will fit just fine in an int. }}&lt;br /&gt;
{{Tip | You can shift left by 1 if you would prefer to not have to multiply by the big integer value of 2.}}&lt;br /&gt;
&lt;br /&gt;
=Fun (Optional)=&lt;br /&gt;
==RecurrenceRelationParallelWithThresholdFibonacciCalculator==&lt;br /&gt;
Similar to [[#RecurrenceRelationParallelFibonacciCalculator]] but with a threshold in place to prevent creating too many tasks for the number of processors.&lt;br /&gt;
&lt;br /&gt;
==MemoizationParallelFibonacciCalculator==&lt;br /&gt;
Create all of your futures [0..N] up front and then call get on memo[n].&lt;br /&gt;
==DynamicRecursiveSequentialFibonacciCalculator==&lt;br /&gt;
==RoundPhiToTheNOverSqrt5SequentialFibonacciCalculator==&lt;br /&gt;
&amp;lt;math&amp;gt;\dfrac{\Phi^n}{\sqrt{5}}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|FibonacciTestSuite|fibonacci.studio}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|FibonacciTiming|fibonacci.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Performance|FibonacciIterations|fibonacci.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Fibonacci&amp;diff=2217</id>
		<title>Fibonacci</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Fibonacci&amp;diff=2217"/>
		<updated>2018-07-24T07:56:29Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Studio (Required) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
It is important to always reduce the work, then parallelize if possible.  In this studio you will build a beautiful, elegant solution to Fibonacci which can be easily parallelized yielding off-the-charts ideal parallelism.  Sadly, it performs terribly since the work is exponential.  It is far better to build a linear or log time algorithm whether or not it can be parallelized.&lt;br /&gt;
&lt;br /&gt;
We will gain experience with the future construct.&lt;br /&gt;
&lt;br /&gt;
We will convert recurrence relations into code.&lt;br /&gt;
&lt;br /&gt;
Additionally, (and of minor importance) we gain experience working with the [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger] class.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
The fibonacci sequence is a mathematical concept often used in computer science as a means to demonstrate iteration and recursion. Although you should be familiar with it from CSE 131, we will use the fibonacci sequence to demonstrate memoization and dynamic programming. Follow these links for a quick recap on [http://classes.engineering.wustl.edu/cse231/core/index.php/FAQ#Unit_2:_Futures.2FAccumulators.2FData_Races.2FMemoization memoization, dynamic programming], and the [https://en.wikipedia.org/wiki/Fibonacci_number fibonacci sequence].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;SjSHVDfXHQ4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://www.scientificamerican.com/video/the-mind-blowing-mathematics-of-sunflowers/ Scientific American Video]: [[File:Fibonacci spiral.jpg|400px]]&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
&amp;lt;youtube&amp;gt;PELL8QxKl4M&amp;lt;/youtube&amp;gt;&lt;br /&gt;
===Parallel Docs===&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#future-edu.wustl.cse231s.v5.api.CheckedCallable- future(body)] &lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html interface Future&amp;lt;V&amp;gt;].  &lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-- get()]&lt;br /&gt;
&lt;br /&gt;
Check out the [[Reference_Page#Future|wiki's reference page]] to see how Future's can be used!&lt;br /&gt;
&lt;br /&gt;
===BigInteger Docs===&lt;br /&gt;
fibonacci(47) is greater than [https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#MAX_VALUE Integer.MAX_VALUE] which would [https://en.wikipedia.org/wiki/Integer_overflow overflow] if we used the [https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html primitive int data type].  We use [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger] instead to prevent this problem.&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#ZERO BigInteger.ZERO]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#ONE BigInteger.ONE]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add-java.math.BigInteger- bi.add(other)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#multiply-java.math.BigInteger- bi.multiply(other)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#valueOf-long- bi.valueOf(val)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#shiftLeft-int- bi.shiftLeft(n)]&lt;br /&gt;
&lt;br /&gt;
=Studio (Required)=&lt;br /&gt;
&lt;br /&gt;
For the required part of the studio, you will be implementing a Fibonacci calculator five different ways. Some will be in parallel, some won't. The goal for each is to simply have it return the nth Fibonacci number that is initially passed through &lt;br /&gt;
&lt;br /&gt;
==RecurrenceRelationSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(\Phi^n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|RecurrenceRelationSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
The first file to complete is the basic recursive solution to Fibonacci. This should be done sequentially, and won't look too different from when you did it back in 131. Remember that instead of adding integers, we are using BigIntegers, so make sure to properly handle those.&lt;br /&gt;
&lt;br /&gt;
===recurrence relation===&lt;br /&gt;
: &amp;lt;math&amp;gt;F_n = F_{n-1} + F_{n-2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===seed values===&lt;br /&gt;
: &amp;lt;math&amp;gt;F_0=0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;F_1=1&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RecurrenceRelationParallelFibonacciCalculator==&lt;br /&gt;
{{WorkCPLIdealParallelism|&amp;lt;math&amp;gt;O(\Phi^n)&amp;lt;/math&amp;gt;|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;|&amp;lt;math&amp;gt;\dfrac{\Phi^n}{n}&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|RecurrenceRelationParallelFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Parallel|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
Now make the solution you just wrote parallel, such that solving &amp;lt;code&amp;gt;fibonacci(n-1)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;fibonacci(n-2)&amp;lt;/code&amp;gt; are being solved at the same time. Do this by using futures. Make sure to call future.get() at the right time so there is sufficient parallelism.&lt;br /&gt;
&lt;br /&gt;
==MemoizationSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|MemoizationSequentialFibonacciCalculator|fibonacciMemo|fibonacci.studio}}&lt;br /&gt;
{{Sequential|private BigInteger fibonacciMemo(BigInteger[] memos, int n)}}&lt;br /&gt;
&lt;br /&gt;
The recurrence relation algorithm for Fibonacci has a lot of repeated calculations. For example, if we want fibonacci(10), we need to calculate fibonacci(9) and fibonacci(8), but during the calculations of fibonacci(9), we also calculate fibonacci(8), so that part is getting repeated. The bigger the number, the more repetition there is and the larger impact it has on our performance. The smart way to get around this is memoization. By storing our calculation results (in this case, with an array), we can simply refer to the work we've already done rather than doing it again.&lt;br /&gt;
&lt;br /&gt;
Implement the recurrence relation algorithm again (sequentially), but employ memoization this time for the win. Make sure to store your work, and only do more work if it hasn't yet been done.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public BigInteger fibonacci(int n) {&lt;br /&gt;
		BigInteger[] memos = new BigInteger[n + 1];&lt;br /&gt;
		return fibonacciMemo(memos, n);&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT invoke fibonacci from fibonacciMemo.  Invoke fibonacciMemo from fibonacciMemo. }}&lt;br /&gt;
{{Warning | The entire point of memoization is to avoid recalculating the same computation.  Be sure to store the value for each calculation as it is made even if that means splitting up a line of code.}}&lt;br /&gt;
&lt;br /&gt;
==DynamicIterativeSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|DynamicIterativeSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
In the previous algortihms, we've been tackling this problem from the top-down. But that isn't always the easiest way to think about the problem. Imagine you are simply writing out Fibonacci numbers:&lt;br /&gt;
&lt;br /&gt;
: 0, 1, 1, 2, 3, 5, 8, 13...&lt;br /&gt;
&lt;br /&gt;
You (assuming you aren't a human super-computer) start from the very bottom, and keep working the sequence up to your answer. For this class, convert that process of summing the two previous numbers over and over into code. It should be sequential, and '''not have any recursive calls'''.&lt;br /&gt;
&lt;br /&gt;
==LinearRecurrenceSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}} &lt;br /&gt;
&lt;br /&gt;
note: can be memoized to {{Work|&amp;lt;math&amp;gt;O(\log{}n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|LinearRecurrenceSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT invoke &amp;lt;code&amp;gt;fibonacci(k)&amp;lt;/code&amp;gt; or  &amp;lt;code&amp;gt;fibonacci(k-1)&amp;lt;/code&amp;gt; multiple times if you can catch the result in a variable and reuse it. }}&lt;br /&gt;
{{Tip | There is no need to store k in a BigInteger.  Since it is smaller than n, it will fit just fine in an int. }}&lt;br /&gt;
{{Tip | You can shift left by 1 if you would prefer to not have to multiply by the big integer value of 2.}}&lt;br /&gt;
===recurrence relation===&lt;br /&gt;
&lt;br /&gt;
: if n is odd&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;k = \dfrac{n+1}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;F_n = (F_{k} \times F_{k}) + (F_{k-1} \times F_{k-1})&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:else&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;k = \dfrac{n}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;F_n = ((2 \times F_{k-1}) + F_{k}) \times F_{k}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===seed values===&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;F_0=0&amp;lt;/math&amp;gt;&lt;br /&gt;
: &amp;lt;math&amp;gt;F_1=1&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Fun (Optional)=&lt;br /&gt;
==RecurrenceRelationParallelWithThresholdFibonacciCalculator==&lt;br /&gt;
Similar to [[#RecurrenceRelationParallelFibonacciCalculator]] but with a threshold in place to prevent creating too many tasks for the number of processors.&lt;br /&gt;
&lt;br /&gt;
==MemoizationParallelFibonacciCalculator==&lt;br /&gt;
Create all of your futures [0..N] up front and then call get on memo[n].&lt;br /&gt;
==DynamicRecursiveSequentialFibonacciCalculator==&lt;br /&gt;
==RoundPhiToTheNOverSqrt5SequentialFibonacciCalculator==&lt;br /&gt;
&amp;lt;math&amp;gt;\dfrac{\Phi^n}{\sqrt{5}}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|FibonacciTestSuite|fibonacci.studio}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|FibonacciTiming|fibonacci.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Performance|FibonacciIterations|fibonacci.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=AllOrNothingLocks&amp;diff=2216</id>
		<title>AllOrNothingLocks</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=AllOrNothingLocks&amp;diff=2216"/>
		<updated>2018-07-24T06:39:15Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [http://jcip.net/ Java Concurrency in Practice], Ben Choi, and Dennis Cosgrove&lt;br /&gt;
&lt;br /&gt;
=Motivation=&lt;br /&gt;
In addition to [[Ordered_Locks||Ordered Locks]] we can employ an all-or-nothing strategy for acquiring locks for mutual exclusion.&lt;br /&gt;
&lt;br /&gt;
We gain experience with explicit locks and trying to acquire them and responding appropriately to success and failure.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
Check out the [[Lock_Ordering#Background|lock ordering]] studio.&lt;br /&gt;
&lt;br /&gt;
In Java, locks are a synchronization tool that exists to ensure whatever is protected by the lock is only accessed one thread at a time, as to avoid a possible data race. In this studio we will explore the second type of locks: explicitly created &amp;lt;code&amp;gt;Lock&amp;lt;/code&amp;gt; objects from the &amp;lt;code&amp;gt;java.util.concurrent.locks&amp;lt;/code&amp;gt; package.&lt;br /&gt;
&lt;br /&gt;
Every object has an intrinsic lock associated with the object, but &amp;lt;code&amp;gt;Lock&amp;lt;/code&amp;gt; objects are explicitly defined and instantiated locks which can be called to lock or unlock. Lock objects are acted upon just like any other object, but we are mostly interested in the &amp;lt;code&amp;gt;lock()&amp;lt;/code&amp;gt; method, the &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; method, and the &amp;lt;code&amp;gt;unlock()&amp;lt;/code&amp;gt; method. For this studio, we will specifically use the &amp;lt;code&amp;gt;ReentrantLock&amp;lt;/code&amp;gt; object, a class which implements the general &amp;lt;code&amp;gt;Lock&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
To demonstrate how to avoid both data races and deadlock issues, we will create a method designed to transfer money between two bank accounts. Two parties should be able to asynchronously and continuously transfer money between each other without a data race (courtesy of locks) or deadlock (something you will address).&lt;br /&gt;
&lt;br /&gt;
For this approach, we will make use of the &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; method in order to attempt to acquire an object’s lock. If the object’s lock is not available at the time, we will continue to try to acquire the lock until it finally succeeds, after which we can successfully transfer funds from one bank account to another. In this approach, an asynchronous pair of transfers from A to B and B to A will not lead to deadlock as the two processes will give up on acquiring the lock until it becomes available, at which point it will finally acquire the lock. This approach does not make use of ordering, but simply relies on making lock attempts give up if the desired lock is not immediately available (and then try again later).&lt;br /&gt;
&lt;br /&gt;
==Java Util Concurrent==&lt;br /&gt;
Refer to Oracle's official documentation for more information:&lt;br /&gt;
* [https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html Lock Objects Tutorial] &lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/package-summary.html package java.util.concurrent.locks]&lt;br /&gt;
&lt;br /&gt;
*[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html while loops]&lt;br /&gt;
*[https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html finally]&lt;br /&gt;
*[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#yield-- Thread yield]&lt;br /&gt;
&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html-- Lock]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html#tryLock-- tryLock]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html#unlock--- unlock]&lt;br /&gt;
&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html--- ReentrantLock]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html#isHeldByCurrentThread--- isHeldByCurrentThread ]&lt;br /&gt;
&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html ListIterator&amp;lt;E&amp;gt;]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#hasNext-- boolean hasNext()]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#next-- E next()]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#hasPrevious-- boolean hasPrevious()]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#previous-- E previous()]&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
As mentioned in the background section, this implementation will avoid deadlock by giving up on acquiring a lock if it is not immediately available before coming back to it later (when it might actually be available). This implementation will need to make use of the ReentrantLocks associated with the sender and recipient bank account objects. More specifically, it will have to make use of the &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; method. For an example of how to format a tryLock, look below:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===BankAccountTryLocking===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|BankAccountLockTrying|tryTransferMoney|lock.allornothing.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static TransferResult tryTransferMoney(AccountWithLock sender, AccountWithLock recipient, int amount)}}&lt;br /&gt;
&lt;br /&gt;
Open &amp;lt;code&amp;gt;BankAccountTryLocking.java&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A couple of notes and common issues:&lt;br /&gt;
&lt;br /&gt;
*&amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; will immediately give up and return false if the lock is not available when it is called. Thus, you will need to construct a loop that will continuously run until the desired lock is available. You can exit out of this loop in two ways: with the break keyword or by returning a valid value for the method. We do this for you so you will not need to write any loops.&lt;br /&gt;
*&amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; will grab the lock if it can. There's no need to call &amp;lt;code&amp;gt;lock()&amp;lt;/code&amp;gt; after &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt;.&lt;br /&gt;
*We recommend you call the &amp;lt;code&amp;gt;AccountUtils.checkBalanceAndTransfer(sender, receiver, amount)&amp;lt;/code&amp;gt; method for the sake of simplicity. This method will check that the sender and recipient are not the same people and that the sender has enough money in her account to send the specified amount to the recipient.&lt;br /&gt;
*Anytime you lock a lock object, you should/must use a &amp;lt;code&amp;gt;try/finally&amp;lt;/code&amp;gt; block to unlock the lock.&lt;br /&gt;
*Your implementation will have to make use of a nested &amp;lt;code&amp;gt;try/finally&amp;lt;/code&amp;gt; block (one &amp;lt;code&amp;gt;try/finally&amp;lt;/code&amp;gt; call within another).&lt;br /&gt;
&lt;br /&gt;
===LockUtils runWithAllLocksOrDontRunAtAll===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|LockUtils|tryLockAll&amp;lt;br&amp;gt;unlockAllHeldLocks&amp;lt;br&amp;gt;runWithAllLocksOrDontRunAtAll|lock.allornothing.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static boolean tryLockAll(List&amp;lt;ReentrantLock&amp;gt; locks)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void unlockAll(List&amp;lt;ReentrantLock&amp;gt; locks)}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static boolean runWithAllLocksOrDontRunAtAll(List&amp;lt;ReentrantLock&amp;gt; locks, Runnable body)}}&lt;br /&gt;
&lt;br /&gt;
Open &amp;lt;code&amp;gt;LockUtils.java&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For this part of the studio you will need to implement:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;private static boolean tryLockAll(List&amp;lt;ReentrantLock&amp;gt; locks)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;private static void unlockAll(List&amp;lt;ReentrantLock&amp;gt; locks)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
so that the useful utility (shouldn't they all be useful?) &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static boolean runWithAllLocksOrDontRunAtAll(List&amp;lt;ReentrantLock&amp;gt; locks, Runnable body) {&lt;br /&gt;
	boolean status = tryLockAll(locks);&lt;br /&gt;
	if (status) {&lt;br /&gt;
		try {&lt;br /&gt;
			body.run();&lt;br /&gt;
		} finally {&lt;br /&gt;
			unlockAll(locks);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return status;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
produces correct thread safe behavior.&lt;br /&gt;
&lt;br /&gt;
Note: in &amp;lt;code&amp;gt;tryLockAll&amp;lt;/code&amp;gt;, you will need to call &amp;lt;code&amp;gt;tryLock&amp;lt;/code&amp;gt; on all of the given locks. However, if one fails, you will need to unlock everything you have currently locked. A lock cannot be unlocked from a thread that doesn't hold the lock. Consider using the [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html ListIterator] interface.&lt;br /&gt;
&lt;br /&gt;
{{Warning | If tryLockAll fails to acquire all of the locks, make sure to unlock any of the locks you did acquire.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | If tryLockAll fails, when rolling back a ListIterator to unlock any locks you acquired, be sure to do an initial prev() to set the iterator in the correct location before looping through to unlock the rest.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | An IllegalMonitorStateException() means that a thread tried to unlock a lock that it was not holding. }}&lt;br /&gt;
&lt;br /&gt;
===KitchenLockUtilsApp===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|KitchenLockUtilsApp|executeRecipe|lock.allornothing.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static boolean executeRecipe(Recipe recipe)}}&lt;br /&gt;
&lt;br /&gt;
Open &amp;lt;code&amp;gt;KitchenLockUtilsApp.java&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A couple of notes:&lt;br /&gt;
&lt;br /&gt;
*An object of class Recipe contains a list of Appliances that it needs in order to complete the item. An object of class Appliance has a lock that you can use to make sure the method remains thread-safe.&lt;br /&gt;
*Use the &amp;lt;code&amp;gt;recipe.create()&amp;lt;/code&amp;gt; method in order to actually execute the recipe. Caution: this method will throw an &amp;lt;code&amp;gt;IllegalThreadStateException()&amp;lt;/code&amp;gt; if it is called without all the locks being held by the same thread that called the create method.&lt;br /&gt;
* Since it is unknown how many locks each recipe will need beforehand, make use of the &amp;lt;code&amp;gt;LockUtils.runWithAllLocksOrDontRunAtAll(List&amp;lt;ReentrantLock&amp;gt; locks, Runnable body)&amp;lt;/code&amp;gt; method you wrote earlier.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|TryLockingTestSuite|lock.allornothing.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=AllOrNothingLocks&amp;diff=2215</id>
		<title>AllOrNothingLocks</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=AllOrNothingLocks&amp;diff=2215"/>
		<updated>2018-07-24T06:33:00Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [http://jcip.net/ Java Concurrency in Practice], Ben Choi, and Dennis Cosgrove&lt;br /&gt;
&lt;br /&gt;
=Motivation=&lt;br /&gt;
In addition to [[Ordered_Locks]] we can employ an all-or-nothing strategy for acquiring locks for mutual exclusion.&lt;br /&gt;
&lt;br /&gt;
We gain experience with explicit locks and trying to acquire them and responding appropriately to success and failure.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
Check out the [[Lock_Ordering#Background|lock ordering]] studio.&lt;br /&gt;
&lt;br /&gt;
In Java, locks are a synchronization tool that exists to ensure whatever is protected by the lock is only accessed one thread at a time, as to avoid a possible data race. In this studio we will explore the second type of locks: explicitly created &amp;lt;code&amp;gt;Lock&amp;lt;/code&amp;gt; objects from the &amp;lt;code&amp;gt;java.util.concurrent.locks&amp;lt;/code&amp;gt; package.&lt;br /&gt;
&lt;br /&gt;
Every object has an intrinsic lock associated with the object, but &amp;lt;code&amp;gt;Lock&amp;lt;/code&amp;gt; objects are explicitly defined and instantiated locks which can be called to lock or unlock. Lock objects are acted upon just like any other object, but we are mostly interested in the &amp;lt;code&amp;gt;lock()&amp;lt;/code&amp;gt; method, the &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; method, and the &amp;lt;code&amp;gt;unlock()&amp;lt;/code&amp;gt; method. For this studio, we will specifically use the &amp;lt;code&amp;gt;ReentrantLock&amp;lt;/code&amp;gt; object, a class which implements the general &amp;lt;code&amp;gt;Lock&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
To demonstrate how to avoid both data races and deadlock issues, we will create a method designed to transfer money between two bank accounts. Two parties should be able to asynchronously and continuously transfer money between each other without a data race (courtesy of locks) or deadlock (something you will address).&lt;br /&gt;
&lt;br /&gt;
For this approach, we will make use of the &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; method in order to attempt to acquire an object’s lock. If the object’s lock is not available at the time, we will continue to try to acquire the lock until it finally succeeds, after which we can successfully transfer funds from one bank account to another. In this approach, an asynchronous pair of transfers from A to B and B to A will not lead to deadlock as the two processes will give up on acquiring the lock until it becomes available, at which point it will finally acquire the lock. This approach does not make use of ordering, but simply relies on making lock attempts give up if the desired lock is not immediately available (and then try again later).&lt;br /&gt;
&lt;br /&gt;
==Java Util Concurrent==&lt;br /&gt;
Refer to Oracle's official documentation for more information:&lt;br /&gt;
* [https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html Lock Objects Tutorial] &lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/package-summary.html package java.util.concurrent.locks]&lt;br /&gt;
&lt;br /&gt;
*[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html while loops]&lt;br /&gt;
*[https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html finally]&lt;br /&gt;
*[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#yield-- Thread yield]&lt;br /&gt;
&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html-- Lock]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html#tryLock-- tryLock]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html#unlock--- unlock]&lt;br /&gt;
&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html--- ReentrantLock]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html#isHeldByCurrentThread--- isHeldByCurrentThread ]&lt;br /&gt;
&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html ListIterator&amp;lt;E&amp;gt;]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#hasNext-- boolean hasNext()]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#next-- E next()]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#hasPrevious-- boolean hasPrevious()]&lt;br /&gt;
** [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html#previous-- E previous()]&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
As mentioned in the background section, this implementation will avoid deadlock by giving up on acquiring a lock if it is not immediately available before coming back to it later (when it might actually be available). This implementation will need to make use of the ReentrantLocks associated with the sender and recipient bank account objects. More specifically, it will have to make use of the &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; method. For an example of how to format a tryLock, look below:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===BankAccountTryLocking===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|BankAccountLockTrying|tryTransferMoney|lock.allornothing.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static TransferResult tryTransferMoney(AccountWithLock sender, AccountWithLock recipient, int amount)}}&lt;br /&gt;
&lt;br /&gt;
Open &amp;lt;code&amp;gt;BankAccountTryLocking.java&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A couple of notes and common issues:&lt;br /&gt;
&lt;br /&gt;
*&amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; will immediately give up and return false if the lock is not available when it is called. Thus, you will need to construct a loop that will continuously run until the desired lock is available. You can exit out of this loop in two ways: with the break keyword or by returning a valid value for the method. We do this for you so you will not need to write any loops.&lt;br /&gt;
*&amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt; will grab the lock if it can. There's no need to call &amp;lt;code&amp;gt;lock()&amp;lt;/code&amp;gt; after &amp;lt;code&amp;gt;tryLock()&amp;lt;/code&amp;gt;.&lt;br /&gt;
*We recommend you call the &amp;lt;code&amp;gt;AccountUtils.checkBalanceAndTransfer(sender, receiver, amount)&amp;lt;/code&amp;gt; method for the sake of simplicity. This method will check that the sender and recipient are not the same people and that the sender has enough money in her account to send the specified amount to the recipient.&lt;br /&gt;
*Anytime you lock a lock object, you should/must use a &amp;lt;code&amp;gt;try/finally&amp;lt;/code&amp;gt; block to unlock the lock.&lt;br /&gt;
*Your implementation will have to make use of a nested &amp;lt;code&amp;gt;try/finally&amp;lt;/code&amp;gt; block (one &amp;lt;code&amp;gt;try/finally&amp;lt;/code&amp;gt; call within another).&lt;br /&gt;
&lt;br /&gt;
===LockUtils runWithAllLocksOrDontRunAtAll===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|LockUtils|tryLockAll&amp;lt;br&amp;gt;unlockAllHeldLocks&amp;lt;br&amp;gt;runWithAllLocksOrDontRunAtAll|lock.allornothing.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static boolean tryLockAll(List&amp;lt;ReentrantLock&amp;gt; locks)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void unlockAll(List&amp;lt;ReentrantLock&amp;gt; locks)}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static boolean runWithAllLocksOrDontRunAtAll(List&amp;lt;ReentrantLock&amp;gt; locks, Runnable body)}}&lt;br /&gt;
&lt;br /&gt;
Open &amp;lt;code&amp;gt;LockUtils.java&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For this part of the studio you will need to implement:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;private static boolean tryLockAll(List&amp;lt;ReentrantLock&amp;gt; locks)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;private static void unlockAll(List&amp;lt;ReentrantLock&amp;gt; locks)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
so that the useful utility (shouldn't they all be useful?) &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static boolean runWithAllLocksOrDontRunAtAll(List&amp;lt;ReentrantLock&amp;gt; locks, Runnable body) {&lt;br /&gt;
	boolean status = tryLockAll(locks);&lt;br /&gt;
	if (status) {&lt;br /&gt;
		try {&lt;br /&gt;
			body.run();&lt;br /&gt;
		} finally {&lt;br /&gt;
			unlockAll(locks);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return status;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
produces correct thread safe behavior.&lt;br /&gt;
&lt;br /&gt;
Note: in &amp;lt;code&amp;gt;tryLockAll&amp;lt;/code&amp;gt;, you will need to call &amp;lt;code&amp;gt;tryLock&amp;lt;/code&amp;gt; on all of the given locks. However, if one fails, you will need to unlock everything you have currently locked. A lock cannot be unlocked from a thread that doesn't hold the lock. Consider using the [https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html ListIterator] interface.&lt;br /&gt;
&lt;br /&gt;
{{Warning | If tryLockAll fails to acquire all of the locks, make sure to unlock any of the locks you did acquire.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | If tryLockAll fails, when rolling back a ListIterator to unlock any locks you acquired, be sure to do an initial prev() to set the iterator in the correct location before looping through to unlock the rest.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | An IllegalMonitorStateException() means that a thread tried to unlock a lock that it was not holding. }}&lt;br /&gt;
&lt;br /&gt;
===KitchenLockUtilsApp===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|KitchenLockUtilsApp|executeRecipe|lock.allornothing.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static boolean executeRecipe(Recipe recipe)}}&lt;br /&gt;
&lt;br /&gt;
Open &amp;lt;code&amp;gt;KitchenLockUtilsApp.java&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A couple of notes:&lt;br /&gt;
&lt;br /&gt;
*An object of class Recipe contains a list of Appliances that it needs in order to complete the item. An object of class Appliance has a lock that you can use to make sure the method remains thread-safe.&lt;br /&gt;
*Use the &amp;lt;code&amp;gt;recipe.create()&amp;lt;/code&amp;gt; method in order to actually execute the recipe. Caution: this method will throw an &amp;lt;code&amp;gt;IllegalThreadStateException()&amp;lt;/code&amp;gt; if it is called without all the locks being held by the same thread that called the create method.&lt;br /&gt;
* Since it is unknown how many locks each recipe will need beforehand, make use of the &amp;lt;code&amp;gt;LockUtils.runWithAllLocksOrDontRunAtAll(List&amp;lt;ReentrantLock&amp;gt; locks, Runnable body)&amp;lt;/code&amp;gt; method you wrote earlier.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|TryLockingTestSuite|lock.allornothing.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Ordered_Locks&amp;diff=2214</id>
		<title>Ordered Locks</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Ordered_Locks&amp;diff=2214"/>
		<updated>2018-07-24T06:31:54Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [http://jcip.net/ Java Concurrency in Practice], Ben Choi, and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
X10's isolated construct provides mutual exclusion while avoiding deadlock.  We will learn how to achieve this desirable property of deadlock freedom by ordering locks.&lt;br /&gt;
&lt;br /&gt;
We will gain experience with implicit locks and the synchronized statement.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
In Java, locks are a synchronization tool that exists to ensure whatever is protected by the lock is only accessed one thread at a time, as to avoid a possible data race. We will explore the first of two different types of locks: intrinsic locks.&lt;br /&gt;
&lt;br /&gt;
Every object has an intrinsic lock associated with the object. Intrinsic locks are accessed with the &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; keyword. &lt;br /&gt;
&lt;br /&gt;
To demonstrate how to avoid both data races and deadlock issues, we will create a method designed to transfer money between two bank accounts. Two parties should be able to safely transfer money between each other without a data race (courtesy of locks) or deadlock (something you will address).&lt;br /&gt;
&lt;br /&gt;
In this studio we will use lock ordering to avoid deadlock.&lt;br /&gt;
&lt;br /&gt;
With lock ordering, we will control the order in which locks are acquired for two bank accounts using unique identifying values associated with the bank accounts. In this way, a transfer from bank account A to B paired with a simultaneous transfer from B to A will not lead to a scenario in which A is waiting for B’s lock forever while B is waiting for A’s lock forever, as both calls will always attempt to go for A’s lock before B’s or vice versa. For a general object, we might use the object’s hashcode as the unique identifying value, but for this assignment, we will use the account number associated with the bank account (which is guaranteed to be unique, unlike hashcodes).&lt;br /&gt;
&lt;br /&gt;
Refer to Oracle's official documentation regarding [https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html intrinsic locks/synchronization] for more information.&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
Navigate to &amp;lt;code&amp;gt;LockOrdering.java&amp;lt;/code&amp;gt;. As mentioned in the background section, we will attempt to prevent deadlock using a lock ordering algorithm of your making. Essentially, whenever an operation needs to use two separate locks, make sure that the locks are always acquired in a fixed order no matter how the operation is called. The general way to do this is to compare the identity hash codes of the two objects and enforce an order based on those values. However, this can lead to a rare issue in which the two objects are unique, but have the same hashcode. &lt;br /&gt;
&lt;br /&gt;
To avoid this issue entirely, however, we have assigned unique bank account numbers to each instance of the bank account object. Thus, you will not need to worry about this edge case.&lt;br /&gt;
&lt;br /&gt;
A couple of notes and common issues:&lt;br /&gt;
&lt;br /&gt;
*You can use the implicit locks associated with the sender and recipient, but we recommend simply using intrinsic locks for this method. In other words, use &amp;lt;code&amp;gt;synchronized(sender)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;synchronized(recipient)&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Syntax for synchronized can be found on the [[Reference_Page#Synchronized|reference page]]&lt;br /&gt;
*Invoke the not-thread-safe [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/locking/core/banking/TransferUtils.html#checkBalanceAndTransfer-locking.core.banking.Account-locking.core.banking.Account-int- TransferUtils.checkBalanceAndTransfer()] method. This method will check that the sender and recipient are not the same person and that the sender has enough money in her account to send the specified amount to the recipient.&lt;br /&gt;
*Use the [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/locking/core/banking/Account.html#getUniqueIdNumber-- getUniqueIdNumber()] method to get the unique account ID of a given bank account.&lt;br /&gt;
*Your implementation will have to make use of a nested &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; blocks (one &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; call within another).&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|BankAccountLockOrdering|transferMoney|lock.order.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static TransferResult transferMoney(Account sender, Account recipient, int amount)}}&lt;br /&gt;
&lt;br /&gt;
=Not Required Problem To Contemplate=&lt;br /&gt;
How would you handle the case where every attempt to order two objects ([https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T- compareTo(other)], [https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#identityHashCode-java.lang.Object- System.identityHashCode(o)], et cetera) failed?&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Synchronize on a shared third object first for this rare case.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|LockOrderingTestSuite|lock.order.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Ordered_Locks&amp;diff=2213</id>
		<title>Ordered Locks</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Ordered_Locks&amp;diff=2213"/>
		<updated>2018-07-24T06:31:25Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [http://jcip.net/ Java Concurrency in Practice], Ben Choi, and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
X10's isolated construct provides mutual exclusion while avoiding deadlock.  We will learn how to achieve this desirable property of deadlock freedom by ordering locks.&lt;br /&gt;
&lt;br /&gt;
We will gain experience with implicit locks and the synchronized statement.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
In Java, locks are a synchronization tool that exists to ensure whatever is protected by the lock is only accessed one thread at a time, as to avoid a possible data race. We will explore the first of two different types of locks: intrinsic locks.&lt;br /&gt;
&lt;br /&gt;
Every object has an intrinsic lock associated with the object. Intrinsic locks are accessed with the &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; keyword. &lt;br /&gt;
&lt;br /&gt;
To demonstrate how to avoid both data races and deadlock issues, we will create a method designed to transfer money between two bank accounts. Two parties should be able to safely transfer money between each other without a data race (courtesy of locks) or deadlock (something you will address).&lt;br /&gt;
&lt;br /&gt;
In this studio we will use lock ordering to avoid deadlock.&lt;br /&gt;
&lt;br /&gt;
With lock ordering, we will control the order in which locks are acquired for two bank accounts using unique identifying values associated with the bank accounts. In this way, a transfer from bank account A to B paired with a simultaneous transfer from B to A will not lead to a scenario in which A is waiting for B’s lock forever while B is waiting for A’s lock forever, as both calls will always attempt to go for A’s lock before B’s or vice versa. For a general object, we might use the object’s hashcode as the unique identifying value, but for this assignment, we will use the account number associated with the bank account (which is guaranteed to be unique, unlike hashcodes).&lt;br /&gt;
&lt;br /&gt;
Refer to Oracle's official documentation regarding [https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html intrinsic locks/synchronization] for more information. Also check out the [[Reference_Page#Locks|reference page]] for help on the syntax of locks.&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
Navigate to &amp;lt;code&amp;gt;LockOrdering.java&amp;lt;/code&amp;gt;. As mentioned in the background section, we will attempt to prevent deadlock using a lock ordering algorithm of your making. Essentially, whenever an operation needs to use two separate locks, make sure that the locks are always acquired in a fixed order no matter how the operation is called. The general way to do this is to compare the identity hash codes of the two objects and enforce an order based on those values. However, this can lead to a rare issue in which the two objects are unique, but have the same hashcode. &lt;br /&gt;
&lt;br /&gt;
To avoid this issue entirely, however, we have assigned unique bank account numbers to each instance of the bank account object. Thus, you will not need to worry about this edge case.&lt;br /&gt;
&lt;br /&gt;
A couple of notes and common issues:&lt;br /&gt;
&lt;br /&gt;
*You can use the implicit locks associated with the sender and recipient, but we recommend simply using intrinsic locks for this method. In other words, use &amp;lt;code&amp;gt;synchronized(sender)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;synchronized(recipient)&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Syntax for synchronized can be found on the [[Reference_Page#Synchronized|reference page]]&lt;br /&gt;
*Invoke the not-thread-safe [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/locking/core/banking/TransferUtils.html#checkBalanceAndTransfer-locking.core.banking.Account-locking.core.banking.Account-int- TransferUtils.checkBalanceAndTransfer()] method. This method will check that the sender and recipient are not the same person and that the sender has enough money in her account to send the specified amount to the recipient.&lt;br /&gt;
*Use the [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/locking/core/banking/Account.html#getUniqueIdNumber-- getUniqueIdNumber()] method to get the unique account ID of a given bank account.&lt;br /&gt;
*Your implementation will have to make use of a nested &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; blocks (one &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; call within another).&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|BankAccountLockOrdering|transferMoney|lock.order.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static TransferResult transferMoney(Account sender, Account recipient, int amount)}}&lt;br /&gt;
&lt;br /&gt;
=Not Required Problem To Contemplate=&lt;br /&gt;
How would you handle the case where every attempt to order two objects ([https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T- compareTo(other)], [https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#identityHashCode-java.lang.Object- System.identityHashCode(o)], et cetera) failed?&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Synchronize on a shared third object first for this rare case.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|LockOrderingTestSuite|lock.order.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Ordered_Locks&amp;diff=2212</id>
		<title>Ordered Locks</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Ordered_Locks&amp;diff=2212"/>
		<updated>2018-07-24T06:23:39Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Implement */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [http://jcip.net/ Java Concurrency in Practice], Ben Choi, and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
X10's isolated construct provides mutual exclusion while avoiding deadlock.  We will learn how to achieve this desirable property of deadlock freedom by ordering locks.&lt;br /&gt;
&lt;br /&gt;
We will gain experience with implicit locks and the synchronized statement.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
In Java, locks are a synchronization tool that exists to ensure whatever is protected by the lock is only accessed one thread at a time, as to avoid a possible data race. We will explore the first of two different types of locks: intrinsic locks.&lt;br /&gt;
&lt;br /&gt;
Every object has an intrinsic lock associated with the object. Intrinsic locks are accessed with the &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; keyword. &lt;br /&gt;
&lt;br /&gt;
To demonstrate how to avoid both data races and deadlock issues, we will create a method designed to transfer money between two bank accounts. Two parties should be able to safely transfer money between each other without a data race (courtesy of locks) or deadlock (something you will address).&lt;br /&gt;
&lt;br /&gt;
In this studio we will use lock ordering to avoid deadlock.&lt;br /&gt;
&lt;br /&gt;
With lock ordering, we will control the order in which locks are acquired for two bank accounts using unique identifying values associated with the bank accounts. In this way, a transfer from bank account A to B paired with a simultaneous transfer from B to A will not lead to a scenario in which A is waiting for B’s lock forever while B is waiting for A’s lock forever, as both calls will always attempt to go for A’s lock before B’s or vice versa. For a general object, we might use the object’s hashcode as the unique identifying value, but for this assignment, we will use the account number associated with the bank account (which is guaranteed to be unique, unlike hashcodes).&lt;br /&gt;
&lt;br /&gt;
Refer to Oracle's official documentation regarding [https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html intrinsic locks/synchronization] for more information.&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
Navigate to &amp;lt;code&amp;gt;LockOrdering.java&amp;lt;/code&amp;gt;. As mentioned in the background section, we will attempt to prevent deadlock using a lock ordering algorithm of your making. Essentially, whenever an operation needs to use two separate locks, make sure that the locks are always acquired in a fixed order no matter how the operation is called. The general way to do this is to compare the identity hash codes of the two objects and enforce an order based on those values. However, this can lead to a rare issue in which the two objects are unique, but have the same hashcode. &lt;br /&gt;
&lt;br /&gt;
To avoid this issue entirely, however, we have assigned unique bank account numbers to each instance of the bank account object. Thus, you will not need to worry about this edge case.&lt;br /&gt;
&lt;br /&gt;
A couple of notes and common issues:&lt;br /&gt;
&lt;br /&gt;
*You can use the implicit locks associated with the sender and recipient, but we recommend simply using intrinsic locks for this method. In other words, use &amp;lt;code&amp;gt;synchronized(sender)&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;synchronized(recipient)&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Syntax for synchronized can be found on the [[Reference_Page#Synchronized|reference page]]&lt;br /&gt;
*Invoke the not-thread-safe [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/locking/core/banking/TransferUtils.html#checkBalanceAndTransfer-locking.core.banking.Account-locking.core.banking.Account-int- TransferUtils.checkBalanceAndTransfer()] method. This method will check that the sender and recipient are not the same person and that the sender has enough money in her account to send the specified amount to the recipient.&lt;br /&gt;
*Use the [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/locking/core/banking/Account.html#getUniqueIdNumber-- getUniqueIdNumber()] method to get the unique account ID of a given bank account.&lt;br /&gt;
*Your implementation will have to make use of a nested &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; blocks (one &amp;lt;code&amp;gt;synchronized&amp;lt;/code&amp;gt; call within another).&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|BankAccountLockOrdering|transferMoney|lock.order.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public static TransferResult transferMoney(Account sender, Account recipient, int amount)}}&lt;br /&gt;
&lt;br /&gt;
=Not Required Problem To Contemplate=&lt;br /&gt;
How would you handle the case where every attempt to order two objects ([https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T- compareTo(other)], [https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#identityHashCode-java.lang.Object- System.identityHashCode(o)], et cetera) failed?&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Synchronize on a shared third object first for this rare case.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|LockOrderingTestSuite|lock.order.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Atomicity&amp;diff=2211</id>
		<title>Atomicity</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Atomicity&amp;diff=2211"/>
		<updated>2018-07-24T06:14:12Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Many [https://en.wikipedia.org/wiki/Race_condition race conditions] can be prevented by proper encapsulation avoiding check-then-write and read-then-modify-then-write in non-[https://en.wikipedia.org/wiki/Linearizability atomically].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
Take a look at the [[Reference_Page#Synchronized|synchronized and lock sections of the reference page]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html Concurrency Tutorial]&lt;br /&gt;
: [https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html Synchronized Methods]&lt;br /&gt;
: [https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html Intrinsic Locks]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html ConcurrentMap]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html#compute-K-java.util.function.BiFunction- compute]&lt;br /&gt;
&lt;br /&gt;
=Code To Investigate=&lt;br /&gt;
{{Warning|Although the code below is technically thread-safe, it offers check-then-act usage which leads to atomicity races.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToInvestigate|CheckThenActCourse|isSpaceRemaining&amp;lt;br&amp;gt;add&amp;lt;br&amp;gt;drop|atomicity.course.studio}}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public class CheckThenActCourse {&lt;br /&gt;
	private final Collection&amp;lt;Student&amp;gt; students;&lt;br /&gt;
	private final int limit;&lt;br /&gt;
&lt;br /&gt;
	public CheckThenActCourse(int limit, Supplier&amp;lt;Collection&amp;lt;Student&amp;gt;&amp;gt; collectionSupplier) {&lt;br /&gt;
		this.students = collectionSupplier.get();&lt;br /&gt;
		this.limit = limit;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public int getLimit() {&lt;br /&gt;
		return this.limit;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public boolean isSpaceRemaining() {&lt;br /&gt;
		synchronized (this.students) {&lt;br /&gt;
			return this.students.size() &amp;lt; this.limit;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void add(Student student) {&lt;br /&gt;
		synchronized (this.students) {&lt;br /&gt;
			this.students.add(student);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public boolean drop(Student student) {&lt;br /&gt;
		synchronized (this.students) {&lt;br /&gt;
			return this.students.remove(student);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
If you can answer all these questions, this studio should be a breeze!&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
We will build a thread-safe &amp;lt;code&amp;gt;Course&amp;lt;/code&amp;gt; class with methods which do not lead clients towards atomicity races.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|Course|addIfSpace&amp;lt;br&amp;gt;drop|atomicity.course.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public boolean addIfSpace(Student student)}}&lt;br /&gt;
&lt;br /&gt;
Adds the student if there is space under the limit specified to the constructor and returns whether or not the add actually occurred.&lt;br /&gt;
&lt;br /&gt;
NOTE: Must be thread safe.&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public boolean drop(Student student)}}&lt;br /&gt;
&lt;br /&gt;
Removes the student from the course if the student was enrolled (the remove method returns just the status you need).&lt;br /&gt;
&lt;br /&gt;
NOTE: Must be thread safe.&lt;br /&gt;
&lt;br /&gt;
=Code To Fix=&lt;br /&gt;
{{Warning|Do NOT use synchronized here.  ConcurrentMaps are already thread safe.}}&lt;br /&gt;
&lt;br /&gt;
For this part of the studio we are presented with broken code.  Despite using a thread-safe concurrent map:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;private final ConcurrentMap&amp;lt;String, Integer&amp;gt; map;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it suffers from an atomicity race:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;private int transfer(String listingSymbol, int deltaShareCount) {&lt;br /&gt;
	Integer oldValue = this.map.get(listingSymbol);&lt;br /&gt;
	Integer newValue;&lt;br /&gt;
	if (oldValue != null) {&lt;br /&gt;
		newValue = oldValue + deltaShareCount;&lt;br /&gt;
	} else {&lt;br /&gt;
		newValue = deltaShareCount;&lt;br /&gt;
	}&lt;br /&gt;
	this.map.put(listingSymbol, newValue);&lt;br /&gt;
	return newValue;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Recalling the song:&lt;br /&gt;
&lt;br /&gt;
: ''get then put is not atomic&amp;lt;br&amp;gt;call [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#compute-K-java.util.function.BiFunction- compute]&amp;lt;br&amp;gt;call [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#compute-K-java.util.function.BiFunction- compute]&amp;lt;br&amp;gt;use [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]&amp;lt;br&amp;gt;use [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]&amp;lt;br&amp;gt;or say shoot!&amp;lt;br&amp;gt;or say shoot!''&lt;br /&gt;
&lt;br /&gt;
fix the code to remove the atomicity race.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|StockPortfolio|transfer|atomicity.stockportfolio.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|private int transfer(String listingSymbol, int deltaShareCount)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: do not be concerned about ConcurrentMap vs ConcurrentHashMap.  The supplier's get method will return an instance of a thread-safe map.  (It will, in fact, be an instance of ConcurrentHashMap.)&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|AtomicityTestSuite|atomicity}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Atomicity&amp;diff=2210</id>
		<title>Atomicity</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Atomicity&amp;diff=2210"/>
		<updated>2018-07-24T06:12:10Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Many [https://en.wikipedia.org/wiki/Race_condition race conditions] can be prevented by proper encapsulation avoiding check-then-write and read-then-modify-then-write in non-[https://en.wikipedia.org/wiki/Linearizability atomically].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
Take a look at the [[Reference_Page#Synchronized|synchronized and lock sections of the reference page]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html Concurrency Tutorial]&lt;br /&gt;
: [https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html Synchronized Methods]&lt;br /&gt;
: [https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html Intrinsic Locks]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html ConcurrentMap]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html#compute-K-java.util.function.BiFunction- compute]&lt;br /&gt;
&lt;br /&gt;
=Code To Investigate=&lt;br /&gt;
{{Warning|Although the code below is technically thread-safe, it offers check-then-act usage which leads to atomicity races.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToInvestigate|CheckThenActCourse|isSpaceRemaining&amp;lt;br&amp;gt;add&amp;lt;br&amp;gt;drop|atomicity.course.studio}}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public class CheckThenActCourse {&lt;br /&gt;
	private final Collection&amp;lt;Student&amp;gt; students;&lt;br /&gt;
	private final int limit;&lt;br /&gt;
&lt;br /&gt;
	public CheckThenActCourse(int limit, Supplier&amp;lt;Collection&amp;lt;Student&amp;gt;&amp;gt; collectionSupplier) {&lt;br /&gt;
		this.students = collectionSupplier.get();&lt;br /&gt;
		this.limit = limit;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public int getLimit() {&lt;br /&gt;
		return this.limit;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public boolean isSpaceRemaining() {&lt;br /&gt;
		synchronized (this.students) {&lt;br /&gt;
			return this.students.size() &amp;lt; this.limit;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void add(Student student) {&lt;br /&gt;
		synchronized (this.students) {&lt;br /&gt;
			this.students.add(student);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public boolean drop(Student student) {&lt;br /&gt;
		synchronized (this.students) {&lt;br /&gt;
			return this.students.remove(student);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
We will build a thread-safe &amp;lt;code&amp;gt;Course&amp;lt;/code&amp;gt; class with methods which do not lead clients towards atomicity races.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|Course|addIfSpace&amp;lt;br&amp;gt;drop|atomicity.course.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public boolean addIfSpace(Student student)}}&lt;br /&gt;
&lt;br /&gt;
Adds the student if there is space under the limit specified to the constructor and returns whether or not the add actually occurred.&lt;br /&gt;
&lt;br /&gt;
NOTE: Must be thread safe.&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public boolean drop(Student student)}}&lt;br /&gt;
&lt;br /&gt;
Removes the student from the course if the student was enrolled (the remove method returns just the status you need).&lt;br /&gt;
&lt;br /&gt;
NOTE: Must be thread safe.&lt;br /&gt;
&lt;br /&gt;
=Code To Fix=&lt;br /&gt;
{{Warning|Do NOT use synchronized here.  ConcurrentMaps are already thread safe.}}&lt;br /&gt;
&lt;br /&gt;
For this part of the studio we are presented with broken code.  Despite using a thread-safe concurrent map:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;private final ConcurrentMap&amp;lt;String, Integer&amp;gt; map;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
it suffers from an atomicity race:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;private int transfer(String listingSymbol, int deltaShareCount) {&lt;br /&gt;
	Integer oldValue = this.map.get(listingSymbol);&lt;br /&gt;
	Integer newValue;&lt;br /&gt;
	if (oldValue != null) {&lt;br /&gt;
		newValue = oldValue + deltaShareCount;&lt;br /&gt;
	} else {&lt;br /&gt;
		newValue = deltaShareCount;&lt;br /&gt;
	}&lt;br /&gt;
	this.map.put(listingSymbol, newValue);&lt;br /&gt;
	return newValue;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Recalling the song:&lt;br /&gt;
&lt;br /&gt;
: ''get then put is not atomic&amp;lt;br&amp;gt;call [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#compute-K-java.util.function.BiFunction- compute]&amp;lt;br&amp;gt;call [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#compute-K-java.util.function.BiFunction- compute]&amp;lt;br&amp;gt;use [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]&amp;lt;br&amp;gt;use [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]&amp;lt;br&amp;gt;or say shoot!&amp;lt;br&amp;gt;or say shoot!''&lt;br /&gt;
&lt;br /&gt;
fix the code to remove the atomicity race.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|StockPortfolio|transfer|atomicity.stockportfolio.studio}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|private int transfer(String listingSymbol, int deltaShareCount)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: do not be concerned about ConcurrentMap vs ConcurrentHashMap.  The supplier's get method will return an instance of a thread-safe map.  (It will, in fact, be an instance of ConcurrentHashMap.)&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|AtomicityTestSuite|atomicity}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=K_Mer_Counting_Assignment&amp;diff=2209</id>
		<title>K Mer Counting Assignment</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=K_Mer_Counting_Assignment&amp;diff=2209"/>
		<updated>2018-07-24T06:07:53Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: John Gibson and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
K-mer counting is a real world application which provides the opportunity to build thread safe data structures which alleviate contention.&lt;br /&gt;
&lt;br /&gt;
Pulling real data from the National Institutes of Health forces us to address balancing our work.&lt;br /&gt;
&lt;br /&gt;
Finally, k-mer counting provides opportunities for performance engineering.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
The term k-mer refers to a substring of length k and k-mer counting refers to the process of finding the number of occurrences of a k-mer in a given string. This computational problem has many real-world applications, the most notable being in the field of computational genomics. In this assignment, you will design a program that will ultimately take in a human X-chromosome and count the number of k-mers in the string of DNA. You will be making use of everything you have learned thus far, including atomic variables. It is useful to know that given a string of length n, the amount of possible k-mers is equal to '''n - k + 1'''.&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Investigate=&lt;br /&gt;
==Java Util Concurrent==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html AtomicIntegerArray].&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html ReentrantReadWriteLock]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html#readLock-- readLock]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html#writeLock-- writeLock]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html Lock]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html#lock-- lock]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html#lock-- unlock]&lt;br /&gt;
&lt;br /&gt;
==KMerUtils==&lt;br /&gt;
The following methods should be useful as you build the assignment.&lt;br /&gt;
&lt;br /&gt;
Check out the Javadocs either [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/kmer/core/KMerUtils.html on the web], or in the comments in KMerUtils.java for further details on how they work.&lt;br /&gt;
&lt;br /&gt;
===long calculatePossibleKMers(int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static long calculatePossibleKMers(int kMerLength) {&lt;br /&gt;
	int bitsPerBase = 2;&lt;br /&gt;
	int bitsPerKMer = kMerLength * bitsPerBase;&lt;br /&gt;
	long possibleKMers = 1L &amp;lt;&amp;lt; bitsPerKMer;&lt;br /&gt;
	return possibleKMers;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===int toArrayLength(long possibleKMers)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static int toArrayLength(long possibleKMers) {&lt;br /&gt;
	// maximum array length is VM dependent, but must be indexed by an int.&lt;br /&gt;
	// reportedly some vms reserve some header words (see ArrayList) which puts its&lt;br /&gt;
	// limit as just below 2^31.&lt;br /&gt;
	// we will choose 2^30 (inclusive) as the maximum since it will hold the largest&lt;br /&gt;
	// potential k-mer (4^15)&lt;br /&gt;
	final long MAX_K_MER_ARRAY_LENGTH_INCLUSIVE = 1 &amp;lt;&amp;lt; 30;&lt;br /&gt;
	if (possibleKMers &amp;lt;= MAX_K_MER_ARRAY_LENGTH_INCLUSIVE) {&lt;br /&gt;
		return (int) possibleKMers;&lt;br /&gt;
	} else {&lt;br /&gt;
		throw new IllegalArgumentException(possibleKMers + &amp;quot; &amp;gt; &amp;quot; + MAX_K_MER_ARRAY_LENGTH_INCLUSIVE);&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===int calculateSumOfAllKMers(List&amp;lt;byte[]&amp;gt; sequences, int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static int calculateSumOfAllKMers(List&amp;lt;byte[]&amp;gt; sequences, int kMerLength) {&lt;br /&gt;
	int sum = 0;&lt;br /&gt;
	for (byte[] sequence : sequences) {&lt;br /&gt;
		int i = (sequence.length - kMerLength + 1);&lt;br /&gt;
		if( i &amp;gt; 0 ) {&lt;br /&gt;
			sum += i;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return sum;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===String toString(byte[] sequence, int offset, int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static String toString(byte[] sequence, int offset, int kMerLength) {&lt;br /&gt;
	return new String(sequence, offset, kMerLength, StandardCharsets.UTF_8);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===String toString(byte[] kMer)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static String toString(byte[] kMer) {&lt;br /&gt;
	return new String(kMer, StandardCharsets.UTF_8);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===int toPackedInt(byte[] sequence, int offset, int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static int toPackedInt(byte[] sequence, int offset, int kMerLength) {&lt;br /&gt;
	int result = 0;&lt;br /&gt;
	for (int i = 0; i &amp;lt; kMerLength; i++) {&lt;br /&gt;
		switch (sequence[offset + i]) {&lt;br /&gt;
		// case A:&lt;br /&gt;
		// result |= (A_MASK_INT &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
		// break;&lt;br /&gt;
		case T:&lt;br /&gt;
			result |= (T_MASK_INT &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
			break;&lt;br /&gt;
		case C:&lt;br /&gt;
			result |= (C_MASK_INT &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
			break;&lt;br /&gt;
		case G:&lt;br /&gt;
			result |= (G_MASK_INT &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
			break;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return result;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===int toPackedInt(byte[] kMer)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static int toPackedInt(byte[] kMer) {&lt;br /&gt;
	return toPackedInt(kMer, 0, kMer.length);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===byte[] unpackInt(int kMer, int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static byte[] unpackInt(int kMer, int kMerLength) {&lt;br /&gt;
	byte[] result = new byte[kMerLength];&lt;br /&gt;
&lt;br /&gt;
	for (int i = 0; i &amp;lt; kMerLength; i++) {&lt;br /&gt;
		int v = (kMer &amp;gt;&amp;gt; (i + i)) &amp;amp; 0x3;&lt;br /&gt;
		switch (v) {&lt;br /&gt;
		case A_MASK_INT:&lt;br /&gt;
			result[i] = A;&lt;br /&gt;
			break;&lt;br /&gt;
		case T_MASK_INT:&lt;br /&gt;
			result[i] = T;&lt;br /&gt;
			break;&lt;br /&gt;
		case C_MASK_INT:&lt;br /&gt;
			result[i] = C;&lt;br /&gt;
			break;&lt;br /&gt;
		case G_MASK_INT:&lt;br /&gt;
			result[i] = G;&lt;br /&gt;
			break;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return result;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===long toPackedLong(byte[] sequence, int offset, int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static long toPackedLong(byte[] sequence, int offset, int kMerLength) {&lt;br /&gt;
	long result = 0;&lt;br /&gt;
	for (int i = 0; i &amp;lt; kMerLength; i++) {&lt;br /&gt;
		switch (sequence[offset + i]) {&lt;br /&gt;
		// case A:&lt;br /&gt;
		// result |= (A_MASK_LONG &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
		// break;&lt;br /&gt;
		case T:&lt;br /&gt;
			result |= (T_MASK_LONG &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
			break;&lt;br /&gt;
		case C:&lt;br /&gt;
			result |= (C_MASK_LONG &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
			break;&lt;br /&gt;
		case G:&lt;br /&gt;
			result |= (G_MASK_LONG &amp;lt;&amp;lt; (i + i));&lt;br /&gt;
			break;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return result;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===long toPackedLong(byte[] sequence)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static long toPackedLong(byte[] sequence) {&lt;br /&gt;
	return toPackedLong(sequence, 0, sequence.length);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===byte[] unpackLong(long kMer, int kMerLength)===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static byte[] unpackLong(long kMer, int kMerLength) {&lt;br /&gt;
	byte[] result = new byte[kMerLength];&lt;br /&gt;
&lt;br /&gt;
	for (int i = 0; i &amp;lt; kMerLength; i++) {&lt;br /&gt;
		long v = (kMer &amp;gt;&amp;gt; (i + i)) &amp;amp; 0x3;&lt;br /&gt;
		switch ((int) v) {&lt;br /&gt;
		case A_MASK_INT:&lt;br /&gt;
			result[i] = A;&lt;br /&gt;
			break;&lt;br /&gt;
		case T_MASK_INT:&lt;br /&gt;
			result[i] = T;&lt;br /&gt;
			break;&lt;br /&gt;
		case C_MASK_INT:&lt;br /&gt;
			result[i] = C;&lt;br /&gt;
			break;&lt;br /&gt;
		case G_MASK_INT:&lt;br /&gt;
			result[i] = G;&lt;br /&gt;
			break;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	return result;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==KMerCounts==&lt;br /&gt;
===MapKMerCount===&lt;br /&gt;
In order to provide a KMerCount that works with different k-mer type representations we have added an interface KMerCodec which provides functions to go to an from the byte[] representation:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public interface KMerCodec&amp;lt;T&amp;gt; {&lt;br /&gt;
	BiFunction&amp;lt;T, Integer, byte[]&amp;gt; decoder();&lt;br /&gt;
&lt;br /&gt;
	Function&amp;lt;byte[], T&amp;gt; encoder();&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As an example the instance for long -&amp;gt; byte[] and back simply utilizes the pack and unpack methods in KMerUtils:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public enum LongKMerCodec implements KMerCodec&amp;lt;Long&amp;gt; {&lt;br /&gt;
	INSTANCE;&lt;br /&gt;
&lt;br /&gt;
	@Override&lt;br /&gt;
	public Function&amp;lt;byte[], Long&amp;gt; encoder() {&lt;br /&gt;
		return KMerUtils::toPackedLong;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	@Override&lt;br /&gt;
	public BiFunction&amp;lt;Long, Integer, byte[]&amp;gt; decoder() {&lt;br /&gt;
		return KMerUtils::unpackLong;&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Creating an instance of a MapKMerCount to return from your KMerCounters will need to use the appropriate codec.  For example, if you have a map of type &amp;lt;code&amp;gt;Map&amp;lt;Long, Integer&amp;gt;&amp;lt;/code&amp;gt; which you wish to wrap and return, your code would look something like this:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;return new MapKMerCount&amp;lt;&amp;gt;(k, map, LongKMerCodec.INSTANCE);&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===IntArrayKMerCount===&lt;br /&gt;
===AtomicIntegerArrayKMerCount===&lt;br /&gt;
&lt;br /&gt;
=Warmups=&lt;br /&gt;
&lt;br /&gt;
The warm-ups associated with this assignment can be found under the &amp;lt;code&amp;gt;kmer.warmup&amp;lt;/code&amp;gt; packages.&lt;br /&gt;
&lt;br /&gt;
==String HashMap Implementation==&lt;br /&gt;
{{CodeToImplement|StringHashMapKMerCounter|parse|kmer.warmup.stringmap}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
In this completely sequential implementation, you will have to write the parse method. The method takes in a list of arrays of bytes and a k-mer length. It should return an instance of MapKMerCount(which takes in a map), a class provided to you which does exactly what its name suggests. In order to implement this method, we recommend taking a look at the KMerUtils class and more specifically the toString method, which converts a given byte array into a String in order to make it compatible with the String HashMap.&lt;br /&gt;
&lt;br /&gt;
parse should go through the amount of possible k-mers for every byte array in the list of sequences. As it goes through the bytes in the array, use the KMerUtils.toString() method to create a string to use for the HashMap. The map should take in a String as the key and an Integer as the value. We recommend using the map.compute() method and reviewing how to use lambdas.&lt;br /&gt;
&lt;br /&gt;
==String ConcurrentHashMap Implementation==&lt;br /&gt;
{{CodeToImplement|StringConcurrentHashMapKMerCounter|parse|kmer.warmup.stringmap}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
This implementation will make your sequential String HashMap implementation into a parallel one. To do so, you will be making use of Java’s atomic version of a HashMap: a ConcurrentHashMap. Like before, you will be need to complete the parse method. You can choose to finish this method with a forall loop or a finish/async approach, which is completely up to you.&lt;br /&gt;
&lt;br /&gt;
==ByteArrayRange Implementation==&lt;br /&gt;
{{CodeToImplement|ByteArrayRangeConcurrentHashMapKMerCounter|parse|kmer.warmup.bytearrayrangemap}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
This parallel implementation will overlap greatly with your previous two implementations, but it will use ByteArrayRange instead of Strings. Refer to the ByteArrayRange class in order to get a better idea of how to implement this method and instantiate an instance of the class. The class closely resembles the Slice class you worked on earlier in the semester.&lt;br /&gt;
&lt;br /&gt;
=Lab=&lt;br /&gt;
{{ tip | Get ThresholdSlices working and then use it to balance all of your parallel KMerCounter implementations. }}&lt;br /&gt;
==ThresholdSlices==&lt;br /&gt;
===slicing===&lt;br /&gt;
{{CodeToImplement|ThresholdSlices|addToCollectionKernel&amp;lt;br&amp;gt;createSlicesBelowThreshold&amp;lt;br&amp;gt;calculateReasonableThreshold|kmer.lab.util}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void addToCollectionKernel(Collection&amp;lt;Slice&amp;lt;byte[]&amp;gt;&amp;gt; slices, byte[] sequence, int min, int max, int sliceThreshold)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static List&amp;lt;Slice&amp;lt;byte[]&amp;gt;&amp;gt; createSlicesBelowThreshold(List&amp;lt;byte[]&amp;gt; sequences, int k, int sliceThreshold)}}&lt;br /&gt;
&lt;br /&gt;
This class is designed to take in a list of bytes and convert it into a list of slices. The slice class should be familiar to you from earlier in the semester, but feel free to refer back to the documentation on [[Slices]] for a quick recap. You should perform this task recursively and there are two methods you will need to implement. The createSlicesBelowThreshold method should call the addToCollectionKernel once, but the kernel should take over the recursion from there.&lt;br /&gt;
&lt;br /&gt;
In the createSlicesBelowThreshold method, you should call the recursive kernel for each sequence in the list of sequences. When defining the min and max values, keep the information mentioned in the &amp;quot;Background&amp;quot; section in mind. As for the kernel, it should add a new slice to the collection of slices once the length of the slice dips below the provided threshold, but it should otherwise split itself into two smaller slices using recursion.&lt;br /&gt;
&lt;br /&gt;
In our previous uses of Slices we leveraged sliceIndexId (and not originalData) since it was a n-way split/coarsening scenario.  Here we are recursively splitting each item in a collection of sub-sequences so originalData will be used (and sliceIndexId is unnecessary and can be specified as invalid (-1))..&lt;br /&gt;
&lt;br /&gt;
{{warning | be sure to slice the offset (a.k.a. startingIndex) space}}&lt;br /&gt;
&lt;br /&gt;
for N=10 and K=3, you should be slicing like this:&lt;br /&gt;
&lt;br /&gt;
[[File:ThresholdSlices.svg|320px]]&lt;br /&gt;
&lt;br /&gt;
===threshold calculation===&lt;br /&gt;
{{Sequential|public static int calculateReasonableThreshold(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
Question to ask yourself: given a list of sequences which are to be k-mer counted, how would you calculate a reasonable threshold?&lt;br /&gt;
&lt;br /&gt;
==LongConcurrentHashMapKMerCounter==&lt;br /&gt;
{{CodeToImplement|LongConcurrentHashMapKMerCounter|parse|kmer.lab.longconcurrenthashmap}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
This parallel implementation will also overlap greatly with everything you have done previously, but instead of using Strings or SequenceSlice, we will be using Longs to represent DNA data. In order to do this, refer to the KMerUtils class, more specifically the toPackedLong method which will convert a sequence of bytes into a Long for our purposes. As the data that this implementation can take is much larger than the previous implementations, consider how to instantiate the ConcurrentHashMap in order to avoid dynamically resizing the map. KMerUtils has a method which will calculate this number for you, but think about which one to use, why you would use it, and how that would differ from simply calculating n - k + 1 yourself.&lt;br /&gt;
&lt;br /&gt;
Hint: calculatePossibleKmers and calculateSumOfAllKmers are distinct and take different input parameters. calculateSumOfAllKmers performs the n - k + 1 calculation on a list of arrays of sequences and sums the total. calculatePossibleKmers only takes the length of the k-mer (k) as the input parameter, meaning it will calculate possibilities independent of the size of the sequence. Thus, the n - k + 1 calculation would yield a value ranging from 0 (inclusive) to the result of calculatePossibleKmers (exclusive).&lt;br /&gt;
&lt;br /&gt;
==IntArrayKMerCounter==&lt;br /&gt;
{{CodeToImplement|IntArrayKMerCounter|parse|kmer.lab.intarray}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
Like the String HashMap implementation, this implementation should be completed sequentially. However, unlike the previous implementations, we will be using an array instead of a map. This means that you must keep in mind what size to make the array in order to instantiate it. KMerUtils has a method which will calculate this number for you, but think about which one to use, why you would use it, and how that would differ from simply calculating n - k + 1 yourself. Think of using the int array as similar to using the map, but with ints as the key/value pairs. Use KMerUtils.toPackedInt() in order to convert the sequence into an int for our purposes.&lt;br /&gt;
&lt;br /&gt;
Hint: calculatePossibleKmers and calculateSumOfAllKmers are distinct and take different input parameters. calculateSumOfAllKmers performs the n - k + 1 calculation on a list of arrays of sequences and sums the total. calculatePossibleKmers only takes the length of the k-mer (k) as the input parameter, meaning it will calculate possibilities independent of the size of the sequence. Thus, the n - k + 1 calculation would yield a value ranging from 0 (inclusive) to the result of calculatePossibleKmers (exclusive).&lt;br /&gt;
&lt;br /&gt;
==AtomicIntegerArrayKMerCounter==&lt;br /&gt;
{{CodeToImplement|AtomicIntegerArrayKMerCounter|parse|kmer.lab.atomicintegerarray}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
This implementation is simply the parallel equivalent of the int array implementation. To do so, you will be making use of Java’s atomic version of an array: an AtomicIntegerArray. Like before, you will be need to complete the parse method. You can choose to finish this method with a forall loop or a finish/async approach, which is completely up to you.&lt;br /&gt;
&lt;br /&gt;
==ConcurrentBucketHashMapKMerCounter==&lt;br /&gt;
{{CodeToImplement|ConcurrentBucketHashMapKMerCounter|parse|kmer.lab.concurrentbuckethashmap}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public KMerCount parse(List&amp;lt;byte[]&amp;gt; sequences, int k)}}&lt;br /&gt;
&lt;br /&gt;
This parallel implementation will go a step beyond the previous implementations and divide entries into 1024 buckets. Although a different number of buckets can be used, we will simply stick to 1024. Every time an entry is added to the bucket dictionary, it will create a hash based on the entry's key and place the entry into one of the 1024 buckets. Because we would only need to search one bucket for an entry based on a key's hash, this mainly serves the purpose of cutting down on search time. The compute method of the ConcurrentBucketHashMap should automatically compute the correct bucket for the entry, so this implementation should closely resemble the previous ConcurrentHashMap implementations. When instantiating the ConcurrentBucketHashMap, we recommend making the key/value pairs a Long and an Integer.&lt;br /&gt;
&lt;br /&gt;
===ConcurrentBucketHashMap===&lt;br /&gt;
{{CodeToImplement|ConcurrentBucketHashMap|constructor&amp;lt;br&amp;gt;getIndex&amp;lt;br&amp;gt;getBucket&amp;lt;br&amp;gt;getLock&amp;lt;br&amp;gt;getEntry&amp;lt;br&amp;gt;get&amp;lt;br&amp;gt;put&amp;lt;br&amp;gt;compute|kmer.lab.concurrentbuckethashmap}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public ConcurrentBucketHashMap(int bucketCount)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private int getIndex(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|Math.abs(Integer.MIN_VALUE) is negative.}}&lt;br /&gt;
&lt;br /&gt;
{{Tip|Use [https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int- floorMod]}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private List&amp;lt;Entry&amp;lt;K, V&amp;gt;&amp;gt; getBucket(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private ReadWriteLock getLock(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static &amp;lt;K, V&amp;gt; Entry&amp;lt;K, V&amp;gt; getEntry(List&amp;lt;Entry&amp;lt;K, V&amp;gt;&amp;gt; bucket, Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public V get(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public V put(K key, V value)}}&lt;br /&gt;
&lt;br /&gt;
{{ThreadSafe|public V compute(K key, BiFunction&amp;lt;? super K, ? super V, ? extends V&amp;gt; remappingFunction)}}&lt;br /&gt;
&lt;br /&gt;
{{ warning | Do '''NOT''' call get() from compute().  It will result in a nonintuitive error.  getEntry(bucket, key) gives you everything you need. }}&lt;br /&gt;
&lt;br /&gt;
{{ tip | Be sure to make your ConcurrentBucketHashMap thread-safe.  If any code is going to access shared mutable data, it needs to do so in a thread-safe manner. }}&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
A simple example of how to use the many incantations of isolated:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;@ThreadSafe&lt;br /&gt;
public class IsolatedInteger {&lt;br /&gt;
    private int value;&lt;br /&gt;
&lt;br /&gt;
    public IsolatedInteger(int value) {&lt;br /&gt;
        this.value = value;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public int getValue() {&lt;br /&gt;
        return isolatedWithReturn(objectBased(readMode(this)), () -&amp;gt; {&lt;br /&gt;
            return value;&lt;br /&gt;
        });&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void increment() {&lt;br /&gt;
        isolated(objectBased(this), () -&amp;gt; {&lt;br /&gt;
            value++;&lt;br /&gt;
        });&lt;br /&gt;
    }&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=Extra Credit=&lt;br /&gt;
==Open-ended K-mer Counter==&lt;br /&gt;
&lt;br /&gt;
This implementation is worth up to 4.5 extra credit points.&lt;br /&gt;
&lt;br /&gt;
It is intended as an opportunity to build a high-performing, thread-safe data structure.&lt;br /&gt;
&lt;br /&gt;
One possible path was outlined at a high level in class.  However, students are encouraged to think of alternate solutions.&lt;br /&gt;
&lt;br /&gt;
We have explicitly disallowed implementations akin to our matrix map reduce assignment, since we have already done the &amp;quot;give everyone their own data and combine in post&amp;quot; pattern to death.&lt;br /&gt;
&lt;br /&gt;
Partial credit is possible for solutions which demonstrate significant ingenuity.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
* Correct ThresholdSlices (10)&lt;br /&gt;
* Correct Long ConcurrentHashMap (15)&lt;br /&gt;
* Correct Int Array (15)&lt;br /&gt;
* Correct AtomicIntegerArray (15)&lt;br /&gt;
* Correct ConcurrentBucketHashMapCounter (10)&lt;br /&gt;
* Correct ConcurrentBucketHashMap implementation (25)&lt;br /&gt;
* Clarity and efficiency (10)&lt;br /&gt;
&lt;br /&gt;
=Research=&lt;br /&gt;
[https://en.wikipedia.org/wiki/K-mer wikipedia article on k-mers]&lt;br /&gt;
&lt;br /&gt;
paper: [https://academic.oup.com/bioinformatics/article-lookup/doi/10.1093/bioinformatics/btr011 A fast, lock-free approach for efficient parallel counting of occurrences of k-mers] (Jellyfish)&lt;br /&gt;
&lt;br /&gt;
paper: [https://peerj.com/articles/cs-94/ Multiple comparative metagenomics using multiset k-mer counting]&lt;br /&gt;
&lt;br /&gt;
[http://homolog.us/Tutorials/index.php?p=3.7&amp;amp;s=2 Collection of approaches to k-mer counting]&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform Burrows–Wheeler transform]&lt;br /&gt;
&lt;br /&gt;
[http://biology.stackexchange.com/questions/45016/what-is-the-biological-significance-of-k-mer-counting Significance of k-mer Counting]&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Scan&amp;diff=2208</id>
		<title>Scan</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Scan&amp;diff=2208"/>
		<updated>2018-07-24T05:57:37Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Scan, also known as parallel prefix, is a fundamental and useful operation in parallel programming.  We will gain experience in building Hillis &amp;amp; Steele scan with an optional work efficient Blellock scan.  &lt;br /&gt;
&lt;br /&gt;
Further, the dependencies in scan:&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;y_i = y_{i-1} + x_i&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
make it seem to have little hope for parallelism.  However, simple yet clever approaches can achieve &amp;lt;math&amp;gt;\log n&amp;lt;/math&amp;gt; critical path lengths.&lt;br /&gt;
&lt;br /&gt;
While we will simply implement prefix sum, scan can be used for other associative operations.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[https://en.wikipedia.org/wiki/Prefix_sum Prefix Sum]&lt;br /&gt;
&lt;br /&gt;
==Hillis-Steele Prefix Sum==&lt;br /&gt;
[https://en.wikipedia.org/wiki/Prefix_sum#Algorithm_1:_Shorter_span,_more_parallel Hillis and Steele Algorithm]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;RdfmxfZBHpo&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Hillis-Steele_Prefix_Sum.svg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==(Optional) Work-efficient Blelloch Scan==&lt;br /&gt;
[https://en.wikipedia.org/wiki/Prefix_sum#Algorithm_2:_Work-efficient Blelloch Algorithm]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;mmYv3Haj6uc&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Prefix sum 16.svg]]&lt;br /&gt;
&lt;br /&gt;
=Code To Investigate=&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/scan/core/ArraysHolder.html ArraysHolder]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/scan/core/ArraysHolder.html#getSrc-- getSrc()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/scan/core/ArraysHolder.html#getDst-- getDst()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/scan/core/ArraysHolder.html#nextSrcAndDst-- nextSrcAndDst()]&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/scan/core/PowersOfTwoLessThan.html PowersOfTwoLessThan] implements [https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html Iterable&amp;lt;Integer&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Sequential Scan==&lt;br /&gt;
{{CodeToImplement|SequentialScan|sumScan|scan.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int[] sumScan(int[] data)}}&lt;br /&gt;
&lt;br /&gt;
==Default Arrays Holder==&lt;br /&gt;
One of the downsides to parallel scan requires memory.  For our scans we add the additional requirement that we will not mutate the incoming array parameter.  We could create log(n) arrays, one for each level but that would be wasteful.  If we create two array buffers and switch which is the source to read from and which is the destination to write from at each power of two level of the scan, we should be good to go.&lt;br /&gt;
&lt;br /&gt;
The table below shows which array will be passed back for each offset if &amp;lt;code&amp;gt;nextSrcAndDst&amp;lt;/code&amp;gt; used appropriately from a parallel scan.&lt;br /&gt;
{|class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! ||1|||2||4||8||16&lt;br /&gt;
|-&lt;br /&gt;
|'''src:'''||data||a||b||a||b&lt;br /&gt;
|-&lt;br /&gt;
|'''dst:'''||a||b||a||b||a&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''NOTE:''' think about which array is the correct one to return from your scan method given how you write your code.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultArraysHolder|getSrc&amp;lt;br&amp;gt;getDst&amp;lt;br&amp;gt;nextSrcAndDst&amp;lt;br&amp;gt;size|scan.studio}}&lt;br /&gt;
&lt;br /&gt;
==Hillis and Steele Parallel Scan==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelScan|sumScan|scan.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public int[] sumScan(int[] data)}}&lt;br /&gt;
&lt;br /&gt;
==(Optional) Blelloch Work Efficient Scan==&lt;br /&gt;
{{CodeToImplement|WorkEfficientScan|sumScan|scan.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public int[] sumScan(int[] data)}}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
===Required===&lt;br /&gt;
{{TestSuite|ScanTestSuite|scan.studio}}&lt;br /&gt;
===Optional Work Efficient===&lt;br /&gt;
{{TestSuite|WorkEfficientScanTestSuite|scan.challenge}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2207</id>
		<title>Iced Cakes Pipeline</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2207"/>
		<updated>2018-07-24T05:53:00Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Pipelines can increase throughput when processing a stream of data.  We will gain additional experience with Phasers by building a software pipeline.&lt;br /&gt;
&lt;br /&gt;
=Backgroud=&lt;br /&gt;
&amp;lt;youtube&amp;gt;3cqVtc2rDlg&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Cakes==&lt;br /&gt;
class Mixer&lt;br /&gt;
:mix(int cakeIndex)&lt;br /&gt;
class Baker&lt;br /&gt;
:bake(int cakeIndex, MixedIngredients mixedIngredients)&lt;br /&gt;
:inUse()&lt;br /&gt;
:numberAlreadyBaked()&lt;br /&gt;
class Icer&lt;br /&gt;
:ice(int cakeIndex, BakedCake bakedCake)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[[Reference_Page#Parallel_Loops|Our reference page's parallel loop section]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[[Reference_Page#Phasers|Our reference page's phasers section]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
Here are some other questions that will help lead you down the right road.&lt;br /&gt;
*What work does each task need to do?&lt;br /&gt;
*What, if anything, does each task depend upon?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Required Code==&lt;br /&gt;
{{CodeToImplement|CakePipeline|mixBakeAndIceCakes|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
Design a simple pipeline using Phasers. In order to have a finished cake, you need to first mix the ingredients, then bake the cake, and finally ice it with frosting. Although you only have one tool for each step (one whisk, one oven, and one icing spatula), there's no problem with icing one cake while another is baking in the oven. That's where the parallelism comes in. Answering the above questions should give you all the information you need to set up this method. Remember that this needs to be able work for any number of cakes passed through! &lt;br /&gt;
&lt;br /&gt;
Note that icer.ice() returns an object of IcedCake. Collect all the 'IcedCake's you make, and return them in an array.&lt;br /&gt;
&lt;br /&gt;
==Optional Challenge==&lt;br /&gt;
{{CodeToImplement|TwoOvenPipeline|mixBakeAndIceCakes|pipeline.cake.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker1, Baker baker2, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
As we've discussed in class, not all steps of the pipeline always take the same amount of time to complete. In this example, baking a cake in the oven usually takes much longer than simply mixing the ingredients or icing the cake. The Baker is the bottleneck on the performance of this pipeline. One way to further improve the process then is to simply add another oven. This time, build a similar pipeline to what you made earlier, but use both of the Bakers passed to you in order to speed things up. Here's a couple things to take note of:&lt;br /&gt;
*How have the tasks changed? How does this additional oven affect the number of threads your program will use?&lt;br /&gt;
*Assume that the only way to get a second oven is to buy an old, used one. It can't get as hot, so it will need more time to bake a cake. Because of this, it is better to set up your solution such that when a set of ingredients has been mixed, it sends them to any open oven, rather than just alternating between the two ovens.&lt;br /&gt;
*Make sure that only one of the two ovens bakes any given cake. Use baker.inUse() and baker.numberAlreadyBaked() to help keep track of which oven has done which cakes.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|CakePipelineVizApp|pipeline.cake.viz}}&lt;br /&gt;
&lt;br /&gt;
[[File:CakePipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
The viz below is for the challenge assignment.&lt;br /&gt;
&lt;br /&gt;
[[File:TwoOvenPipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|CakePipelineTestSuite|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2206</id>
		<title>Iced Cakes Pipeline</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2206"/>
		<updated>2018-07-24T05:49:17Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Phasers */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Pipelines can increase throughput when processing a stream of data.  We will gain additional experience with Phasers by building a software pipeline.&lt;br /&gt;
&lt;br /&gt;
=Backgroud=&lt;br /&gt;
&amp;lt;youtube&amp;gt;3cqVtc2rDlg&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Cakes==&lt;br /&gt;
class Mixer&lt;br /&gt;
:mix(int cakeIndex)&lt;br /&gt;
class Baker&lt;br /&gt;
:bake(int cakeIndex, MixedIngredients mixedIngredients)&lt;br /&gt;
:inUse()&lt;br /&gt;
:numberAlreadyBaked()&lt;br /&gt;
class Icer&lt;br /&gt;
:ice(int cakeIndex, BakedCake bakedCake)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[[Reference_Page#Parallel_Loops|Our reference page's parallel loop section]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[[Reference_Page#Phasers|Our reference page's phasers section]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Questions To Ask Yourself=&lt;br /&gt;
# What are my tasks?&lt;br /&gt;
# What work does each task need to do?&lt;br /&gt;
# What, if anything, does each task depend upon?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Required Code==&lt;br /&gt;
{{CodeToImplement|CakePipeline|mixBakeAndIceCakes|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
Design a simple pipeline using Phasers. In order to have a finished cake, you need to first mix the ingredients, then bake the cake, and finally ice it with frosting. Although you only have one tool for each step (one whisk, one oven, and one icing spatula), there's no problem with icing one cake while another is baking in the oven. That's where the parallelism comes in. Answering the above questions should give you all the information you need to set up this method. Remember that this needs to be able work for any number of cakes passed through! &lt;br /&gt;
&lt;br /&gt;
Note that icer.ice() returns an object of IcedCake. Collect all the 'IcedCake's you make, and return them in an array.&lt;br /&gt;
&lt;br /&gt;
==Optional Challenge==&lt;br /&gt;
{{CodeToImplement|TwoOvenPipeline|mixBakeAndIceCakes|pipeline.cake.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker1, Baker baker2, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
As we've discussed in class, not all steps of the pipeline always take the same amount of time to complete. In this example, baking a cake in the oven usually takes much longer than simply mixing the ingredients or icing the cake. The Baker is the bottleneck on the performance of this pipeline. One way to further improve the process then is to simply add another oven. This time, build a similar pipeline to what you made earlier, but use both of the Bakers passed to you in order to speed things up. Here's a couple things to take note of:&lt;br /&gt;
*How have the tasks changed? How does this additional oven affect the number of threads your program will use?&lt;br /&gt;
*Assume that the only way to get a second oven is to buy an old, used one. It can't get as hot, so it will need more time to bake a cake. Because of this, it is better to set up your solution such that when a set of ingredients has been mixed, it sends them to any open oven, rather than just alternating between the two ovens.&lt;br /&gt;
*Make sure that only one of the two ovens bakes any given cake. Use baker.inUse() and baker.numberAlreadyBaked() to help keep track of which oven has done which cakes.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|CakePipelineVizApp|pipeline.cake.viz}}&lt;br /&gt;
&lt;br /&gt;
[[File:CakePipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
The viz below is for the challenge assignment.&lt;br /&gt;
&lt;br /&gt;
[[File:TwoOvenPipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|CakePipelineTestSuite|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2205</id>
		<title>Iced Cakes Pipeline</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2205"/>
		<updated>2018-07-24T05:49:02Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Looping */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Pipelines can increase throughput when processing a stream of data.  We will gain additional experience with Phasers by building a software pipeline.&lt;br /&gt;
&lt;br /&gt;
=Backgroud=&lt;br /&gt;
&amp;lt;youtube&amp;gt;3cqVtc2rDlg&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Cakes==&lt;br /&gt;
class Mixer&lt;br /&gt;
:mix(int cakeIndex)&lt;br /&gt;
class Baker&lt;br /&gt;
:bake(int cakeIndex, MixedIngredients mixedIngredients)&lt;br /&gt;
:inUse()&lt;br /&gt;
:numberAlreadyBaked()&lt;br /&gt;
class Icer&lt;br /&gt;
:ice(int cakeIndex, BakedCake bakedCake)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[[Reference_Page#Parallel_Loops|Our reference page's parallel loop section]]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[[Reference_Page#Phasers|Our reference page's phasers section]]&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Questions To Ask Yourself=&lt;br /&gt;
# What are my tasks?&lt;br /&gt;
# What work does each task need to do?&lt;br /&gt;
# What, if anything, does each task depend upon?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Required Code==&lt;br /&gt;
{{CodeToImplement|CakePipeline|mixBakeAndIceCakes|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
Design a simple pipeline using Phasers. In order to have a finished cake, you need to first mix the ingredients, then bake the cake, and finally ice it with frosting. Although you only have one tool for each step (one whisk, one oven, and one icing spatula), there's no problem with icing one cake while another is baking in the oven. That's where the parallelism comes in. Answering the above questions should give you all the information you need to set up this method. Remember that this needs to be able work for any number of cakes passed through! &lt;br /&gt;
&lt;br /&gt;
Note that icer.ice() returns an object of IcedCake. Collect all the 'IcedCake's you make, and return them in an array.&lt;br /&gt;
&lt;br /&gt;
==Optional Challenge==&lt;br /&gt;
{{CodeToImplement|TwoOvenPipeline|mixBakeAndIceCakes|pipeline.cake.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker1, Baker baker2, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
As we've discussed in class, not all steps of the pipeline always take the same amount of time to complete. In this example, baking a cake in the oven usually takes much longer than simply mixing the ingredients or icing the cake. The Baker is the bottleneck on the performance of this pipeline. One way to further improve the process then is to simply add another oven. This time, build a similar pipeline to what you made earlier, but use both of the Bakers passed to you in order to speed things up. Here's a couple things to take note of:&lt;br /&gt;
*How have the tasks changed? How does this additional oven affect the number of threads your program will use?&lt;br /&gt;
*Assume that the only way to get a second oven is to buy an old, used one. It can't get as hot, so it will need more time to bake a cake. Because of this, it is better to set up your solution such that when a set of ingredients has been mixed, it sends them to any open oven, rather than just alternating between the two ovens.&lt;br /&gt;
*Make sure that only one of the two ovens bakes any given cake. Use baker.inUse() and baker.numberAlreadyBaked() to help keep track of which oven has done which cakes.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|CakePipelineVizApp|pipeline.cake.viz}}&lt;br /&gt;
&lt;br /&gt;
[[File:CakePipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
The viz below is for the challenge assignment.&lt;br /&gt;
&lt;br /&gt;
[[File:TwoOvenPipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|CakePipelineTestSuite|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2204</id>
		<title>Iced Cakes Pipeline</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2204"/>
		<updated>2018-07-24T05:48:38Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Use */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Pipelines can increase throughput when processing a stream of data.  We will gain additional experience with Phasers by building a software pipeline.&lt;br /&gt;
&lt;br /&gt;
=Backgroud=&lt;br /&gt;
&amp;lt;youtube&amp;gt;3cqVtc2rDlg&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Cakes==&lt;br /&gt;
class Mixer&lt;br /&gt;
:mix(int cakeIndex)&lt;br /&gt;
class Baker&lt;br /&gt;
:bake(int cakeIndex, MixedIngredients mixedIngredients)&lt;br /&gt;
:inUse()&lt;br /&gt;
:numberAlreadyBaked()&lt;br /&gt;
class Icer&lt;br /&gt;
:ice(int cakeIndex, BakedCake bakedCake)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[[Reference_Page#Parallel_Loops|Our reference page's parallel loop section]]&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[[Reference_Page#Phasers|Our reference page's phasers section]]&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Questions To Ask Yourself=&lt;br /&gt;
# What are my tasks?&lt;br /&gt;
# What work does each task need to do?&lt;br /&gt;
# What, if anything, does each task depend upon?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Required Code==&lt;br /&gt;
{{CodeToImplement|CakePipeline|mixBakeAndIceCakes|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
Design a simple pipeline using Phasers. In order to have a finished cake, you need to first mix the ingredients, then bake the cake, and finally ice it with frosting. Although you only have one tool for each step (one whisk, one oven, and one icing spatula), there's no problem with icing one cake while another is baking in the oven. That's where the parallelism comes in. Answering the above questions should give you all the information you need to set up this method. Remember that this needs to be able work for any number of cakes passed through! &lt;br /&gt;
&lt;br /&gt;
Note that icer.ice() returns an object of IcedCake. Collect all the 'IcedCake's you make, and return them in an array.&lt;br /&gt;
&lt;br /&gt;
==Optional Challenge==&lt;br /&gt;
{{CodeToImplement|TwoOvenPipeline|mixBakeAndIceCakes|pipeline.cake.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker1, Baker baker2, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
As we've discussed in class, not all steps of the pipeline always take the same amount of time to complete. In this example, baking a cake in the oven usually takes much longer than simply mixing the ingredients or icing the cake. The Baker is the bottleneck on the performance of this pipeline. One way to further improve the process then is to simply add another oven. This time, build a similar pipeline to what you made earlier, but use both of the Bakers passed to you in order to speed things up. Here's a couple things to take note of:&lt;br /&gt;
*How have the tasks changed? How does this additional oven affect the number of threads your program will use?&lt;br /&gt;
*Assume that the only way to get a second oven is to buy an old, used one. It can't get as hot, so it will need more time to bake a cake. Because of this, it is better to set up your solution such that when a set of ingredients has been mixed, it sends them to any open oven, rather than just alternating between the two ovens.&lt;br /&gt;
*Make sure that only one of the two ovens bakes any given cake. Use baker.inUse() and baker.numberAlreadyBaked() to help keep track of which oven has done which cakes.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|CakePipelineVizApp|pipeline.cake.viz}}&lt;br /&gt;
&lt;br /&gt;
[[File:CakePipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
The viz below is for the challenge assignment.&lt;br /&gt;
&lt;br /&gt;
[[File:TwoOvenPipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|CakePipelineTestSuite|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2203</id>
		<title>Iced Cakes Pipeline</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iced_Cakes_Pipeline&amp;diff=2203"/>
		<updated>2018-07-24T05:47:00Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Pipelines can increase throughput when processing a stream of data.  We will gain additional experience with Phasers by building a software pipeline.&lt;br /&gt;
&lt;br /&gt;
=Backgroud=&lt;br /&gt;
&amp;lt;youtube&amp;gt;3cqVtc2rDlg&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Cakes==&lt;br /&gt;
class Mixer&lt;br /&gt;
:mix(int cakeIndex)&lt;br /&gt;
class Baker&lt;br /&gt;
:bake(int cakeIndex, MixedIngredients mixedIngredients)&lt;br /&gt;
:inUse()&lt;br /&gt;
:numberAlreadyBaked()&lt;br /&gt;
class Icer&lt;br /&gt;
:ice(int cakeIndex, BakedCake bakedCake)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Questions To Ask Yourself=&lt;br /&gt;
# What are my tasks?&lt;br /&gt;
# What work does each task need to do?&lt;br /&gt;
# What, if anything, does each task depend upon?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Required Code==&lt;br /&gt;
{{CodeToImplement|CakePipeline|mixBakeAndIceCakes|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
Design a simple pipeline using Phasers. In order to have a finished cake, you need to first mix the ingredients, then bake the cake, and finally ice it with frosting. Although you only have one tool for each step (one whisk, one oven, and one icing spatula), there's no problem with icing one cake while another is baking in the oven. That's where the parallelism comes in. Answering the above questions should give you all the information you need to set up this method. Remember that this needs to be able work for any number of cakes passed through! &lt;br /&gt;
&lt;br /&gt;
Note that icer.ice() returns an object of IcedCake. Collect all the 'IcedCake's you make, and return them in an array.&lt;br /&gt;
&lt;br /&gt;
==Optional Challenge==&lt;br /&gt;
{{CodeToImplement|TwoOvenPipeline|mixBakeAndIceCakes|pipeline.cake.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static IcedCake[] mixBakeAndIceCakes(Mixer mixer, Baker baker1, Baker baker2, Icer icer, int cakeCount)}}&lt;br /&gt;
&lt;br /&gt;
As we've discussed in class, not all steps of the pipeline always take the same amount of time to complete. In this example, baking a cake in the oven usually takes much longer than simply mixing the ingredients or icing the cake. The Baker is the bottleneck on the performance of this pipeline. One way to further improve the process then is to simply add another oven. This time, build a similar pipeline to what you made earlier, but use both of the Bakers passed to you in order to speed things up. Here's a couple things to take note of:&lt;br /&gt;
*How have the tasks changed? How does this additional oven affect the number of threads your program will use?&lt;br /&gt;
*Assume that the only way to get a second oven is to buy an old, used one. It can't get as hot, so it will need more time to bake a cake. Because of this, it is better to set up your solution such that when a set of ingredients has been mixed, it sends them to any open oven, rather than just alternating between the two ovens.&lt;br /&gt;
*Make sure that only one of the two ovens bakes any given cake. Use baker.inUse() and baker.numberAlreadyBaked() to help keep track of which oven has done which cakes.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|CakePipelineVizApp|pipeline.cake.viz}}&lt;br /&gt;
&lt;br /&gt;
[[File:CakePipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
The viz below is for the challenge assignment.&lt;br /&gt;
&lt;br /&gt;
[[File:TwoOvenPipelineGIF.gif]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|CakePipelineTestSuite|pipeline.cake.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Connect_Four&amp;diff=2202</id>
		<title>Connect Four</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Connect_Four&amp;diff=2202"/>
		<updated>2018-07-24T05:41:41Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: Finn Voichick and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
[https://en.wikipedia.org/wiki/Minimax Minimax] is an important concept in [https://en.wikipedia.org/wiki/Game_theory game theory] and search.&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Negamax Negamax] is a variant which relies on &amp;lt;math&amp;gt;\max(a, b) = -\min(-a, -b)&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While this technique is applicable to [https://en.wikipedia.org/wiki/Chess Chess] (as [https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer) Deep Blue] [https://en.wikipedia.org/wiki/Deep_Blue_versus_Garry_Kasparov employed to defeat Kasparov]), we choose [https://en.wikipedia.org/wiki/Connect_Four Connect Four] as our context since it has a simpler game mechanic.&lt;br /&gt;
&lt;br /&gt;
While the core part of searches like Minimax may be easy to parallelize, critical aspects such as alpha-beta pruning are more challenging.&lt;br /&gt;
&lt;br /&gt;
Parallelism can be added in a number of different ways.  We can choose at our preference between: &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;futures&amp;lt;/code&amp;gt;, and [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html RecursiveTask].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
==Video==&lt;br /&gt;
&amp;lt;youtube&amp;gt;STjW3eH0Cik&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
[http://blog.gamesolver.org/ Solving Connect Four]&lt;br /&gt;
&lt;br /&gt;
==Wikipedia==&lt;br /&gt;
[https://en.wikipedia.org/wiki/Minimax Minimax]&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Negamax Negamax]&lt;br /&gt;
&lt;br /&gt;
==The Core Questions==&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
==Code To Use==&lt;br /&gt;
===connectfour.core===&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html class Config]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html#getHeuristic-- getHeuristic()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html#getMaxDepth-- getMaxDepth()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html#getMaxParallelDepth-- getMaxParallelDepth()]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html interface Board]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html#isDone-- isDone()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html#getValidPlays-- getValidPlays()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html#createNextBoard-int- createNextBoard(int column)]&lt;br /&gt;
&lt;br /&gt;
===java.util.concurrent===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html class RecursiveTask] extends ForkJoinTask&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html#compute-- compute()]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html class ForkJoinTask]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html#fork-- fork()]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html#join-- join()]&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Win or Lose Heuristic==&lt;br /&gt;
{{CodeToImplement|WinOrLoseHeuristic|evaluate|connectfour.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public double evaluate(Board board)}}&lt;br /&gt;
&lt;br /&gt;
==Sequential Negamax==&lt;br /&gt;
{{CodeToImplement|SequentialConnectFour|negamax|connectfour.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static ColumnEvaluationPair negamax(Board board, Player playerWhoseTurnItIs, Config config, int currentDepth)}}&lt;br /&gt;
&lt;br /&gt;
==Parallel Choose Your Own Adventure==&lt;br /&gt;
The approach for each of the parallel paths is fundamentally the same.  Create tasks for each branch until you reach the specified depth at which you transition to sequential.&lt;br /&gt;
&lt;br /&gt;
The forall and futures paths use our X10 inspired features.  The NegamaxTask path is more well suited to those interested in standard Java parallel constructs.&lt;br /&gt;
&lt;br /&gt;
Choose one of the following paths:&lt;br /&gt;
===path a) forall===&lt;br /&gt;
{{CodeToImplement|ParallelForallConnectFour|negamax|connectfour.studio.chooseyourownadventure.forall}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ColumnEvaluationPair negamax(Board board, Player playerWhoseTurnItIs, Config config, int currentDepth)}}&lt;br /&gt;
&lt;br /&gt;
===path b) futures===&lt;br /&gt;
{{CodeToImplement|ParallelFuturesConnectFour|negamax|connectfour.studio.chooseyourownadventure.futures}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ColumnEvaluationPair negamax(Board board, Player playerWhoseTurnItIs, Config config, int currentDepth)}}&lt;br /&gt;
&lt;br /&gt;
===path c) recursive tasks===&lt;br /&gt;
{{CodeToImplement|NegamaxTask|compute|connectfour.studio.chooseyourownadventure.recursivetasks}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public ColumnEvaluationPair compute()}}&lt;br /&gt;
&lt;br /&gt;
==OpenEndedHeuristic==&lt;br /&gt;
NOW OPTIONAL&lt;br /&gt;
{{CodeToImplement|OpenEndedHeuristic|evaluate|connectfour.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public double evaluate(Board board)}}&lt;br /&gt;
&lt;br /&gt;
==(Optional) Utility==&lt;br /&gt;
You may elect to implement this utility method so that you can reuse the functionality across your negamaxes.&lt;br /&gt;
&lt;br /&gt;
One of the annoying things about parallel programming is that you often have to duplicate code for the initial parallel part often followed by the sequential part when you have created enough tasks already.  When building negamax, I found that I wanted to build a common method which would select the best column value pair from both the sequential and parallel algorithms.  To allow for all of the different parallel adventures, select takes a function which returns the ColumnEvaluationPair.  As an example, for the ParallelFuturesConnectFour adventure I used:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;return NegamaxUtils.select(futures, (future) -&amp;gt; chainedGet(future));&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|NegamaxUtils|select|connectfour.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static &amp;lt;T&amp;gt; ColumnEvaluationPair select(T[] array, Function&amp;lt;T, ColumnEvaluationPair&amp;gt; f)}}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|ConnectFourViz|connnectfour.challenge}}&lt;br /&gt;
&lt;br /&gt;
[[File:ConnectFourViz.png|400px]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|ConnectFourTestSuite|connnectfour.challenge}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Connect_Four&amp;diff=2201</id>
		<title>Connect Four</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Connect_Four&amp;diff=2201"/>
		<updated>2018-07-24T05:40:51Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: Finn Voichick and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
[https://en.wikipedia.org/wiki/Minimax Minimax] is an important concept in [https://en.wikipedia.org/wiki/Game_theory game theory] and search.&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Negamax Negamax] is a variant which relies on &amp;lt;math&amp;gt;\max(a, b) = -\min(-a, -b)&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While this technique is applicable to [https://en.wikipedia.org/wiki/Chess Chess] (as [https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer) Deep Blue] [https://en.wikipedia.org/wiki/Deep_Blue_versus_Garry_Kasparov employed to defeat Kasparov]), we choose [https://en.wikipedia.org/wiki/Connect_Four Connect Four] as our context since it has a simpler game mechanic.&lt;br /&gt;
&lt;br /&gt;
While the core part of searches like Minimax may be easy to parallelize, critical aspects such as alpha-beta pruning are more challenging.&lt;br /&gt;
&lt;br /&gt;
Parallelism can be added in a number of different ways.  We can choose at our preference between: &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;futures&amp;lt;/code&amp;gt;, and [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html RecursiveTask].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
==Video==&lt;br /&gt;
&amp;lt;youtube&amp;gt;STjW3eH0Cik&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Tutorial==&lt;br /&gt;
[http://blog.gamesolver.org/ Solving Connect Four]&lt;br /&gt;
&lt;br /&gt;
==Wikipedia==&lt;br /&gt;
[https://en.wikipedia.org/wiki/Minimax Minimax]&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Negamax Negamax]&lt;br /&gt;
&lt;br /&gt;
==Code To Use==&lt;br /&gt;
===connectfour.core===&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html class Config]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html#getHeuristic-- getHeuristic()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html#getMaxDepth-- getMaxDepth()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Config.html#getMaxParallelDepth-- getMaxParallelDepth()]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html interface Board]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html#isDone-- isDone()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html#getValidPlays-- getValidPlays()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/connectfour/core/Board.html#createNextBoard-int- createNextBoard(int column)]&lt;br /&gt;
&lt;br /&gt;
===java.util.concurrent===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html class RecursiveTask] extends ForkJoinTask&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html#compute-- compute()]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html class ForkJoinTask]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html#fork-- fork()]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html#join-- join()]&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Win or Lose Heuristic==&lt;br /&gt;
{{CodeToImplement|WinOrLoseHeuristic|evaluate|connectfour.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public double evaluate(Board board)}}&lt;br /&gt;
&lt;br /&gt;
==Sequential Negamax==&lt;br /&gt;
{{CodeToImplement|SequentialConnectFour|negamax|connectfour.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static ColumnEvaluationPair negamax(Board board, Player playerWhoseTurnItIs, Config config, int currentDepth)}}&lt;br /&gt;
&lt;br /&gt;
==Parallel Choose Your Own Adventure==&lt;br /&gt;
The approach for each of the parallel paths is fundamentally the same.  Create tasks for each branch until you reach the specified depth at which you transition to sequential.&lt;br /&gt;
&lt;br /&gt;
The forall and futures paths use our X10 inspired features.  The NegamaxTask path is more well suited to those interested in standard Java parallel constructs.&lt;br /&gt;
&lt;br /&gt;
Choose one of the following paths:&lt;br /&gt;
===path a) forall===&lt;br /&gt;
{{CodeToImplement|ParallelForallConnectFour|negamax|connectfour.studio.chooseyourownadventure.forall}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ColumnEvaluationPair negamax(Board board, Player playerWhoseTurnItIs, Config config, int currentDepth)}}&lt;br /&gt;
&lt;br /&gt;
===path b) futures===&lt;br /&gt;
{{CodeToImplement|ParallelFuturesConnectFour|negamax|connectfour.studio.chooseyourownadventure.futures}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ColumnEvaluationPair negamax(Board board, Player playerWhoseTurnItIs, Config config, int currentDepth)}}&lt;br /&gt;
&lt;br /&gt;
===path c) recursive tasks===&lt;br /&gt;
{{CodeToImplement|NegamaxTask|compute|connectfour.studio.chooseyourownadventure.recursivetasks}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public ColumnEvaluationPair compute()}}&lt;br /&gt;
&lt;br /&gt;
==OpenEndedHeuristic==&lt;br /&gt;
NOW OPTIONAL&lt;br /&gt;
{{CodeToImplement|OpenEndedHeuristic|evaluate|connectfour.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public double evaluate(Board board)}}&lt;br /&gt;
&lt;br /&gt;
==(Optional) Utility==&lt;br /&gt;
You may elect to implement this utility method so that you can reuse the functionality across your negamaxes.&lt;br /&gt;
&lt;br /&gt;
One of the annoying things about parallel programming is that you often have to duplicate code for the initial parallel part often followed by the sequential part when you have created enough tasks already.  When building negamax, I found that I wanted to build a common method which would select the best column value pair from both the sequential and parallel algorithms.  To allow for all of the different parallel adventures, select takes a function which returns the ColumnEvaluationPair.  As an example, for the ParallelFuturesConnectFour adventure I used:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;return NegamaxUtils.select(futures, (future) -&amp;gt; chainedGet(future));&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|NegamaxUtils|select|connectfour.challenge}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static &amp;lt;T&amp;gt; ColumnEvaluationPair select(T[] array, Function&amp;lt;T, ColumnEvaluationPair&amp;gt; f)}}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|ConnectFourViz|connnectfour.challenge}}&lt;br /&gt;
&lt;br /&gt;
[[File:ConnectFourViz.png|400px]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|ConnectFourTestSuite|connnectfour.challenge}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=N-Queens/Sudoku_Assignment&amp;diff=2200</id>
		<title>N-Queens/Sudoku Assignment</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=N-Queens/Sudoku_Assignment&amp;diff=2200"/>
		<updated>2018-07-24T05:39:14Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Sudoku */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Not everything in the world should be divided and conquered.  Backtracking is a powerful technique which can be readily parallelized.  We will gain experience with backtracking by solving the N-Queens problem and Sudoku in parallel.&lt;br /&gt;
&lt;br /&gt;
N-Queens in particular can be used to explain the call stack as the chessboard *IS* the call stack.  Whoa.&lt;br /&gt;
&lt;br /&gt;
In this assignment, you will implement solutions to both the n-queens and Sudoku problems.&lt;br /&gt;
&lt;br /&gt;
=N-Queens=&lt;br /&gt;
&lt;br /&gt;
[[File:SolvedNQueens8.PNG|250px|thumb|Example solution of N-Queens when n equals 8]]&lt;br /&gt;
&lt;br /&gt;
==Background==&lt;br /&gt;
The n-queens problem is a fundamental coding puzzle which asks: how can N queens be placed on an NxN chessboard so that they cannot attack each other? In chess, a queen can move horizontally, vertically, and diagonally across the board. Thus, to solve the n-queens problem, we must effectively figure out how to place the queens in such a way that no two of them occupy the same row, column, or diagonal. We will be building a method that finds the total number of solutions for n-queens for any given n.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Roadmap to Victory==&lt;br /&gt;
#DefaultImmutableQueens&lt;br /&gt;
#QueenLocationsUtils&lt;br /&gt;
#SequentialNQueens&lt;br /&gt;
#ParallelNQueens&lt;br /&gt;
&lt;br /&gt;
==The Core Questions==&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
==Code To Implement==&lt;br /&gt;
Before coding anything, take a look at the javadocs to see what everything does and what you will need to implement.&lt;br /&gt;
===Sequential Solution===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int countSolutions(MutableQueenLocations queenLocations) {&lt;br /&gt;
		MutableInt count = new MutableInt(0);&lt;br /&gt;
		placeQueenInRow(count, queenLocations, 0);&lt;br /&gt;
		return count.intValue();&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SequentialNQueens|placeQueenInRow|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void placeQueenInRow(MutableInt count, MutableQueenLocations queenLocations, int row)}}&lt;br /&gt;
&lt;br /&gt;
===Parallel Solution===&lt;br /&gt;
====Board State====&lt;br /&gt;
Investigate &amp;lt;code&amp;gt;DefaultMutableQueenLocations&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;AbstractQueenLocations&amp;lt;/code&amp;gt; for clues on how to implement &amp;lt;code&amp;gt;DefaultImmutableQueenLocations&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultImmutableQueenLocations|createNext&amp;lt;br&amp;gt;getColumnOfQueenInRow&amp;lt;br&amp;gt;getRowCount&amp;lt;br&amp;gt;getBoardSize|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public DefaultImmutableQueenLocations createNext(int column)}}&lt;br /&gt;
&lt;br /&gt;
There are two constructors for this class.  [https://www.cse.wustl.edu/~cosgroved/courses/cse231/curent/apidocs/nqueens/lab/DefaultImmutableQueenLocations.html#DefaultImmutableQueenLocations-int- A public one which creates a fresh new board state with no queens yet placed.] and a private one which creates a new board with the state of a given board which is further constrained by a new queen in the next row.  You need to create a new instance using one of these two constructors.  Which one is it? &lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getColumnOfQueenInRow(int row)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getRowCount()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getBoardSize()}}&lt;br /&gt;
&lt;br /&gt;
The three methods above can all be done in just one line. Don't make things too complicated! Note that we will refer to the standard 8x8 chessboard's size as 8 and not 64.&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public boolean isNextRowThreatFree(int column)}}&lt;br /&gt;
&lt;br /&gt;
Do not feel compelled to build this method from scratch.  Investigate your super class for a utility method that will be helpful. &lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/nqueens/core/AbstractQueenLocations.html#isCandidateThreatFree-int-int- isCandidateThreatFree(row, candidateColumn)]&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Board Utils====&lt;br /&gt;
This class will provide methods that will speed up our implementation of the parallel solution in the final step.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|QueenLocationsUtils|getCandidateColumns&amp;lt;br&amp;gt;getCandidateColumnsForNextRow|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential| public static Collection&amp;lt;Integer&amp;gt; getCandidateColumns(QueenLocations queenLocations, int row)}}&lt;br /&gt;
&lt;br /&gt;
This method should find all the columns in the given row that a queen could be placed, and return them in a single collection (ex. LinkedList). Don't forget to utilize some of the methods you just completed in &amp;lt;code&amp;gt;DefaultImmutableQueensLocation&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential| public static Collection&amp;lt;Integer&amp;gt; getCandidateColumnsForNextRow(ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
Nice and simple, don't overthink it! Just use methods you've already written to do all the work.&lt;br /&gt;
&lt;br /&gt;
====ParallelNQueens====&lt;br /&gt;
Searching for solutions like n-queens can be done in parallel without the need to finish at each level.  As such, &amp;lt;code&amp;gt;forasync&amp;lt;/code&amp;gt; is preferable to &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;.  However:&lt;br /&gt;
&lt;br /&gt;
{{Warning|Ensure that you complete all of your tasks by enclosing them all in a &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelNQueens|placeQueenInRow&amp;lt;br&amp;gt;countSolutions|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static int countSolutions(ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|FinishAccumulators must be registered with their finish statement}}&lt;br /&gt;
&lt;br /&gt;
Instead of using a MutableInt in order to count the number of solutions we have found, we want to use a Finish Accumulator. Refer to the [[Syntax_of_231#Finish_Accumulators|syntax page]] in order to see the syntax for properly setting up the accumulator.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void placeQueenInRow(FinishAccumulator&amp;lt;Integer&amp;gt; acc, ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
Make sure you look at the Sequential N-Queens solution if you need ideas on how to approach the algorithm.&lt;br /&gt;
&lt;br /&gt;
==Tips==&lt;br /&gt;
*As &amp;lt;code&amp;gt;ImmutableQueenLocations&amp;lt;/code&amp;gt; is immutable, you will need to create a new instance of the object whenever you move on from one row to the next. This is where &amp;lt;code&amp;gt;createNext&amp;lt;/code&amp;gt; comes in, along with the private constructor of this class.&lt;br /&gt;
*The &amp;lt;code&amp;gt;isNextRowThreatFree&amp;lt;/code&amp;gt; method can easily be completed with a method in &amp;lt;code&amp;gt;AbstractQueenLocations&amp;lt;/code&amp;gt;. Refer to that for help.&lt;br /&gt;
*The sequential solution uses &amp;lt;code&amp;gt;MutableQueenLocations&amp;lt;/code&amp;gt; while the parallel solution uses your implementation of &amp;lt;code&amp;gt;ImmutableQueenLocations&amp;lt;/code&amp;gt;. Be careful to use the correct &amp;lt;code&amp;gt;QueenLocations&amp;lt;/code&amp;gt; implementation.&lt;br /&gt;
*As the name suggests, &amp;lt;code&amp;gt;placeQueenInRow&amp;lt;/code&amp;gt; will go through the columns of the given row to check if a queen can fit in that location. If it can, it will set that value in &amp;lt;code&amp;gt;MutableQueenLocations&amp;lt;/code&amp;gt;. If the examined row is that last row of the board, you have found one valid solution to the n-queens problem. Update the correct parameter accordingly. Otherwise, recurse and keep going until you reach the last row.&lt;br /&gt;
*For the parallel implementation of &amp;lt;code&amp;gt;placeQueenInRow&amp;lt;/code&amp;gt;, we are using the &amp;quot;one-finish&amp;quot; pattern. Do not call &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt; in the recursive method.&lt;br /&gt;
*Go check out the [[Syntax_of_231#Finish_Accumulators|syntax page]] if you have questions on how to set up the Finish Accumulator&lt;br /&gt;
&lt;br /&gt;
=Sudoku=&lt;br /&gt;
==Background==&lt;br /&gt;
[[File:BasicSudoku.PNG|thumb]]&lt;br /&gt;
We will be using a similar algorithm to solve a Sudoku puzzle. For those not familiar, a Sudoku puzzle is composed of a 9-by-9 grid of squares. This grid is also divided into 9 large boxes, each of which is a 3-by-3 of the smaller squares. In a completed puzzle, each of the smaller squares contains a single number from 1 to 9 (inclusive). However, if a square contains a given number, that same number cannot be anywhere else in the same row, column, or box. Thus, for Sudoku, we are given an incomplete board and must fill in the remaining squares while meeting these requirements.&lt;br /&gt;
&lt;br /&gt;
Sudoku is another problem well solved by backtracking.  Check the understanding you gained of backtracking with N-Queens by challenging yourself to solve Sudoku's solver without assistance. The game of Sudoku is bit more complex though than N-Queens, and there are more strategies we can do than just backtracking in order to speed up our solution. To make this assignment more compelling, you will also do search orderings and constraint propagation. &lt;br /&gt;
&lt;br /&gt;
Read [http://norvig.com/sudoku.html Peter Norvig's Essay] before you begin coding. It will cover everything related to the Sudoku problem itself and how one can design a solution for it.&lt;br /&gt;
&lt;br /&gt;
==Roadmap to Victory==&lt;br /&gt;
There isn't one easiest path through the required files. Some classes utilize methods written in other files, so some students may take a the path such that they will only call methods that are provided or have already implemented. For other students, it might be conceptually easier to start with &amp;lt;code&amp;gt;ParallelSudoku.java&amp;lt;/code&amp;gt;, since this class closest resembles the work you just did in n-queens. Below is one path that we recommend. In this path, you will have to call the constraint propagator in the Immutable Puzzle before completing the actual propagator, but aside from that most methods build on top of one another. In summary, you can work on these classes in whatever order makes the most sense for you personally.&lt;br /&gt;
#DefaultImmutableSudokuPuzzle&lt;br /&gt;
#RowMajorSquareSearchAlgorithm&lt;br /&gt;
#FewestOptionsFirstSquareSearchAlgorithm&lt;br /&gt;
#ParallelSudoku&lt;br /&gt;
#DefaultConstraintPropagator&lt;br /&gt;
#(Optional Challenge) Add Unit Constraint Propagation to DefaultConstraintPropagator&lt;br /&gt;
&lt;br /&gt;
==The Core Questions==&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
==Code To Investigate==&lt;br /&gt;
enum [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html Square]&lt;br /&gt;
:Collection&amp;lt;Square&amp;gt; [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#getPeers-- getPeers()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#valueOf-int-int- valueOf(row, column)]&lt;br /&gt;
:all [https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html enums] have a [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#values-- values()] method&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Units.html Units]&lt;br /&gt;
:public static Iterable&amp;lt;Collection&amp;lt;Square&amp;gt;&amp;gt; [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Units.html#allUnits-- allUnits()]&lt;br /&gt;
&lt;br /&gt;
interface [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/ConstraintPropagator.html ConstraintPropagator] extends AbstractSet&amp;lt;Integer&amp;gt; implements SortedSet&amp;lt;Integer&amp;gt;&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html OptionSet]&lt;br /&gt;
:public static OptionSet [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html#createAllOptions-- createAllOptions()]&lt;br /&gt;
:public static OptionSet [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html#createSingleOption-- createSingleOption(int option)]&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/SquareToOptionSetMapUtils.html SquareToOptionSetMapUtils]&lt;br /&gt;
:public static Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; deepCopyOf(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; other)&lt;br /&gt;
&lt;br /&gt;
==Code To Implement==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Puzzle===&lt;br /&gt;
As the name suggests, &amp;lt;code&amp;gt;ImmutableSudokuPuzzle&amp;lt;/code&amp;gt; is immutable, and you will need to create a new instance of the object whenever you move on from one square to the next. This is analogous to the work you did for [[#NQueens]].&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultImmutableSudokuPuzzle|constructors&amp;lt;br&amp;gt;createNext&amp;lt;br&amp;gt;getValue&amp;lt;br&amp;gt;getOptions|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public DefaultImmutableSudokuPuzzle(ConstraintPropagator constraintPropagator, String givens)}}&lt;br /&gt;
&lt;br /&gt;
This constructor creates a puzzle constrained to an initial set of givens.  You can think of the givens as the original values provided by the newspaper or airline magazine or puzzle book or whatever.&lt;br /&gt;
&lt;br /&gt;
You will leverage the constraintPropagator to build your map of option sets.&lt;br /&gt;
&lt;br /&gt;
{{Tip| To quickly make a map containing each possible Square, use &amp;lt;code&amp;gt;new EnumMap&amp;lt;&amp;gt;(Square.class)&amp;lt;/code&amp;gt;}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private DefaultImmutableSudokuPuzzle(DefaultImmutableSudokuPuzzle other, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This constructor takes a given previous puzzle and a square value to create a new further constrained puzzle.&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public ImmutableSudokuPuzzle createNext(Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This method should create a new puzzle instance using one of the constructors.  Which one is it?&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getValue(Square square)}}&lt;br /&gt;
&lt;br /&gt;
Based on the state of the board, return the value of a given square if it is known.  Otherwise, return 0.&lt;br /&gt;
&lt;br /&gt;
How do we determine if a value for a given square is &amp;quot;known&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public SortedSet&amp;lt;Integer&amp;gt; getOptions(Square square)}}&lt;br /&gt;
&lt;br /&gt;
Based on the state of the board, return the candidate values for a given square.&lt;br /&gt;
&lt;br /&gt;
===Search Order===&lt;br /&gt;
Simply by changing the search order, a great reduction of work can be achieved.  The class names sadly give away the approaches.  &lt;br /&gt;
&lt;br /&gt;
Ask yourself: &lt;br /&gt;
* Which algorithm will perform better and why?&lt;br /&gt;
* What properties make a square &amp;quot;filled&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|RowMajorSquareSearchAlgorithm|selectNextUnfilledSquare|sudoku.lab}}&lt;br /&gt;
{{Sequential|public Square selectNextUnfilledSquare(SudokuPuzzle puzzle)}}&lt;br /&gt;
&lt;br /&gt;
Simply run through the &amp;lt;code&amp;gt;Square.values()&amp;lt;/code&amp;gt; which will iterate through squares going down the row (A1, A2, A3, ...). Make sure not to return squares that have already been filled.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|FewestOptionsFirstSquareSearchAlgorithm|selectNextUnfilledSquare|sudoku.lab}}&lt;br /&gt;
{{Sequential|public Square selectNextUnfilledSquare(SudokuPuzzle puzzle)}}&lt;br /&gt;
&lt;br /&gt;
Go through every square by calling &amp;lt;code&amp;gt;Square.values()&amp;lt;/code&amp;gt;, find a square that is (1) not already filled, and (2) has the minimal number of possible options among all the squares, and return that square.&lt;br /&gt;
&lt;br /&gt;
===Solver===&lt;br /&gt;
This part of the assignment is also similar to its n-queens counterpart. Searching for solutions like sudoku can be done in parallel without the need to finish at each level.  As such, &amp;lt;code&amp;gt;forasync&amp;lt;/code&amp;gt; is preferable to &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;.  However:&lt;br /&gt;
&lt;br /&gt;
{{Warning|Ensure that you complete all of your tasks by enclosing them all in a &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelSudoku|solve&amp;lt;br&amp;gt;solveKernel|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ImmutableSudokuPuzzle solve(ImmutableSudokuPuzzle puzzle, SquareSearchAlgorithm squareSearchAlgorithm)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void solveKernel(MutableObject&amp;lt;ImmutableSudokuPuzzle&amp;gt; solution, ImmutableSudokuPuzzle puzzle, SquareSearchAlgorithm squareSearchAlgorithm)}}&lt;br /&gt;
&lt;br /&gt;
====Tips====&lt;br /&gt;
*Make sure your solver uses the generic SquareSearchAlgorithm so that it works with both versions of the search ordering.&lt;br /&gt;
*Just like n-queens, your &amp;lt;code&amp;gt;solveKernel&amp;lt;/code&amp;gt; is the recursive method that will be called in the solve method. Again, watch where you put your &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.&lt;br /&gt;
*In your &amp;lt;code&amp;gt;solveKernel&amp;lt;/code&amp;gt; method, you should use the given search algorithm (row major or fewest options first) to select which square you will fill. After selecting a square, you should recursively call the kernel to check every viable option in the context of the puzzle. If there are no more unfilled squares, you should set the value of the solution to the finished puzzle and exit out of the recursion.&lt;br /&gt;
&lt;br /&gt;
===Constraint Propagator===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultConstraintPropagator|createOptionSetsFromGivens&amp;lt;br&amp;gt;createNextOptionSets&amp;lt;br&amp;gt;assign&amp;lt;br&amp;gt;eliminate|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
You will need to implement two public methods to satisfy the ConstraintPropagator interface: &amp;lt;code&amp;gt;createOptionSetsFromGivens&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;createNextOptionSets&amp;lt;/code&amp;gt;.  Each of these two methods will be invoked from a different constructor in the [[#DefaultImmutableSudokuPuzzle]] class.  It should be relatively obvious which one goes with which based on the parameters.&lt;br /&gt;
&lt;br /&gt;
{{Warning| Resist the temptation to perform the constraint propagation in these public methods.  Get things set up and then get your private method(s) to work for you.}}&lt;br /&gt;
&lt;br /&gt;
====createOptionSetsFromGivens====&lt;br /&gt;
{{Sequential|public Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; createOptionSetsFromGivens(String givens)}}&lt;br /&gt;
&lt;br /&gt;
This method will be invoked when you have loaded a new puzzle.  Whether it is from the newspaper, or your airline magazine, or Dr. Arto Inkala there is a set of givens the puzzle creator has provided. That string of givens is parsed into a double array of integers that aligns with the Sudoku board (values[0][0] is the top left corner of the board). If a specific spot of the board wasn't given in the input, it will be put into values[][] as 0.  &lt;br /&gt;
&lt;br /&gt;
A good approach here is to start of by initializing all of the squares to all the options (1 through 9) whether or not the square has a given value.  &lt;br /&gt;
&lt;br /&gt;
Once that is complete go through the givens and get your private method(s) to work for you.  Note: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#valueOf-int-int- Square.valueOf(row, column)] should be useful here.&lt;br /&gt;
&lt;br /&gt;
====createNextOptionSets====&lt;br /&gt;
{{Sequential|public Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; createNextOptionSets(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; otherOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This method should be invoked when you are searching for the solution in your solver.  Much like when you need to create a new copy of the board every time you make a decision in the n-queens search so too will you need to create a new copy of your sudoku board every time you make a decision in your backtracking search.&lt;br /&gt;
&lt;br /&gt;
Make sure to use the &amp;lt;code&amp;gt;SquareToOptionSetMapUtils.deepCopyOf&amp;lt;/code&amp;gt; method and refrain from mutating the incoming parameter &amp;lt;code&amp;gt;otherOptionSets&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
As warned above, do not actually do any of the constraint propagation in this method. Simply get the copy of the options set, then send it through your private &amp;lt;code&amp;gt;assign&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;eliminate&amp;lt;/code&amp;gt; to update the copy to be correct before returning it.&lt;br /&gt;
&lt;br /&gt;
{{Tip |If you have two Lists, &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;, and you set &amp;lt;code&amp;gt;a &amp;lt;nowiki&amp;gt;=&amp;lt;/nowiki&amp;gt; b&amp;lt;/code&amp;gt;, then any changes you make to &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; will also be made to &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;. Both variables reference the same objects; they are not copies.}}&lt;br /&gt;
&lt;br /&gt;
====Assign and Eliminate====&lt;br /&gt;
&lt;br /&gt;
[http://norvig.com/sudoku.html Peter Norvig's Essay] is very helpful here.  We have adopted his terms, but challenge yourself to complete this section without simply translating his pseudocode.&lt;br /&gt;
&lt;br /&gt;
To simplify things a bit, we have elected to not short circuit when a 0 option square is found (relying on the search ordering to take care of that for us).&lt;br /&gt;
&lt;br /&gt;
It is up to you how to utilize these two methods. The goal is to update the map that is passed in to reflect the &amp;quot;solving&amp;quot; of a square. For example, if assign is called on square A1 for the value 1, the map that is returned should link the square A1 to a list containing just the value 1 ([1]). Furthermore, any square that is a peer of A1 (ex. B1), should not have the value 1 in its set in the map. &lt;br /&gt;
&lt;br /&gt;
But in solving Sudoku, there are some strategies that we can rely on to more efficiently complete the puzzle. The first one, and required in order to finish this lab, is ''Peer Elimination Constraint Propagation'' (rule 1 in the Norvig essay). The rule is as follows: &amp;quot;If a square has only one possible value, then eliminate that value from the square's peers.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Let's very slowly walk through a example of this propagation in detail to make it more clear what we are looking for. Start by looking at this nearly finished board:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
		|-&lt;br /&gt;
		! Board !! Info&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:PeerConstraint1.PNG|200px]]  || We can see that the red square (D1) has only one available option. At this point, let's say we call assign on the red square D1 for the value 1.&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:PeerConstraint3.PNG|200px]]  || As part of the assignment process, all the peers of red square D1 have the value 1 removed from their possibilities. In this example, yellow square, A1, is directly affected! After eliminating the alternative option, there is only one possible value yellow square A1 could be. This is where our constraint propagator needs to take the next step and treat yellow square A1 as assigned.&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:PeerConstraint4.PNG|200px]]  || This step right here (going from a small 7 to a big 7) is not actually something our program will do. In our implementation, '''having only one option in a square's set is equivalent to that square being &amp;quot;assigned&amp;quot; to that value'''. Because of this, you actually do not need to call assign again for yellow square A1.&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:PeerConstraint5.PNG|200px]]  || Now that yellow square A1 is known, the final step is to go through all of A1's peers (including green square C3) and remove the value 7. Note that now there is only one possible option left for green square C3. Your code should keep going, looking at all the peers of C3 and eliminating the value 1, and so on. Some puzzles can be completely solved using only Peer Elimination constraint propagation!&lt;br /&gt;
		|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
{{Sequential|private void assign(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; resultOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|If you are hitting a ConcurrentModificationException here, make sure to make a copy of the optionsSet you are iterating over.  Use your local utility copyOf method. }}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	SortedSet&amp;lt;Integer&amp;gt; copy = copyOf(optionSet);&lt;br /&gt;
	for (int otherValue : copy) {&lt;br /&gt;
		...&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private void eliminate(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; resultOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
====(Optional) Unit Constraint Propagation====&lt;br /&gt;
The second rule in [http://norvig.com/sudoku.html Peter Norvig's Essay] is Unit Constraint Propagation: &amp;quot;If a unit has only one possible place for a value, then put the value there&amp;quot;. This propagation rule is it bit more challenging to put into code, but doing so can make even the hardest of Sudoku puzzles fall nice and quickly. To complete this bonus part of the lab, simply update your &amp;lt;code&amp;gt;assign&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;eliminate&amp;lt;/code&amp;gt; methods to do unit constraint propagation (don't remove the old propagation rule!). After assigning a square, you'll have to look at the new options set to see if any unit (a single row, column, or box) has only one unassigned square that is a possibility for any value. We encourage you to think of a solution on your own! Below is a example of unit constraint propagation.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
		|-&lt;br /&gt;
		! Board !! Info&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:UnitConstraint1.PNG|200px]]  || We can see that the red square (E1) has only one available option. At this point, let's say we call assign on the red square E1 for the value 6.&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:UnitConstraint2.PNG|200px]]  || Due to the assignment of red square E1, the value of 6 is eliminated from its peer, yellow square A1. &lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:UnitConstraint3.PNG|200px]]  || Our Peer Elimination constraint propagation will treat yellow square A1 as if it has been assigned. Unfortunately, eliminating the value 9 from the peers doesn't open up any new opportunities for solving squares. This is where unit constraint propagation kicks in. Of the three unassigned squares in the top left box unit, 6 is only a valid option in the green square, C3. Even though green square C3 has multiple possible options remaining, we know that it '''must''' be 6, and should assign it as such&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:UnitConstraint4.PNG|200px]]  || Once green square C3 has been assigned (all other options are removed), we should make sure that all of C3's peers have 6 removed from their options. And keep an eye out for any new squares that we now know due to the two propagation rules! With both peer elimination and unit constraint propagation, we can solve a large quantity of Sudoku puzzles without needing any backtracking recursion&lt;br /&gt;
		|}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
===N-Queens===&lt;br /&gt;
{{Viz|NQueensVizApp|nqueens.viz.solution}}&lt;br /&gt;
&lt;br /&gt;
[[File:NQueensViz.png]]&lt;br /&gt;
&lt;br /&gt;
===Sudoku===&lt;br /&gt;
{{Viz|SudokuSolutionApp|sudoku.viz.solution}}&lt;br /&gt;
&lt;br /&gt;
[[File:SudokuViz.png]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|BacktrackTestSuite|backtrack.lab}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|NQueensTestSuite|nqueens.lab}}&lt;br /&gt;
{{TestSuite|SudokuTestSuite|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
===(Optional) Challenge Unit Constraint Propagation===&lt;br /&gt;
{{TestSuite|ChallengeSudokuTestSuite|sudoku.challenge}}&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
N-Queens subtotal: 35&lt;br /&gt;
* Correct DefaultImmutableQueenLocations (5)&lt;br /&gt;
* Correct SequentialNQueens (10)&lt;br /&gt;
* Correct ParallelNQueens (10)&lt;br /&gt;
* Parallel ParallelNQueens (10)&lt;br /&gt;
&lt;br /&gt;
Sudoku subtotal: 55&lt;br /&gt;
* Correct DefaultImmutableSudokuPuzzle (5)&lt;br /&gt;
* Correct ContraintPropagator (15)&lt;br /&gt;
* Correct RowMajorSquareSearchAlgorithm (5)&lt;br /&gt;
* Correct FewestOtionsFirstSquareSearchAlgorithm (10)&lt;br /&gt;
* Correct ParallelSudoku (10)&lt;br /&gt;
* Parallel ParallelSudoku (10)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=N-Queens/Sudoku_Assignment&amp;diff=2199</id>
		<title>N-Queens/Sudoku Assignment</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=N-Queens/Sudoku_Assignment&amp;diff=2199"/>
		<updated>2018-07-24T05:38:35Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* N-Queens */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Not everything in the world should be divided and conquered.  Backtracking is a powerful technique which can be readily parallelized.  We will gain experience with backtracking by solving the N-Queens problem and Sudoku in parallel.&lt;br /&gt;
&lt;br /&gt;
N-Queens in particular can be used to explain the call stack as the chessboard *IS* the call stack.  Whoa.&lt;br /&gt;
&lt;br /&gt;
In this assignment, you will implement solutions to both the n-queens and Sudoku problems.&lt;br /&gt;
&lt;br /&gt;
=N-Queens=&lt;br /&gt;
&lt;br /&gt;
[[File:SolvedNQueens8.PNG|250px|thumb|Example solution of N-Queens when n equals 8]]&lt;br /&gt;
&lt;br /&gt;
==Background==&lt;br /&gt;
The n-queens problem is a fundamental coding puzzle which asks: how can N queens be placed on an NxN chessboard so that they cannot attack each other? In chess, a queen can move horizontally, vertically, and diagonally across the board. Thus, to solve the n-queens problem, we must effectively figure out how to place the queens in such a way that no two of them occupy the same row, column, or diagonal. We will be building a method that finds the total number of solutions for n-queens for any given n.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Roadmap to Victory==&lt;br /&gt;
#DefaultImmutableQueens&lt;br /&gt;
#QueenLocationsUtils&lt;br /&gt;
#SequentialNQueens&lt;br /&gt;
#ParallelNQueens&lt;br /&gt;
&lt;br /&gt;
==The Core Questions==&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
==Code To Implement==&lt;br /&gt;
Before coding anything, take a look at the javadocs to see what everything does and what you will need to implement.&lt;br /&gt;
===Sequential Solution===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int countSolutions(MutableQueenLocations queenLocations) {&lt;br /&gt;
		MutableInt count = new MutableInt(0);&lt;br /&gt;
		placeQueenInRow(count, queenLocations, 0);&lt;br /&gt;
		return count.intValue();&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SequentialNQueens|placeQueenInRow|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void placeQueenInRow(MutableInt count, MutableQueenLocations queenLocations, int row)}}&lt;br /&gt;
&lt;br /&gt;
===Parallel Solution===&lt;br /&gt;
====Board State====&lt;br /&gt;
Investigate &amp;lt;code&amp;gt;DefaultMutableQueenLocations&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;AbstractQueenLocations&amp;lt;/code&amp;gt; for clues on how to implement &amp;lt;code&amp;gt;DefaultImmutableQueenLocations&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultImmutableQueenLocations|createNext&amp;lt;br&amp;gt;getColumnOfQueenInRow&amp;lt;br&amp;gt;getRowCount&amp;lt;br&amp;gt;getBoardSize|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public DefaultImmutableQueenLocations createNext(int column)}}&lt;br /&gt;
&lt;br /&gt;
There are two constructors for this class.  [https://www.cse.wustl.edu/~cosgroved/courses/cse231/curent/apidocs/nqueens/lab/DefaultImmutableQueenLocations.html#DefaultImmutableQueenLocations-int- A public one which creates a fresh new board state with no queens yet placed.] and a private one which creates a new board with the state of a given board which is further constrained by a new queen in the next row.  You need to create a new instance using one of these two constructors.  Which one is it? &lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getColumnOfQueenInRow(int row)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getRowCount()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getBoardSize()}}&lt;br /&gt;
&lt;br /&gt;
The three methods above can all be done in just one line. Don't make things too complicated! Note that we will refer to the standard 8x8 chessboard's size as 8 and not 64.&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public boolean isNextRowThreatFree(int column)}}&lt;br /&gt;
&lt;br /&gt;
Do not feel compelled to build this method from scratch.  Investigate your super class for a utility method that will be helpful. &lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/nqueens/core/AbstractQueenLocations.html#isCandidateThreatFree-int-int- isCandidateThreatFree(row, candidateColumn)]&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Board Utils====&lt;br /&gt;
This class will provide methods that will speed up our implementation of the parallel solution in the final step.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|QueenLocationsUtils|getCandidateColumns&amp;lt;br&amp;gt;getCandidateColumnsForNextRow|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential| public static Collection&amp;lt;Integer&amp;gt; getCandidateColumns(QueenLocations queenLocations, int row)}}&lt;br /&gt;
&lt;br /&gt;
This method should find all the columns in the given row that a queen could be placed, and return them in a single collection (ex. LinkedList). Don't forget to utilize some of the methods you just completed in &amp;lt;code&amp;gt;DefaultImmutableQueensLocation&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential| public static Collection&amp;lt;Integer&amp;gt; getCandidateColumnsForNextRow(ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
Nice and simple, don't overthink it! Just use methods you've already written to do all the work.&lt;br /&gt;
&lt;br /&gt;
====ParallelNQueens====&lt;br /&gt;
Searching for solutions like n-queens can be done in parallel without the need to finish at each level.  As such, &amp;lt;code&amp;gt;forasync&amp;lt;/code&amp;gt; is preferable to &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;.  However:&lt;br /&gt;
&lt;br /&gt;
{{Warning|Ensure that you complete all of your tasks by enclosing them all in a &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelNQueens|placeQueenInRow&amp;lt;br&amp;gt;countSolutions|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static int countSolutions(ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|FinishAccumulators must be registered with their finish statement}}&lt;br /&gt;
&lt;br /&gt;
Instead of using a MutableInt in order to count the number of solutions we have found, we want to use a Finish Accumulator. Refer to the [[Syntax_of_231#Finish_Accumulators|syntax page]] in order to see the syntax for properly setting up the accumulator.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void placeQueenInRow(FinishAccumulator&amp;lt;Integer&amp;gt; acc, ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
Make sure you look at the Sequential N-Queens solution if you need ideas on how to approach the algorithm.&lt;br /&gt;
&lt;br /&gt;
==Tips==&lt;br /&gt;
*As &amp;lt;code&amp;gt;ImmutableQueenLocations&amp;lt;/code&amp;gt; is immutable, you will need to create a new instance of the object whenever you move on from one row to the next. This is where &amp;lt;code&amp;gt;createNext&amp;lt;/code&amp;gt; comes in, along with the private constructor of this class.&lt;br /&gt;
*The &amp;lt;code&amp;gt;isNextRowThreatFree&amp;lt;/code&amp;gt; method can easily be completed with a method in &amp;lt;code&amp;gt;AbstractQueenLocations&amp;lt;/code&amp;gt;. Refer to that for help.&lt;br /&gt;
*The sequential solution uses &amp;lt;code&amp;gt;MutableQueenLocations&amp;lt;/code&amp;gt; while the parallel solution uses your implementation of &amp;lt;code&amp;gt;ImmutableQueenLocations&amp;lt;/code&amp;gt;. Be careful to use the correct &amp;lt;code&amp;gt;QueenLocations&amp;lt;/code&amp;gt; implementation.&lt;br /&gt;
*As the name suggests, &amp;lt;code&amp;gt;placeQueenInRow&amp;lt;/code&amp;gt; will go through the columns of the given row to check if a queen can fit in that location. If it can, it will set that value in &amp;lt;code&amp;gt;MutableQueenLocations&amp;lt;/code&amp;gt;. If the examined row is that last row of the board, you have found one valid solution to the n-queens problem. Update the correct parameter accordingly. Otherwise, recurse and keep going until you reach the last row.&lt;br /&gt;
*For the parallel implementation of &amp;lt;code&amp;gt;placeQueenInRow&amp;lt;/code&amp;gt;, we are using the &amp;quot;one-finish&amp;quot; pattern. Do not call &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt; in the recursive method.&lt;br /&gt;
*Go check out the [[Syntax_of_231#Finish_Accumulators|syntax page]] if you have questions on how to set up the Finish Accumulator&lt;br /&gt;
&lt;br /&gt;
=Sudoku=&lt;br /&gt;
==Background==&lt;br /&gt;
[[File:BasicSudoku.PNG|thumb]]&lt;br /&gt;
We will be using a similar algorithm to solve a Sudoku puzzle. For those not familiar, a Sudoku puzzle is composed of a 9-by-9 grid of squares. This grid is also divided into 9 large boxes, each of which is a 3-by-3 of the smaller squares. In a completed puzzle, each of the smaller squares contains a single number from 1 to 9 (inclusive). However, if a square contains a given number, that same number cannot be anywhere else in the same row, column, or box. Thus, for Sudoku, we are given an incomplete board and must fill in the remaining squares while meeting these requirements.&lt;br /&gt;
&lt;br /&gt;
Sudoku is another problem well solved by backtracking.  Check the understanding you gained of backtracking with N-Queens by challenging yourself to solve Sudoku's solver without assistance. The game of Sudoku is bit more complex though than N-Queens, and there are more strategies we can do than just backtracking in order to speed up our solution. To make this assignment more compelling, you will also do search orderings and constraint propagation. &lt;br /&gt;
&lt;br /&gt;
Read [http://norvig.com/sudoku.html Peter Norvig's Essay] before you begin coding. It will cover everything related to the Sudoku problem itself and how one can design a solution for it.&lt;br /&gt;
&lt;br /&gt;
==Roadmap to Victory==&lt;br /&gt;
There isn't one easiest path through the required files. Some classes utilize methods written in other files, so some students may take a the path such that they will only call methods that are provided or have already implemented. For other students, it might be conceptually easier to start with &amp;lt;code&amp;gt;ParallelSudoku.java&amp;lt;/code&amp;gt;, since this class closest resembles the work you just did in n-queens. Below is one path that we recommend. In this path, you will have to call the constraint propagator in the Immutable Puzzle before completing the actual propagator, but aside from that most methods build on top of one another. In summary, you can work on these classes in whatever order makes the most sense for you personally.&lt;br /&gt;
#DefaultImmutableSudokuPuzzle&lt;br /&gt;
#RowMajorSquareSearchAlgorithm&lt;br /&gt;
#FewestOptionsFirstSquareSearchAlgorithm&lt;br /&gt;
#ParallelSudoku&lt;br /&gt;
#DefaultConstraintPropagator&lt;br /&gt;
#(Optional Challenge) Add Unit Constraint Propagation to DefaultConstraintPropagator&lt;br /&gt;
&lt;br /&gt;
==Code To Investigate==&lt;br /&gt;
enum [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html Square]&lt;br /&gt;
:Collection&amp;lt;Square&amp;gt; [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#getPeers-- getPeers()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#valueOf-int-int- valueOf(row, column)]&lt;br /&gt;
:all [https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html enums] have a [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#values-- values()] method&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Units.html Units]&lt;br /&gt;
:public static Iterable&amp;lt;Collection&amp;lt;Square&amp;gt;&amp;gt; [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Units.html#allUnits-- allUnits()]&lt;br /&gt;
&lt;br /&gt;
interface [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/ConstraintPropagator.html ConstraintPropagator] extends AbstractSet&amp;lt;Integer&amp;gt; implements SortedSet&amp;lt;Integer&amp;gt;&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html OptionSet]&lt;br /&gt;
:public static OptionSet [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html#createAllOptions-- createAllOptions()]&lt;br /&gt;
:public static OptionSet [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html#createSingleOption-- createSingleOption(int option)]&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/SquareToOptionSetMapUtils.html SquareToOptionSetMapUtils]&lt;br /&gt;
:public static Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; deepCopyOf(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; other)&lt;br /&gt;
&lt;br /&gt;
==Code To Implement==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Puzzle===&lt;br /&gt;
As the name suggests, &amp;lt;code&amp;gt;ImmutableSudokuPuzzle&amp;lt;/code&amp;gt; is immutable, and you will need to create a new instance of the object whenever you move on from one square to the next. This is analogous to the work you did for [[#NQueens]].&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultImmutableSudokuPuzzle|constructors&amp;lt;br&amp;gt;createNext&amp;lt;br&amp;gt;getValue&amp;lt;br&amp;gt;getOptions|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public DefaultImmutableSudokuPuzzle(ConstraintPropagator constraintPropagator, String givens)}}&lt;br /&gt;
&lt;br /&gt;
This constructor creates a puzzle constrained to an initial set of givens.  You can think of the givens as the original values provided by the newspaper or airline magazine or puzzle book or whatever.&lt;br /&gt;
&lt;br /&gt;
You will leverage the constraintPropagator to build your map of option sets.&lt;br /&gt;
&lt;br /&gt;
{{Tip| To quickly make a map containing each possible Square, use &amp;lt;code&amp;gt;new EnumMap&amp;lt;&amp;gt;(Square.class)&amp;lt;/code&amp;gt;}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private DefaultImmutableSudokuPuzzle(DefaultImmutableSudokuPuzzle other, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This constructor takes a given previous puzzle and a square value to create a new further constrained puzzle.&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public ImmutableSudokuPuzzle createNext(Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This method should create a new puzzle instance using one of the constructors.  Which one is it?&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getValue(Square square)}}&lt;br /&gt;
&lt;br /&gt;
Based on the state of the board, return the value of a given square if it is known.  Otherwise, return 0.&lt;br /&gt;
&lt;br /&gt;
How do we determine if a value for a given square is &amp;quot;known&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public SortedSet&amp;lt;Integer&amp;gt; getOptions(Square square)}}&lt;br /&gt;
&lt;br /&gt;
Based on the state of the board, return the candidate values for a given square.&lt;br /&gt;
&lt;br /&gt;
===Search Order===&lt;br /&gt;
Simply by changing the search order, a great reduction of work can be achieved.  The class names sadly give away the approaches.  &lt;br /&gt;
&lt;br /&gt;
Ask yourself: &lt;br /&gt;
* Which algorithm will perform better and why?&lt;br /&gt;
* What properties make a square &amp;quot;filled&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|RowMajorSquareSearchAlgorithm|selectNextUnfilledSquare|sudoku.lab}}&lt;br /&gt;
{{Sequential|public Square selectNextUnfilledSquare(SudokuPuzzle puzzle)}}&lt;br /&gt;
&lt;br /&gt;
Simply run through the &amp;lt;code&amp;gt;Square.values()&amp;lt;/code&amp;gt; which will iterate through squares going down the row (A1, A2, A3, ...). Make sure not to return squares that have already been filled.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|FewestOptionsFirstSquareSearchAlgorithm|selectNextUnfilledSquare|sudoku.lab}}&lt;br /&gt;
{{Sequential|public Square selectNextUnfilledSquare(SudokuPuzzle puzzle)}}&lt;br /&gt;
&lt;br /&gt;
Go through every square by calling &amp;lt;code&amp;gt;Square.values()&amp;lt;/code&amp;gt;, find a square that is (1) not already filled, and (2) has the minimal number of possible options among all the squares, and return that square.&lt;br /&gt;
&lt;br /&gt;
===Solver===&lt;br /&gt;
This part of the assignment is also similar to its n-queens counterpart. Searching for solutions like sudoku can be done in parallel without the need to finish at each level.  As such, &amp;lt;code&amp;gt;forasync&amp;lt;/code&amp;gt; is preferable to &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;.  However:&lt;br /&gt;
&lt;br /&gt;
{{Warning|Ensure that you complete all of your tasks by enclosing them all in a &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelSudoku|solve&amp;lt;br&amp;gt;solveKernel|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ImmutableSudokuPuzzle solve(ImmutableSudokuPuzzle puzzle, SquareSearchAlgorithm squareSearchAlgorithm)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void solveKernel(MutableObject&amp;lt;ImmutableSudokuPuzzle&amp;gt; solution, ImmutableSudokuPuzzle puzzle, SquareSearchAlgorithm squareSearchAlgorithm)}}&lt;br /&gt;
&lt;br /&gt;
====Tips====&lt;br /&gt;
*Make sure your solver uses the generic SquareSearchAlgorithm so that it works with both versions of the search ordering.&lt;br /&gt;
*Just like n-queens, your &amp;lt;code&amp;gt;solveKernel&amp;lt;/code&amp;gt; is the recursive method that will be called in the solve method. Again, watch where you put your &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.&lt;br /&gt;
*In your &amp;lt;code&amp;gt;solveKernel&amp;lt;/code&amp;gt; method, you should use the given search algorithm (row major or fewest options first) to select which square you will fill. After selecting a square, you should recursively call the kernel to check every viable option in the context of the puzzle. If there are no more unfilled squares, you should set the value of the solution to the finished puzzle and exit out of the recursion.&lt;br /&gt;
&lt;br /&gt;
===Constraint Propagator===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultConstraintPropagator|createOptionSetsFromGivens&amp;lt;br&amp;gt;createNextOptionSets&amp;lt;br&amp;gt;assign&amp;lt;br&amp;gt;eliminate|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
You will need to implement two public methods to satisfy the ConstraintPropagator interface: &amp;lt;code&amp;gt;createOptionSetsFromGivens&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;createNextOptionSets&amp;lt;/code&amp;gt;.  Each of these two methods will be invoked from a different constructor in the [[#DefaultImmutableSudokuPuzzle]] class.  It should be relatively obvious which one goes with which based on the parameters.&lt;br /&gt;
&lt;br /&gt;
{{Warning| Resist the temptation to perform the constraint propagation in these public methods.  Get things set up and then get your private method(s) to work for you.}}&lt;br /&gt;
&lt;br /&gt;
====createOptionSetsFromGivens====&lt;br /&gt;
{{Sequential|public Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; createOptionSetsFromGivens(String givens)}}&lt;br /&gt;
&lt;br /&gt;
This method will be invoked when you have loaded a new puzzle.  Whether it is from the newspaper, or your airline magazine, or Dr. Arto Inkala there is a set of givens the puzzle creator has provided. That string of givens is parsed into a double array of integers that aligns with the Sudoku board (values[0][0] is the top left corner of the board). If a specific spot of the board wasn't given in the input, it will be put into values[][] as 0.  &lt;br /&gt;
&lt;br /&gt;
A good approach here is to start of by initializing all of the squares to all the options (1 through 9) whether or not the square has a given value.  &lt;br /&gt;
&lt;br /&gt;
Once that is complete go through the givens and get your private method(s) to work for you.  Note: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#valueOf-int-int- Square.valueOf(row, column)] should be useful here.&lt;br /&gt;
&lt;br /&gt;
====createNextOptionSets====&lt;br /&gt;
{{Sequential|public Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; createNextOptionSets(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; otherOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This method should be invoked when you are searching for the solution in your solver.  Much like when you need to create a new copy of the board every time you make a decision in the n-queens search so too will you need to create a new copy of your sudoku board every time you make a decision in your backtracking search.&lt;br /&gt;
&lt;br /&gt;
Make sure to use the &amp;lt;code&amp;gt;SquareToOptionSetMapUtils.deepCopyOf&amp;lt;/code&amp;gt; method and refrain from mutating the incoming parameter &amp;lt;code&amp;gt;otherOptionSets&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
As warned above, do not actually do any of the constraint propagation in this method. Simply get the copy of the options set, then send it through your private &amp;lt;code&amp;gt;assign&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;eliminate&amp;lt;/code&amp;gt; to update the copy to be correct before returning it.&lt;br /&gt;
&lt;br /&gt;
{{Tip |If you have two Lists, &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;, and you set &amp;lt;code&amp;gt;a &amp;lt;nowiki&amp;gt;=&amp;lt;/nowiki&amp;gt; b&amp;lt;/code&amp;gt;, then any changes you make to &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; will also be made to &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;. Both variables reference the same objects; they are not copies.}}&lt;br /&gt;
&lt;br /&gt;
====Assign and Eliminate====&lt;br /&gt;
&lt;br /&gt;
[http://norvig.com/sudoku.html Peter Norvig's Essay] is very helpful here.  We have adopted his terms, but challenge yourself to complete this section without simply translating his pseudocode.&lt;br /&gt;
&lt;br /&gt;
To simplify things a bit, we have elected to not short circuit when a 0 option square is found (relying on the search ordering to take care of that for us).&lt;br /&gt;
&lt;br /&gt;
It is up to you how to utilize these two methods. The goal is to update the map that is passed in to reflect the &amp;quot;solving&amp;quot; of a square. For example, if assign is called on square A1 for the value 1, the map that is returned should link the square A1 to a list containing just the value 1 ([1]). Furthermore, any square that is a peer of A1 (ex. B1), should not have the value 1 in its set in the map. &lt;br /&gt;
&lt;br /&gt;
But in solving Sudoku, there are some strategies that we can rely on to more efficiently complete the puzzle. The first one, and required in order to finish this lab, is ''Peer Elimination Constraint Propagation'' (rule 1 in the Norvig essay). The rule is as follows: &amp;quot;If a square has only one possible value, then eliminate that value from the square's peers.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Let's very slowly walk through a example of this propagation in detail to make it more clear what we are looking for. Start by looking at this nearly finished board:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
		|-&lt;br /&gt;
		! Board !! Info&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:PeerConstraint1.PNG|200px]]  || We can see that the red square (D1) has only one available option. At this point, let's say we call assign on the red square D1 for the value 1.&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:PeerConstraint3.PNG|200px]]  || As part of the assignment process, all the peers of red square D1 have the value 1 removed from their possibilities. In this example, yellow square, A1, is directly affected! After eliminating the alternative option, there is only one possible value yellow square A1 could be. This is where our constraint propagator needs to take the next step and treat yellow square A1 as assigned.&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:PeerConstraint4.PNG|200px]]  || This step right here (going from a small 7 to a big 7) is not actually something our program will do. In our implementation, '''having only one option in a square's set is equivalent to that square being &amp;quot;assigned&amp;quot; to that value'''. Because of this, you actually do not need to call assign again for yellow square A1.&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:PeerConstraint5.PNG|200px]]  || Now that yellow square A1 is known, the final step is to go through all of A1's peers (including green square C3) and remove the value 7. Note that now there is only one possible option left for green square C3. Your code should keep going, looking at all the peers of C3 and eliminating the value 1, and so on. Some puzzles can be completely solved using only Peer Elimination constraint propagation!&lt;br /&gt;
		|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
{{Sequential|private void assign(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; resultOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|If you are hitting a ConcurrentModificationException here, make sure to make a copy of the optionsSet you are iterating over.  Use your local utility copyOf method. }}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	SortedSet&amp;lt;Integer&amp;gt; copy = copyOf(optionSet);&lt;br /&gt;
	for (int otherValue : copy) {&lt;br /&gt;
		...&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private void eliminate(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; resultOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
====(Optional) Unit Constraint Propagation====&lt;br /&gt;
The second rule in [http://norvig.com/sudoku.html Peter Norvig's Essay] is Unit Constraint Propagation: &amp;quot;If a unit has only one possible place for a value, then put the value there&amp;quot;. This propagation rule is it bit more challenging to put into code, but doing so can make even the hardest of Sudoku puzzles fall nice and quickly. To complete this bonus part of the lab, simply update your &amp;lt;code&amp;gt;assign&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;eliminate&amp;lt;/code&amp;gt; methods to do unit constraint propagation (don't remove the old propagation rule!). After assigning a square, you'll have to look at the new options set to see if any unit (a single row, column, or box) has only one unassigned square that is a possibility for any value. We encourage you to think of a solution on your own! Below is a example of unit constraint propagation.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
		|-&lt;br /&gt;
		! Board !! Info&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:UnitConstraint1.PNG|200px]]  || We can see that the red square (E1) has only one available option. At this point, let's say we call assign on the red square E1 for the value 6.&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:UnitConstraint2.PNG|200px]]  || Due to the assignment of red square E1, the value of 6 is eliminated from its peer, yellow square A1. &lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:UnitConstraint3.PNG|200px]]  || Our Peer Elimination constraint propagation will treat yellow square A1 as if it has been assigned. Unfortunately, eliminating the value 9 from the peers doesn't open up any new opportunities for solving squares. This is where unit constraint propagation kicks in. Of the three unassigned squares in the top left box unit, 6 is only a valid option in the green square, C3. Even though green square C3 has multiple possible options remaining, we know that it '''must''' be 6, and should assign it as such&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:UnitConstraint4.PNG|200px]]  || Once green square C3 has been assigned (all other options are removed), we should make sure that all of C3's peers have 6 removed from their options. And keep an eye out for any new squares that we now know due to the two propagation rules! With both peer elimination and unit constraint propagation, we can solve a large quantity of Sudoku puzzles without needing any backtracking recursion&lt;br /&gt;
		|}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
===N-Queens===&lt;br /&gt;
{{Viz|NQueensVizApp|nqueens.viz.solution}}&lt;br /&gt;
&lt;br /&gt;
[[File:NQueensViz.png]]&lt;br /&gt;
&lt;br /&gt;
===Sudoku===&lt;br /&gt;
{{Viz|SudokuSolutionApp|sudoku.viz.solution}}&lt;br /&gt;
&lt;br /&gt;
[[File:SudokuViz.png]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|BacktrackTestSuite|backtrack.lab}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|NQueensTestSuite|nqueens.lab}}&lt;br /&gt;
{{TestSuite|SudokuTestSuite|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
===(Optional) Challenge Unit Constraint Propagation===&lt;br /&gt;
{{TestSuite|ChallengeSudokuTestSuite|sudoku.challenge}}&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
N-Queens subtotal: 35&lt;br /&gt;
* Correct DefaultImmutableQueenLocations (5)&lt;br /&gt;
* Correct SequentialNQueens (10)&lt;br /&gt;
* Correct ParallelNQueens (10)&lt;br /&gt;
* Parallel ParallelNQueens (10)&lt;br /&gt;
&lt;br /&gt;
Sudoku subtotal: 55&lt;br /&gt;
* Correct DefaultImmutableSudokuPuzzle (5)&lt;br /&gt;
* Correct ContraintPropagator (15)&lt;br /&gt;
* Correct RowMajorSquareSearchAlgorithm (5)&lt;br /&gt;
* Correct FewestOtionsFirstSquareSearchAlgorithm (10)&lt;br /&gt;
* Correct ParallelSudoku (10)&lt;br /&gt;
* Parallel ParallelSudoku (10)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=N-Queens/Sudoku_Assignment&amp;diff=2198</id>
		<title>N-Queens/Sudoku Assignment</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=N-Queens/Sudoku_Assignment&amp;diff=2198"/>
		<updated>2018-07-24T05:32:40Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Not everything in the world should be divided and conquered.  Backtracking is a powerful technique which can be readily parallelized.  We will gain experience with backtracking by solving the N-Queens problem and Sudoku in parallel.&lt;br /&gt;
&lt;br /&gt;
N-Queens in particular can be used to explain the call stack as the chessboard *IS* the call stack.  Whoa.&lt;br /&gt;
&lt;br /&gt;
In this assignment, you will implement solutions to both the n-queens and Sudoku problems.&lt;br /&gt;
&lt;br /&gt;
=N-Queens=&lt;br /&gt;
&lt;br /&gt;
[[File:SolvedNQueens8.PNG|250px|thumb|Example solution of N-Queens when n equals 8]]&lt;br /&gt;
&lt;br /&gt;
==Background==&lt;br /&gt;
The n-queens problem is a fundamental coding puzzle which asks: how can N queens be placed on an NxN chessboard so that they cannot attack each other? In chess, a queen can move horizontally, vertically, and diagonally across the board. Thus, to solve the n-queens problem, we must effectively figure out how to place the queens in such a way that no two of them occupy the same row, column, or diagonal. We will be building a method that finds the total number of solutions for n-queens for any given n.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Roadmap to Victory==&lt;br /&gt;
#DefaultImmutableQueens&lt;br /&gt;
#QueenLocationsUtils&lt;br /&gt;
#SequentialNQueens&lt;br /&gt;
#ParallelNQueens&lt;br /&gt;
&lt;br /&gt;
==Code To Implement==&lt;br /&gt;
Before coding anything, take a look at the javadocs to see what everything does and what you will need to implement.&lt;br /&gt;
===Sequential Solution===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int countSolutions(MutableQueenLocations queenLocations) {&lt;br /&gt;
		MutableInt count = new MutableInt(0);&lt;br /&gt;
		placeQueenInRow(count, queenLocations, 0);&lt;br /&gt;
		return count.intValue();&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SequentialNQueens|placeQueenInRow|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void placeQueenInRow(MutableInt count, MutableQueenLocations queenLocations, int row)}}&lt;br /&gt;
&lt;br /&gt;
===Parallel Solution===&lt;br /&gt;
====Board State====&lt;br /&gt;
Investigate &amp;lt;code&amp;gt;DefaultMutableQueenLocations&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;AbstractQueenLocations&amp;lt;/code&amp;gt; for clues on how to implement &amp;lt;code&amp;gt;DefaultImmutableQueenLocations&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultImmutableQueenLocations|createNext&amp;lt;br&amp;gt;getColumnOfQueenInRow&amp;lt;br&amp;gt;getRowCount&amp;lt;br&amp;gt;getBoardSize|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public DefaultImmutableQueenLocations createNext(int column)}}&lt;br /&gt;
&lt;br /&gt;
There are two constructors for this class.  [https://www.cse.wustl.edu/~cosgroved/courses/cse231/curent/apidocs/nqueens/lab/DefaultImmutableQueenLocations.html#DefaultImmutableQueenLocations-int- A public one which creates a fresh new board state with no queens yet placed.] and a private one which creates a new board with the state of a given board which is further constrained by a new queen in the next row.  You need to create a new instance using one of these two constructors.  Which one is it? &lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getColumnOfQueenInRow(int row)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getRowCount()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getBoardSize()}}&lt;br /&gt;
&lt;br /&gt;
The three methods above can all be done in just one line. Don't make things too complicated! Note that we will refer to the standard 8x8 chessboard's size as 8 and not 64.&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public boolean isNextRowThreatFree(int column)}}&lt;br /&gt;
&lt;br /&gt;
Do not feel compelled to build this method from scratch.  Investigate your super class for a utility method that will be helpful. &lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/nqueens/core/AbstractQueenLocations.html#isCandidateThreatFree-int-int- isCandidateThreatFree(row, candidateColumn)]&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Board Utils====&lt;br /&gt;
This class will provide methods that will speed up our implementation of the parallel solution in the final step.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|QueenLocationsUtils|getCandidateColumns&amp;lt;br&amp;gt;getCandidateColumnsForNextRow|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential| public static Collection&amp;lt;Integer&amp;gt; getCandidateColumns(QueenLocations queenLocations, int row)}}&lt;br /&gt;
&lt;br /&gt;
This method should find all the columns in the given row that a queen could be placed, and return them in a single collection (ex. LinkedList). Don't forget to utilize some of the methods you just completed in &amp;lt;code&amp;gt;DefaultImmutableQueensLocation&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential| public static Collection&amp;lt;Integer&amp;gt; getCandidateColumnsForNextRow(ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
Nice and simple, don't overthink it! Just use methods you've already written to do all the work.&lt;br /&gt;
&lt;br /&gt;
====ParallelNQueens====&lt;br /&gt;
Searching for solutions like n-queens can be done in parallel without the need to finish at each level.  As such, &amp;lt;code&amp;gt;forasync&amp;lt;/code&amp;gt; is preferable to &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;.  However:&lt;br /&gt;
&lt;br /&gt;
{{Warning|Ensure that you complete all of your tasks by enclosing them all in a &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelNQueens|placeQueenInRow&amp;lt;br&amp;gt;countSolutions|nqueens.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static int countSolutions(ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|FinishAccumulators must be registered with their finish statement}}&lt;br /&gt;
&lt;br /&gt;
Instead of using a MutableInt in order to count the number of solutions we have found, we want to use a Finish Accumulator. Refer to the [[Syntax_of_231#Finish_Accumulators|syntax page]] in order to see the syntax for properly setting up the accumulator.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void placeQueenInRow(FinishAccumulator&amp;lt;Integer&amp;gt; acc, ImmutableQueenLocations queenLocations)}}&lt;br /&gt;
&lt;br /&gt;
Make sure you look at the Sequential N-Queens solution if you need ideas on how to approach the algorithm.&lt;br /&gt;
&lt;br /&gt;
==Tips==&lt;br /&gt;
*As &amp;lt;code&amp;gt;ImmutableQueenLocations&amp;lt;/code&amp;gt; is immutable, you will need to create a new instance of the object whenever you move on from one row to the next. This is where &amp;lt;code&amp;gt;createNext&amp;lt;/code&amp;gt; comes in, along with the private constructor of this class.&lt;br /&gt;
*The &amp;lt;code&amp;gt;isNextRowThreatFree&amp;lt;/code&amp;gt; method can easily be completed with a method in &amp;lt;code&amp;gt;AbstractQueenLocations&amp;lt;/code&amp;gt;. Refer to that for help.&lt;br /&gt;
*The sequential solution uses &amp;lt;code&amp;gt;MutableQueenLocations&amp;lt;/code&amp;gt; while the parallel solution uses your implementation of &amp;lt;code&amp;gt;ImmutableQueenLocations&amp;lt;/code&amp;gt;. Be careful to use the correct &amp;lt;code&amp;gt;QueenLocations&amp;lt;/code&amp;gt; implementation.&lt;br /&gt;
*As the name suggests, &amp;lt;code&amp;gt;placeQueenInRow&amp;lt;/code&amp;gt; will go through the columns of the given row to check if a queen can fit in that location. If it can, it will set that value in &amp;lt;code&amp;gt;MutableQueenLocations&amp;lt;/code&amp;gt;. If the examined row is that last row of the board, you have found one valid solution to the n-queens problem. Update the correct parameter accordingly. Otherwise, recurse and keep going until you reach the last row.&lt;br /&gt;
*For the parallel implementation of &amp;lt;code&amp;gt;placeQueenInRow&amp;lt;/code&amp;gt;, we are using the &amp;quot;one-finish&amp;quot; pattern. Do not call &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt; in the recursive method.&lt;br /&gt;
*Go check out the [[Syntax_of_231#Finish_Accumulators|syntax page]] if you have questions on how to set up the Finish Accumulator&lt;br /&gt;
&lt;br /&gt;
=Sudoku=&lt;br /&gt;
==Background==&lt;br /&gt;
[[File:BasicSudoku.PNG|thumb]]&lt;br /&gt;
We will be using a similar algorithm to solve a Sudoku puzzle. For those not familiar, a Sudoku puzzle is composed of a 9-by-9 grid of squares. This grid is also divided into 9 large boxes, each of which is a 3-by-3 of the smaller squares. In a completed puzzle, each of the smaller squares contains a single number from 1 to 9 (inclusive). However, if a square contains a given number, that same number cannot be anywhere else in the same row, column, or box. Thus, for Sudoku, we are given an incomplete board and must fill in the remaining squares while meeting these requirements.&lt;br /&gt;
&lt;br /&gt;
Sudoku is another problem well solved by backtracking.  Check the understanding you gained of backtracking with N-Queens by challenging yourself to solve Sudoku's solver without assistance. The game of Sudoku is bit more complex though than N-Queens, and there are more strategies we can do than just backtracking in order to speed up our solution. To make this assignment more compelling, you will also do search orderings and constraint propagation. &lt;br /&gt;
&lt;br /&gt;
Read [http://norvig.com/sudoku.html Peter Norvig's Essay] before you begin coding. It will cover everything related to the Sudoku problem itself and how one can design a solution for it.&lt;br /&gt;
&lt;br /&gt;
==Roadmap to Victory==&lt;br /&gt;
There isn't one easiest path through the required files. Some classes utilize methods written in other files, so some students may take a the path such that they will only call methods that are provided or have already implemented. For other students, it might be conceptually easier to start with &amp;lt;code&amp;gt;ParallelSudoku.java&amp;lt;/code&amp;gt;, since this class closest resembles the work you just did in n-queens. Below is one path that we recommend. In this path, you will have to call the constraint propagator in the Immutable Puzzle before completing the actual propagator, but aside from that most methods build on top of one another. In summary, you can work on these classes in whatever order makes the most sense for you personally.&lt;br /&gt;
#DefaultImmutableSudokuPuzzle&lt;br /&gt;
#RowMajorSquareSearchAlgorithm&lt;br /&gt;
#FewestOptionsFirstSquareSearchAlgorithm&lt;br /&gt;
#ParallelSudoku&lt;br /&gt;
#DefaultConstraintPropagator&lt;br /&gt;
#(Optional Challenge) Add Unit Constraint Propagation to DefaultConstraintPropagator&lt;br /&gt;
&lt;br /&gt;
==Code To Investigate==&lt;br /&gt;
enum [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html Square]&lt;br /&gt;
:Collection&amp;lt;Square&amp;gt; [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#getPeers-- getPeers()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#valueOf-int-int- valueOf(row, column)]&lt;br /&gt;
:all [https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html enums] have a [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#values-- values()] method&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Units.html Units]&lt;br /&gt;
:public static Iterable&amp;lt;Collection&amp;lt;Square&amp;gt;&amp;gt; [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Units.html#allUnits-- allUnits()]&lt;br /&gt;
&lt;br /&gt;
interface [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/ConstraintPropagator.html ConstraintPropagator] extends AbstractSet&amp;lt;Integer&amp;gt; implements SortedSet&amp;lt;Integer&amp;gt;&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html OptionSet]&lt;br /&gt;
:public static OptionSet [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html#createAllOptions-- createAllOptions()]&lt;br /&gt;
:public static OptionSet [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/OptionSet.html#createSingleOption-- createSingleOption(int option)]&lt;br /&gt;
&lt;br /&gt;
class [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/SquareToOptionSetMapUtils.html SquareToOptionSetMapUtils]&lt;br /&gt;
:public static Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; deepCopyOf(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; other)&lt;br /&gt;
&lt;br /&gt;
==Code To Implement==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Puzzle===&lt;br /&gt;
As the name suggests, &amp;lt;code&amp;gt;ImmutableSudokuPuzzle&amp;lt;/code&amp;gt; is immutable, and you will need to create a new instance of the object whenever you move on from one square to the next. This is analogous to the work you did for [[#NQueens]].&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultImmutableSudokuPuzzle|constructors&amp;lt;br&amp;gt;createNext&amp;lt;br&amp;gt;getValue&amp;lt;br&amp;gt;getOptions|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public DefaultImmutableSudokuPuzzle(ConstraintPropagator constraintPropagator, String givens)}}&lt;br /&gt;
&lt;br /&gt;
This constructor creates a puzzle constrained to an initial set of givens.  You can think of the givens as the original values provided by the newspaper or airline magazine or puzzle book or whatever.&lt;br /&gt;
&lt;br /&gt;
You will leverage the constraintPropagator to build your map of option sets.&lt;br /&gt;
&lt;br /&gt;
{{Tip| To quickly make a map containing each possible Square, use &amp;lt;code&amp;gt;new EnumMap&amp;lt;&amp;gt;(Square.class)&amp;lt;/code&amp;gt;}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private DefaultImmutableSudokuPuzzle(DefaultImmutableSudokuPuzzle other, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This constructor takes a given previous puzzle and a square value to create a new further constrained puzzle.&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public ImmutableSudokuPuzzle createNext(Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This method should create a new puzzle instance using one of the constructors.  Which one is it?&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int getValue(Square square)}}&lt;br /&gt;
&lt;br /&gt;
Based on the state of the board, return the value of a given square if it is known.  Otherwise, return 0.&lt;br /&gt;
&lt;br /&gt;
How do we determine if a value for a given square is &amp;quot;known&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public SortedSet&amp;lt;Integer&amp;gt; getOptions(Square square)}}&lt;br /&gt;
&lt;br /&gt;
Based on the state of the board, return the candidate values for a given square.&lt;br /&gt;
&lt;br /&gt;
===Search Order===&lt;br /&gt;
Simply by changing the search order, a great reduction of work can be achieved.  The class names sadly give away the approaches.  &lt;br /&gt;
&lt;br /&gt;
Ask yourself: &lt;br /&gt;
* Which algorithm will perform better and why?&lt;br /&gt;
* What properties make a square &amp;quot;filled&amp;quot;?&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|RowMajorSquareSearchAlgorithm|selectNextUnfilledSquare|sudoku.lab}}&lt;br /&gt;
{{Sequential|public Square selectNextUnfilledSquare(SudokuPuzzle puzzle)}}&lt;br /&gt;
&lt;br /&gt;
Simply run through the &amp;lt;code&amp;gt;Square.values()&amp;lt;/code&amp;gt; which will iterate through squares going down the row (A1, A2, A3, ...). Make sure not to return squares that have already been filled.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|FewestOptionsFirstSquareSearchAlgorithm|selectNextUnfilledSquare|sudoku.lab}}&lt;br /&gt;
{{Sequential|public Square selectNextUnfilledSquare(SudokuPuzzle puzzle)}}&lt;br /&gt;
&lt;br /&gt;
Go through every square by calling &amp;lt;code&amp;gt;Square.values()&amp;lt;/code&amp;gt;, find a square that is (1) not already filled, and (2) has the minimal number of possible options among all the squares, and return that square.&lt;br /&gt;
&lt;br /&gt;
===Solver===&lt;br /&gt;
This part of the assignment is also similar to its n-queens counterpart. Searching for solutions like sudoku can be done in parallel without the need to finish at each level.  As such, &amp;lt;code&amp;gt;forasync&amp;lt;/code&amp;gt; is preferable to &amp;lt;code&amp;gt;forall&amp;lt;/code&amp;gt;.  However:&lt;br /&gt;
&lt;br /&gt;
{{Warning|Ensure that you complete all of your tasks by enclosing them all in a &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.}}&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ParallelSudoku|solve&amp;lt;br&amp;gt;solveKernel|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public static ImmutableSudokuPuzzle solve(ImmutableSudokuPuzzle puzzle, SquareSearchAlgorithm squareSearchAlgorithm)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void solveKernel(MutableObject&amp;lt;ImmutableSudokuPuzzle&amp;gt; solution, ImmutableSudokuPuzzle puzzle, SquareSearchAlgorithm squareSearchAlgorithm)}}&lt;br /&gt;
&lt;br /&gt;
====Tips====&lt;br /&gt;
*Make sure your solver uses the generic SquareSearchAlgorithm so that it works with both versions of the search ordering.&lt;br /&gt;
*Just like n-queens, your &amp;lt;code&amp;gt;solveKernel&amp;lt;/code&amp;gt; is the recursive method that will be called in the solve method. Again, watch where you put your &amp;lt;code&amp;gt;finish&amp;lt;/code&amp;gt;.&lt;br /&gt;
*In your &amp;lt;code&amp;gt;solveKernel&amp;lt;/code&amp;gt; method, you should use the given search algorithm (row major or fewest options first) to select which square you will fill. After selecting a square, you should recursively call the kernel to check every viable option in the context of the puzzle. If there are no more unfilled squares, you should set the value of the solution to the finished puzzle and exit out of the recursion.&lt;br /&gt;
&lt;br /&gt;
===Constraint Propagator===&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|DefaultConstraintPropagator|createOptionSetsFromGivens&amp;lt;br&amp;gt;createNextOptionSets&amp;lt;br&amp;gt;assign&amp;lt;br&amp;gt;eliminate|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
You will need to implement two public methods to satisfy the ConstraintPropagator interface: &amp;lt;code&amp;gt;createOptionSetsFromGivens&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;createNextOptionSets&amp;lt;/code&amp;gt;.  Each of these two methods will be invoked from a different constructor in the [[#DefaultImmutableSudokuPuzzle]] class.  It should be relatively obvious which one goes with which based on the parameters.&lt;br /&gt;
&lt;br /&gt;
{{Warning| Resist the temptation to perform the constraint propagation in these public methods.  Get things set up and then get your private method(s) to work for you.}}&lt;br /&gt;
&lt;br /&gt;
====createOptionSetsFromGivens====&lt;br /&gt;
{{Sequential|public Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; createOptionSetsFromGivens(String givens)}}&lt;br /&gt;
&lt;br /&gt;
This method will be invoked when you have loaded a new puzzle.  Whether it is from the newspaper, or your airline magazine, or Dr. Arto Inkala there is a set of givens the puzzle creator has provided. That string of givens is parsed into a double array of integers that aligns with the Sudoku board (values[0][0] is the top left corner of the board). If a specific spot of the board wasn't given in the input, it will be put into values[][] as 0.  &lt;br /&gt;
&lt;br /&gt;
A good approach here is to start of by initializing all of the squares to all the options (1 through 9) whether or not the square has a given value.  &lt;br /&gt;
&lt;br /&gt;
Once that is complete go through the givens and get your private method(s) to work for you.  Note: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sudoku/core/Square.html#valueOf-int-int- Square.valueOf(row, column)] should be useful here.&lt;br /&gt;
&lt;br /&gt;
====createNextOptionSets====&lt;br /&gt;
{{Sequential|public Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; createNextOptionSets(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; otherOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
This method should be invoked when you are searching for the solution in your solver.  Much like when you need to create a new copy of the board every time you make a decision in the n-queens search so too will you need to create a new copy of your sudoku board every time you make a decision in your backtracking search.&lt;br /&gt;
&lt;br /&gt;
Make sure to use the &amp;lt;code&amp;gt;SquareToOptionSetMapUtils.deepCopyOf&amp;lt;/code&amp;gt; method and refrain from mutating the incoming parameter &amp;lt;code&amp;gt;otherOptionSets&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
As warned above, do not actually do any of the constraint propagation in this method. Simply get the copy of the options set, then send it through your private &amp;lt;code&amp;gt;assign&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;eliminate&amp;lt;/code&amp;gt; to update the copy to be correct before returning it.&lt;br /&gt;
&lt;br /&gt;
{{Tip |If you have two Lists, &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;, and you set &amp;lt;code&amp;gt;a &amp;lt;nowiki&amp;gt;=&amp;lt;/nowiki&amp;gt; b&amp;lt;/code&amp;gt;, then any changes you make to &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; will also be made to &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;. Both variables reference the same objects; they are not copies.}}&lt;br /&gt;
&lt;br /&gt;
====Assign and Eliminate====&lt;br /&gt;
&lt;br /&gt;
[http://norvig.com/sudoku.html Peter Norvig's Essay] is very helpful here.  We have adopted his terms, but challenge yourself to complete this section without simply translating his pseudocode.&lt;br /&gt;
&lt;br /&gt;
To simplify things a bit, we have elected to not short circuit when a 0 option square is found (relying on the search ordering to take care of that for us).&lt;br /&gt;
&lt;br /&gt;
It is up to you how to utilize these two methods. The goal is to update the map that is passed in to reflect the &amp;quot;solving&amp;quot; of a square. For example, if assign is called on square A1 for the value 1, the map that is returned should link the square A1 to a list containing just the value 1 ([1]). Furthermore, any square that is a peer of A1 (ex. B1), should not have the value 1 in its set in the map. &lt;br /&gt;
&lt;br /&gt;
But in solving Sudoku, there are some strategies that we can rely on to more efficiently complete the puzzle. The first one, and required in order to finish this lab, is ''Peer Elimination Constraint Propagation'' (rule 1 in the Norvig essay). The rule is as follows: &amp;quot;If a square has only one possible value, then eliminate that value from the square's peers.&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Let's very slowly walk through a example of this propagation in detail to make it more clear what we are looking for. Start by looking at this nearly finished board:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
		|-&lt;br /&gt;
		! Board !! Info&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:PeerConstraint1.PNG|200px]]  || We can see that the red square (D1) has only one available option. At this point, let's say we call assign on the red square D1 for the value 1.&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:PeerConstraint3.PNG|200px]]  || As part of the assignment process, all the peers of red square D1 have the value 1 removed from their possibilities. In this example, yellow square, A1, is directly affected! After eliminating the alternative option, there is only one possible value yellow square A1 could be. This is where our constraint propagator needs to take the next step and treat yellow square A1 as assigned.&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:PeerConstraint4.PNG|200px]]  || This step right here (going from a small 7 to a big 7) is not actually something our program will do. In our implementation, '''having only one option in a square's set is equivalent to that square being &amp;quot;assigned&amp;quot; to that value'''. Because of this, you actually do not need to call assign again for yellow square A1.&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:PeerConstraint5.PNG|200px]]  || Now that yellow square A1 is known, the final step is to go through all of A1's peers (including green square C3) and remove the value 7. Note that now there is only one possible option left for green square C3. Your code should keep going, looking at all the peers of C3 and eliminating the value 1, and so on. Some puzzles can be completely solved using only Peer Elimination constraint propagation!&lt;br /&gt;
		|}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
{{Sequential|private void assign(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; resultOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|If you are hitting a ConcurrentModificationException here, make sure to make a copy of the optionsSet you are iterating over.  Use your local utility copyOf method. }}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	SortedSet&amp;lt;Integer&amp;gt; copy = copyOf(optionSet);&lt;br /&gt;
	for (int otherValue : copy) {&lt;br /&gt;
		...&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private void eliminate(Map&amp;lt;Square, SortedSet&amp;lt;Integer&amp;gt;&amp;gt; resultOptionSets, Square square, int value)}}&lt;br /&gt;
&lt;br /&gt;
====(Optional) Unit Constraint Propagation====&lt;br /&gt;
The second rule in [http://norvig.com/sudoku.html Peter Norvig's Essay] is Unit Constraint Propagation: &amp;quot;If a unit has only one possible place for a value, then put the value there&amp;quot;. This propagation rule is it bit more challenging to put into code, but doing so can make even the hardest of Sudoku puzzles fall nice and quickly. To complete this bonus part of the lab, simply update your &amp;lt;code&amp;gt;assign&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;eliminate&amp;lt;/code&amp;gt; methods to do unit constraint propagation (don't remove the old propagation rule!). After assigning a square, you'll have to look at the new options set to see if any unit (a single row, column, or box) has only one unassigned square that is a possibility for any value. We encourage you to think of a solution on your own! Below is a example of unit constraint propagation.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
		|-&lt;br /&gt;
		! Board !! Info&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:UnitConstraint1.PNG|200px]]  || We can see that the red square (E1) has only one available option. At this point, let's say we call assign on the red square E1 for the value 6.&lt;br /&gt;
		|-&lt;br /&gt;
		| [[File:UnitConstraint2.PNG|200px]]  || Due to the assignment of red square E1, the value of 6 is eliminated from its peer, yellow square A1. &lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:UnitConstraint3.PNG|200px]]  || Our Peer Elimination constraint propagation will treat yellow square A1 as if it has been assigned. Unfortunately, eliminating the value 9 from the peers doesn't open up any new opportunities for solving squares. This is where unit constraint propagation kicks in. Of the three unassigned squares in the top left box unit, 6 is only a valid option in the green square, C3. Even though green square C3 has multiple possible options remaining, we know that it '''must''' be 6, and should assign it as such&lt;br /&gt;
                |-&lt;br /&gt;
                | [[File:UnitConstraint4.PNG|200px]]  || Once green square C3 has been assigned (all other options are removed), we should make sure that all of C3's peers have 6 removed from their options. And keep an eye out for any new squares that we now know due to the two propagation rules! With both peer elimination and unit constraint propagation, we can solve a large quantity of Sudoku puzzles without needing any backtracking recursion&lt;br /&gt;
		|}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
===N-Queens===&lt;br /&gt;
{{Viz|NQueensVizApp|nqueens.viz.solution}}&lt;br /&gt;
&lt;br /&gt;
[[File:NQueensViz.png]]&lt;br /&gt;
&lt;br /&gt;
===Sudoku===&lt;br /&gt;
{{Viz|SudokuSolutionApp|sudoku.viz.solution}}&lt;br /&gt;
&lt;br /&gt;
[[File:SudokuViz.png]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|BacktrackTestSuite|backtrack.lab}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|NQueensTestSuite|nqueens.lab}}&lt;br /&gt;
{{TestSuite|SudokuTestSuite|sudoku.lab}}&lt;br /&gt;
&lt;br /&gt;
===(Optional) Challenge Unit Constraint Propagation===&lt;br /&gt;
{{TestSuite|ChallengeSudokuTestSuite|sudoku.challenge}}&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
N-Queens subtotal: 35&lt;br /&gt;
* Correct DefaultImmutableQueenLocations (5)&lt;br /&gt;
* Correct SequentialNQueens (10)&lt;br /&gt;
* Correct ParallelNQueens (10)&lt;br /&gt;
* Parallel ParallelNQueens (10)&lt;br /&gt;
&lt;br /&gt;
Sudoku subtotal: 55&lt;br /&gt;
* Correct DefaultImmutableSudokuPuzzle (5)&lt;br /&gt;
* Correct ContraintPropagator (15)&lt;br /&gt;
* Correct RowMajorSquareSearchAlgorithm (5)&lt;br /&gt;
* Correct FewestOtionsFirstSquareSearchAlgorithm (10)&lt;br /&gt;
* Correct ParallelSudoku (10)&lt;br /&gt;
* Parallel ParallelSudoku (10)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=LeggedRaces&amp;diff=2197</id>
		<title>LeggedRaces</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=LeggedRaces&amp;diff=2197"/>
		<updated>2018-07-24T05:31:45Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
In a legged race, a group of people must try to move forward as quickly as possible with their legs tied to each other. In other words, the group can only be as quick as its slowest link and they must try to move in unison. In many ways, this concept mirrors parallel phasers. In this studio, you will use phasers and forall loops in order to simulate a legged race.&lt;br /&gt;
&lt;br /&gt;
You will complete four methods that cover two different types of races. The first three versions are an &amp;quot;n+1 legged race&amp;quot;. This is where all participants are a part of the same group. Each person's legs are tied to their neighbors, and thus it is impossible for one person to take a second step before everyone else has taken their first step. The final method is a &amp;quot;3 legged race&amp;quot;. Participants have a partner who they are tied to and can continue to take steps as long as their partner is keeping up with them.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&amp;lt;youtube&amp;gt;acDrcvwvd8I&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Legged Races==&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/leggedrace/core/Participant.html interface Participant]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/leggedrace/core/Participant.html#takeStep-int- takeStep]&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html Java For Each Loop]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-T:A-edu.wustl.cse231s.v5.api.CheckedConsumer- forall]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#bulkRegister-int- bulkRegister]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndAwaitAdvance-- arriveAndAwaitAdvance]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
Here are some additional questions to help guide you down the right path &lt;br /&gt;
*What work does each task need to do?&lt;br /&gt;
*Upon what does each task depend?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
*What could have possibly been more important than adding a random stopping to tie their shoes animation to the visualization?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==SequentialLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SequentialLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, try to solve the problem sequentially. Your method should go through the array of participants and make each one takeStep until you do this for every stepIndex up until the stepCount for every participant.&lt;br /&gt;
&lt;br /&gt;
Hint: Basically, you will need two for loops. One that iterates up until the stepCount and another which goes through the array of participants.&lt;br /&gt;
&lt;br /&gt;
==ForallLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, the participants should all take each individual step in parallel.  However, the steps should be taken each in turn sequentially.  Think about where to place the forall loop so that the program only progresses to the next stepIndex after every participant has performed a takeStep with the current index value.&lt;br /&gt;
&lt;br /&gt;
==ForallPhasedLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallPhasedLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
[[File:phasedCompGraph.PNG | 400px]]&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
In this solution, you will flip your sequentialLoop/parallelLoop pattern into a parallelLoop/sequentialLoop pattern with a phaser. For this, there should only be one Phaser, which is bulk registered such that each participant can wait on the same Phaser. In order to simplify the code, look into [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndAwaitAdvance-- arriveAndAwaitAdvance()].&lt;br /&gt;
&lt;br /&gt;
==ForallPhasedPointToPointLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallPhasedPointToPointLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
[[File: phasedPoint2PointCompGraph.PNG | 400px]]&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|When you create an array, the contents will initially be null.}}&lt;br /&gt;
&lt;br /&gt;
This time, we want to simulate a 3-legged race with multiple teams participating. In this implementation, you will build on what you did with the forall implementation to incorporate an array of phasers. Start this off by instantiating an array of phasers. It is up to you to determine how many phasers you need in the array. There are multiple solutions that use different numbers of phasers. Think carefully about how you can have participants signal and wait on phasers in order to make sure no participant takes two steps before their partner catches up to them.&lt;br /&gt;
&lt;br /&gt;
Use provided &amp;lt;code&amp;gt;int getPartnerIndex(int)&amp;lt;/code&amp;gt; to find the partner for a participant.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;   	private static int getPartnerIndex(int index) {&lt;br /&gt;
          	boolean isOddIndex = (index&amp;amp;0x1) == 0x1;&lt;br /&gt;
          	if( isOddIndex ) {&lt;br /&gt;
                 	return index - 1;&lt;br /&gt;
          	} else {&lt;br /&gt;
                 	return index + 1;&lt;br /&gt;
          	}&lt;br /&gt;
   	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|LeggedRaceVisualizationApp|leggedrace.viz}}&lt;br /&gt;
&lt;br /&gt;
Click on the buttons on the right to visualize your solutions when you have implemented them. Here are examples of what the correct visualization should look like for each method.&lt;br /&gt;
&lt;br /&gt;
[[File:SequentialLeggedRaceGIF.gif|SequentialLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
[[File:ForAllLeggedRaceGIF.gif|ForallLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
[[File:ForAllPhasedLeggedRaceGIF.gif|ForallPhasedLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
[[File:ForAllPhasedP2PLeggedRaceGIF.gif|ForallPhasedPointToPointLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|LeggedRaceTestSuite|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
{{TestSuite|PartialCreditLeggedRaceTestSuite|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=LeggedRaces&amp;diff=2196</id>
		<title>LeggedRaces</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=LeggedRaces&amp;diff=2196"/>
		<updated>2018-07-24T05:28:29Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
In a legged race, a group of people must try to move forward as quickly as possible with their legs tied to each other. In other words, the group can only be as quick as its slowest link and they must try to move in unison. In many ways, this concept mirrors parallel phasers. In this studio, you will use phasers and forall loops in order to simulate a legged race.&lt;br /&gt;
&lt;br /&gt;
You will complete four methods that cover two different types of races. The first three versions are an &amp;quot;n+1 legged race&amp;quot;. This is where all participants are a part of the same group. Each person's legs are tied to their neighbors, and thus it is impossible for one person to take a second step before everyone else has taken their first step. The final method is a &amp;quot;3 legged race&amp;quot;. Participants have a partner who they are tied to and can continue to take steps as long as their partner is keeping up with them.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&amp;lt;youtube&amp;gt;acDrcvwvd8I&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
==Legged Races==&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/leggedrace/core/Participant.html interface Participant]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/leggedrace/core/Participant.html#takeStep-int- takeStep]&lt;br /&gt;
&lt;br /&gt;
==Looping==&lt;br /&gt;
[https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html Java For Loop]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html Java For Each Loop]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-T:A-edu.wustl.cse231s.v5.api.CheckedConsumer- forall]&lt;br /&gt;
&lt;br /&gt;
==Phasers==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser] ([http://www.baeldung.com/java-phaser Guide to the Java Phaser])&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#register-- register]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#bulkRegister-int- bulkRegister]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndAwaitAdvance-- arriveAndAwaitAdvance]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arrive-- arrive]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#awaitAdvance-int- awaitAdvance] use via PhaserUtils.awaitAdvanceForPhase(phaser, phase)&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html PhaserUtils]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/concurrent/PhaserUtils.html#awaitAdvanceForPhase-java.util.concurrent.Phaser-int- awaitAdvanceForPhase]&lt;br /&gt;
&lt;br /&gt;
If you are on or past the phase you want to await, then calling &amp;lt;code&amp;gt;phaser.awaitAdvance()&amp;lt;/code&amp;gt; directly is fine.  If you might be on a prior phase, then invoke &amp;lt;code&amp;gt;PhaserUtils.awaitAdvanceForPhase(phaser, phase)&amp;lt;/code&amp;gt;.  If in doubt, invoking awaitAdvanceForPhase is safer.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int awaitAdvanceForPhase(Phaser phaser, int phase) {&lt;br /&gt;
		return awaitAdvanceForPhase(phaser, phase, () -&amp;gt; Thread.yield());&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public static int awaitAdvanceForPhase(Phaser phaser, int phase, Runnable runnable) {&lt;br /&gt;
		while (true) {&lt;br /&gt;
			int currentPhase = phaser.awaitAdvance(phase);&lt;br /&gt;
			if (currentPhase &amp;lt; 0 || currentPhase &amp;gt; phase) {&lt;br /&gt;
				return currentPhase;&lt;br /&gt;
			} else {&lt;br /&gt;
				if (runnable != null) {&lt;br /&gt;
					runnable.run();&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Questions To Ask Yourself=&lt;br /&gt;
# What are my tasks?&lt;br /&gt;
# What work does each task need to do?&lt;br /&gt;
# Upon what does each task depend?  That is: what does each task have to wait for before it may proceed?&lt;br /&gt;
# What could have possibly been more important than adding a random stopping to tie their shoes animation to the visualization?&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==SequentialLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SequentialLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, try to solve the problem sequentially. Your method should go through the array of participants and make each one takeStep until you do this for every stepIndex up until the stepCount for every participant.&lt;br /&gt;
&lt;br /&gt;
Hint: Basically, you will need two for loops. One that iterates up until the stepCount and another which goes through the array of participants.&lt;br /&gt;
&lt;br /&gt;
==ForallLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, the participants should all take each individual step in parallel.  However, the steps should be taken each in turn sequentially.  Think about where to place the forall loop so that the program only progresses to the next stepIndex after every participant has performed a takeStep with the current index value.&lt;br /&gt;
&lt;br /&gt;
==ForallPhasedLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallPhasedLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
[[File:phasedCompGraph.PNG | 400px]]&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
In this solution, you will flip your sequentialLoop/parallelLoop pattern into a parallelLoop/sequentialLoop pattern with a phaser. For this, there should only be one Phaser, which is bulk registered such that each participant can wait on the same Phaser. In order to simplify the code, look into [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndAwaitAdvance-- arriveAndAwaitAdvance()].&lt;br /&gt;
&lt;br /&gt;
==ForallPhasedPointToPointLeggedRace==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallPhasedPointToPointLeggedRace|takeSteps|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
[[File: phasedPoint2PointCompGraph.PNG | 400px]]&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public void takeSteps(Participant[] participants, int stepCount)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|When you create an array, the contents will initially be null.}}&lt;br /&gt;
&lt;br /&gt;
This time, we want to simulate a 3-legged race with multiple teams participating. In this implementation, you will build on what you did with the forall implementation to incorporate an array of phasers. Start this off by instantiating an array of phasers. It is up to you to determine how many phasers you need in the array. There are multiple solutions that use different numbers of phasers. Think carefully about how you can have participants signal and wait on phasers in order to make sure no participant takes two steps before their partner catches up to them.&lt;br /&gt;
&lt;br /&gt;
Use provided &amp;lt;code&amp;gt;int getPartnerIndex(int)&amp;lt;/code&amp;gt; to find the partner for a participant.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;   	private static int getPartnerIndex(int index) {&lt;br /&gt;
          	boolean isOddIndex = (index&amp;amp;0x1) == 0x1;&lt;br /&gt;
          	if( isOddIndex ) {&lt;br /&gt;
                 	return index - 1;&lt;br /&gt;
          	} else {&lt;br /&gt;
                 	return index + 1;&lt;br /&gt;
          	}&lt;br /&gt;
   	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
{{Viz|LeggedRaceVisualizationApp|leggedrace.viz}}&lt;br /&gt;
&lt;br /&gt;
Click on the buttons on the right to visualize your solutions when you have implemented them. Here are examples of what the correct visualization should look like for each method.&lt;br /&gt;
&lt;br /&gt;
[[File:SequentialLeggedRaceGIF.gif|SequentialLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
[[File:ForAllLeggedRaceGIF.gif|ForallLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
[[File:ForAllPhasedLeggedRaceGIF.gif|ForallPhasedLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
[[File:ForAllPhasedP2PLeggedRaceGIF.gif|ForallPhasedPointToPointLeggedRace]]&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|LeggedRaceTestSuite|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
{{TestSuite|PartialCreditLeggedRaceTestSuite|leggedrace.studio}}&lt;br /&gt;
&lt;br /&gt;
When you are passing the tests and your visualization looks good, demo it to an instructor.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iterative_Averaging&amp;diff=2195</id>
		<title>Iterative Averaging</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iterative_Averaging&amp;diff=2195"/>
		<updated>2018-07-24T05:27:06Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Iterative Averaging is the process of updating an array to so that each index becomes the average of the indices one before and one after it. After repeating this for many iterations, the array may converge to one set of numbers. For example, when given the following array, we can perform iterations of this algorithm until the array eventually converges:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0.5 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0.25 || 0.5 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;\vdots&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0.1 || 0.2 || 0.3 || 0.4 || 0.5 || 0.6 || 0.7 || 0.8 || 0.9 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Note that the ends of the array remain the same value from the previous iteration. &lt;br /&gt;
&lt;br /&gt;
X10/Habanero like Phasers have been added to Java since JDK7.  We will gain some experience with using Phasers in a parallel for-loop context. Phasers allow us to change the structure of our loops and reduce overhead in the algorithm.&lt;br /&gt;
&lt;br /&gt;
For more information on the algorithm and how we can use Phasers to make it better, review [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/6349730bb2a149a0b33fa23db7afddee/13 Topic 3.5] from the RiceX course.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[[Reference_Page#Phasers|Check out the reference page on phasers]]&lt;br /&gt;
&lt;br /&gt;
[http://www.baeldung.com/java-phaser Guide to the Java Phaser]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#bulkRegister-int- bulkRegister]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndAwaitAdvance-- arriveAndAwaitAdvance]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndDeregister-- arriveAndDeregister] (note: not required for this studio, but good to know about.)&lt;br /&gt;
&lt;br /&gt;
{{warning | Our use of the forall loop with Phasers does not accurately convey their finicky nature.  More than other features, Phasers seem to require more care to get performance improvements. }}&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code to Investigate=&lt;br /&gt;
class AbstractSwappable&lt;br /&gt;
:getSrc()&lt;br /&gt;
:getDst()&lt;br /&gt;
:swap()&lt;br /&gt;
class SwappableDoubleArrays implements AbstractSwappable&lt;br /&gt;
:&amp;lt;code&amp;gt;new SwappableDoubleArrays(int registrations, double[] originalData)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequential Iterative Averaging==&lt;br /&gt;
{{CodeToInvestigate|SequentialIterativeAverager|iterativelyAverage|iterativeaveraging.demo}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public double[] iterativelyAverage(List&amp;lt;Slice&amp;lt;double[]&amp;gt;&amp;gt; slices, double[] originalArray, int iterationCount)}}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;SwappableDoubleArrays data = new SwappableDoubleArrays(1, originalArray);&lt;br /&gt;
	for (int iteration = 0; iteration &amp;lt; iterationCount; iteration++) {&lt;br /&gt;
		double[] arrayPrev = data.getSrc();&lt;br /&gt;
		double[] arrayNext = data.getDst();&lt;br /&gt;
		for (Slice&amp;lt;double[]&amp;gt; slice : slices) {&lt;br /&gt;
			for (int index = slice.getMinInclusive(); index &amp;lt; slice.getMaxExclusive(); index++) {&lt;br /&gt;
				arrayNext[index] = (arrayPrev[index - 1] + arrayPrev[index + 1]) * 0.5;&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
		data.swap();&lt;br /&gt;
	}&lt;br /&gt;
	return data.getSrc();&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is a demo of the Iterative Averaging algorithm done sequentially. Take a look at the code in your repo. Some important questions/notes to think about:&lt;br /&gt;
*What does the &amp;lt;code&amp;gt;SwappableDoubleArrays&amp;lt;/code&amp;gt; do and why is it useful in this algoritm?&lt;br /&gt;
*Why is &amp;lt;code&amp;gt;data.getSrc()&amp;lt;/code&amp;gt; returned and not &amp;lt;code&amp;gt;data.getDst()&amp;lt;/code&amp;gt;?&lt;br /&gt;
*Note that none of the slices contain the indices 0 or originalArray.length. If it did, the code would throw an OutOfBoundsException&lt;br /&gt;
&lt;br /&gt;
==PageRank==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;PR(u) = \sum_{v \in B_u} \frac{PR(v)}{L(v)}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===parallel===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;for (int iteration : new IntegerRange(0, iterationCount)) {&lt;br /&gt;
	forall(slices, (slice) -&amp;gt; {&lt;br /&gt;
		PageRank[] arrayPrev = ((iteration &amp;amp; 1) == 0) ? a : b;&lt;br /&gt;
		PageRank[] arrayNext = ((iteration &amp;amp; 1) == 0) ? b : a;&lt;br /&gt;
		slice.forEachIndex((index) -&amp;gt; {&lt;br /&gt;
                 	arrayNext[index] = calculateNextRank(index, arrayPrev);&lt;br /&gt;
          	});&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===parallel phased===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(slices.size());&lt;br /&gt;
forall(slices, (slice) -&amp;gt; {&lt;br /&gt;
	for (int iteration : new IntegerRange(0, iterationCount)) {&lt;br /&gt;
		PageRank[] arrayPrev = ((iteration &amp;amp; 1) == 0) ? a : b;&lt;br /&gt;
		PageRank[] arrayNext = ((iteration &amp;amp; 1) == 0) ? b : a;&lt;br /&gt;
		slice.forEachIndex((index) -&amp;gt; {&lt;br /&gt;
                 	arrayNext[index] = calculateNextRank(index, arrayPrev);&lt;br /&gt;
          	});&lt;br /&gt;
		phaser.arriveAndAwaitAdvance();&lt;br /&gt;
	}&lt;br /&gt;
	// note: arriveAndDeregister not required for this application&lt;br /&gt;
	phaser.arriveAndDeregister();&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
{{CodeToImplement|ForForallIterativeAverager|iterativelyAverage|iterativeaveraging.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[] iterativelyAverage(List&amp;lt;Slice&amp;lt;double[]&amp;gt;&amp;gt; slices, double[] originalArray, int iterationCount)}}&lt;br /&gt;
&lt;br /&gt;
For this method, you should not be using Phasers. Instead, implement a parallel version of the Iterative Averaging algorithm shown above sequentially. Make use of the SwappableDoubleArrays class. The return value should be the current version of the array after it has gone through the number of iterations passed in the method.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallForPhasedIterativeAverager|iterativelyAverage|iterativeaveraging.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[] iterativelyAverage(List&amp;lt;Slice&amp;lt;double[]&amp;gt;&amp;gt; slices, double[] originalArray, int iterationCount)}}&lt;br /&gt;
&lt;br /&gt;
Before you get started on this, make sure you review the [[Iterative Averaging#Background | Background section]] in order to understand how to utilize Phasers (it will look different than the RiceX implementation!). This time, we will use Phasers to create a parallel version of the algorithm that has less overhead. Here are a few notes to keep in mind when working on this assignment:&lt;br /&gt;
*Think carefully as to how the loops in this version will be structured. Drawing out the computation graph may help&lt;br /&gt;
*Bulk registering a Phaser indicates how many times &amp;lt;code&amp;gt;phaser.arriveAndAwaitAdvance()&amp;lt;/code&amp;gt; needs to be called before any of the threads are able to move on. Make sure to register the right number!&lt;br /&gt;
*You also bulk register the SwappableDoubleArrays when instantiating it. Similar to Phasers, the integer passed through in the constructor tells the object how many times &amp;lt;code&amp;gt;swap()&amp;lt;/code&amp;gt; needs to be called before the source and destination arrays are actually swapped.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|IterativeAveragingTestSuite|iterativeaveraging.studio}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|IterativeAveragingTiming|iterativeaveraging.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iterative_Averaging&amp;diff=2194</id>
		<title>Iterative Averaging</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iterative_Averaging&amp;diff=2194"/>
		<updated>2018-07-24T05:20:07Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Background */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Iterative Averaging is the process of updating an array to so that each index becomes the average of the indices one before and one after it. After repeating this for many iterations, the array may converge to one set of numbers. For example, when given the following array, we can perform iterations of this algorithm until the array eventually converges:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0.5 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0 || 0.25 || 0.5 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;\vdots&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
| 0 || 0.1 || 0.2 || 0.3 || 0.4 || 0.5 || 0.6 || 0.7 || 0.8 || 0.9 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Note that the ends of the array remain the same value from the previous iteration. &lt;br /&gt;
&lt;br /&gt;
X10/Habanero like Phasers have been added to Java since JDK7.  We will gain some experience with using Phasers in a parallel for-loop context. Phasers allow us to change the structure of our loops and reduce overhead in the algorithm.&lt;br /&gt;
&lt;br /&gt;
For more information on the algorithm and how we can use Phasers to make it better, review [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/6349730bb2a149a0b33fa23db7afddee/13 Topic 3.5] from the RiceX course.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[[Reference_Page#Phasers|Check out the reference page on phasers]]&lt;br /&gt;
&lt;br /&gt;
[http://www.baeldung.com/java-phaser Guide to the Java Phaser]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html class Phaser]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#bulkRegister-int- bulkRegister]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndAwaitAdvance-- arriveAndAwaitAdvance]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html#arriveAndDeregister-- arriveAndDeregister] (note: not required for this studio, but good to know about.)&lt;br /&gt;
&lt;br /&gt;
{{warning | Our use of the forall loop with Phasers does not accurately convey their finicky nature.  More than other features, Phasers seem to require more care to get performance improvements. }}&lt;br /&gt;
&lt;br /&gt;
=Code to Investigate=&lt;br /&gt;
class AbstractSwappable&lt;br /&gt;
:getSrc()&lt;br /&gt;
:getDst()&lt;br /&gt;
:swap()&lt;br /&gt;
class SwappableDoubleArrays implements AbstractSwappable&lt;br /&gt;
:&amp;lt;code&amp;gt;new SwappableDoubleArrays(int registrations, double[] originalData)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequential Iterative Averaging==&lt;br /&gt;
{{CodeToInvestigate|SequentialIterativeAverager|iterativelyAverage|iterativeaveraging.demo}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public double[] iterativelyAverage(List&amp;lt;Slice&amp;lt;double[]&amp;gt;&amp;gt; slices, double[] originalArray, int iterationCount)}}&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;SwappableDoubleArrays data = new SwappableDoubleArrays(1, originalArray);&lt;br /&gt;
	for (int iteration = 0; iteration &amp;lt; iterationCount; iteration++) {&lt;br /&gt;
		double[] arrayPrev = data.getSrc();&lt;br /&gt;
		double[] arrayNext = data.getDst();&lt;br /&gt;
		for (Slice&amp;lt;double[]&amp;gt; slice : slices) {&lt;br /&gt;
			for (int index = slice.getMinInclusive(); index &amp;lt; slice.getMaxExclusive(); index++) {&lt;br /&gt;
				arrayNext[index] = (arrayPrev[index - 1] + arrayPrev[index + 1]) * 0.5;&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
		data.swap();&lt;br /&gt;
	}&lt;br /&gt;
	return data.getSrc();&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is a demo of the Iterative Averaging algorithm done sequentially. Take a look at the code in your repo. Some important questions/notes to think about:&lt;br /&gt;
*What does the &amp;lt;code&amp;gt;SwappableDoubleArrays&amp;lt;/code&amp;gt; do and why is it useful in this algoritm?&lt;br /&gt;
*Why is &amp;lt;code&amp;gt;data.getSrc()&amp;lt;/code&amp;gt; returned and not &amp;lt;code&amp;gt;data.getDst()&amp;lt;/code&amp;gt;?&lt;br /&gt;
*Note that none of the slices contain the indices 0 or originalArray.length. If it did, the code would throw an OutOfBoundsException&lt;br /&gt;
&lt;br /&gt;
==PageRank==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;PR(u) = \sum_{v \in B_u} \frac{PR(v)}{L(v)}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===parallel===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;for (int iteration : new IntegerRange(0, iterationCount)) {&lt;br /&gt;
	forall(slices, (slice) -&amp;gt; {&lt;br /&gt;
		PageRank[] arrayPrev = ((iteration &amp;amp; 1) == 0) ? a : b;&lt;br /&gt;
		PageRank[] arrayNext = ((iteration &amp;amp; 1) == 0) ? b : a;&lt;br /&gt;
		slice.forEachIndex((index) -&amp;gt; {&lt;br /&gt;
                 	arrayNext[index] = calculateNextRank(index, arrayPrev);&lt;br /&gt;
          	});&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===parallel phased===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(slices.size());&lt;br /&gt;
forall(slices, (slice) -&amp;gt; {&lt;br /&gt;
	for (int iteration : new IntegerRange(0, iterationCount)) {&lt;br /&gt;
		PageRank[] arrayPrev = ((iteration &amp;amp; 1) == 0) ? a : b;&lt;br /&gt;
		PageRank[] arrayNext = ((iteration &amp;amp; 1) == 0) ? b : a;&lt;br /&gt;
		slice.forEachIndex((index) -&amp;gt; {&lt;br /&gt;
                 	arrayNext[index] = calculateNextRank(index, arrayPrev);&lt;br /&gt;
          	});&lt;br /&gt;
		phaser.arriveAndAwaitAdvance();&lt;br /&gt;
	}&lt;br /&gt;
	// note: arriveAndDeregister not required for this application&lt;br /&gt;
	phaser.arriveAndDeregister();&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
{{CodeToImplement|ForForallIterativeAverager|iterativelyAverage|iterativeaveraging.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[] iterativelyAverage(List&amp;lt;Slice&amp;lt;double[]&amp;gt;&amp;gt; slices, double[] originalArray, int iterationCount)}}&lt;br /&gt;
&lt;br /&gt;
For this method, you should not be using Phasers. Instead, implement a parallel version of the Iterative Averaging algorithm shown above sequentially. Make use of the SwappableDoubleArrays class. The return value should be the current version of the array after it has gone through the number of iterations passed in the method.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ForallForPhasedIterativeAverager|iterativelyAverage|iterativeaveraging.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[] iterativelyAverage(List&amp;lt;Slice&amp;lt;double[]&amp;gt;&amp;gt; slices, double[] originalArray, int iterationCount)}}&lt;br /&gt;
&lt;br /&gt;
Before you get started on this, make sure you review the [[Iterative Averaging#Background | Background section]] in order to understand how to utilize Phasers (it will look different than the RiceX implementation!). This time, we will use Phasers to create a parallel version of the algorithm that has less overhead. Here are a few notes to keep in mind when working on this assignment:&lt;br /&gt;
*Think carefully as to how the loops in this version will be structured. Drawing out the computation graph may help&lt;br /&gt;
*Bulk registering a Phaser indicates how many times &amp;lt;code&amp;gt;phaser.arriveAndAwaitAdvance()&amp;lt;/code&amp;gt; needs to be called before any of the threads are able to move on. Make sure to register the right number!&lt;br /&gt;
*You also bulk register the SwappableDoubleArrays when instantiating it. Similar to Phasers, the integer passed through in the constructor tells the object how many times &amp;lt;code&amp;gt;swap()&amp;lt;/code&amp;gt; needs to be called before the source and destination arrays are actually swapped.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|IterativeAveragingTestSuite|iterativeaveraging.studio}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|IterativeAveragingTiming|iterativeaveraging.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Frameworks_Lab&amp;diff=2193</id>
		<title>MapReduce Frameworks Lab</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Frameworks_Lab&amp;diff=2193"/>
		<updated>2018-07-24T05:13:48Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: Finn Voichick and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
Dealing with [https://en.wikipedia.org/wiki/Big_data big data] is Hansel-level hot right now.  We will build two implementations to better understand the inner workings of Hadoop and Spark-like frameworks.  Your frameworks will actually be more support more than just MapReduce.&lt;br /&gt;
&lt;br /&gt;
The Matrix implementation gives us experience with dividing the work up into thread confined tasks whose results are then combined together.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[https://en.wikipedia.org/wiki/MapReduce wikipedia article on MapReduce]&lt;br /&gt;
&lt;br /&gt;
As the name suggests, MapReduce refers to the process of mapping then reducing some stream of data. At its core, all a MapReduce algorithm entails is transforming a list of one kind of item before collecting those items and reducing them down to a single value using some computation. As you can probably tell, the concept of MapReduce is extremely general and can apply to a wide berth of problems. In this assignment, we will use MapReduce to simulate the Facebook mutual friends algorithm (finding the number of mutual friends between two people) and word count algorithm. As studios, you will use MapReduce to find which infected well(s) is causing an outbreak of cholera in historic London and to map a deck of cards.&lt;br /&gt;
&lt;br /&gt;
For more information on the general concept of MapReduce, refer to [https://stackoverflow.com/questions/28982/simple-explanation-of-mapreduce this] article.&lt;br /&gt;
&lt;br /&gt;
=Java Advice=&lt;br /&gt;
==Parameterized Type Array Tip==&lt;br /&gt;
Creating arrays of parameterized types in Java is madness inducing.  Some details are available in [https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays Java Generics Restrictions].&lt;br /&gt;
&lt;br /&gt;
The example below creates an array of List&amp;lt;String&amp;gt;.  The &amp;lt;code&amp;gt;@SuppressWarnings&amp;lt;/code&amp;gt; annotation is optional.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;@SuppressWarnings(&amp;quot;unchecked&amp;quot;)&lt;br /&gt;
List&amp;lt;String&amp;gt;[] result = new List[length];&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Use map.entrySet()==&lt;br /&gt;
Prefer the use of [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#entrySet-- map.entrySet()] over map.keySet() followed by looking up the value with map.get(key).&lt;br /&gt;
&lt;br /&gt;
==Use the appropriate version of forall==&lt;br /&gt;
there are many overloaded versions of forall including:&lt;br /&gt;
&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- range of ints from min to maxExclusive]&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-T:A-edu.wustl.cse231s.v5.api.CheckedConsumer- array]&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-java.lang.Iterable-edu.wustl.cse231s.v5.api.CheckedConsumer- Iterable]&lt;br /&gt;
&lt;br /&gt;
choose the correct one for each situation where &amp;quot;correct&amp;quot; is often the one that produces the cleanest code.&lt;br /&gt;
&lt;br /&gt;
=Mistakes To Avoid=&lt;br /&gt;
{{Warning | Arrays (and Matrices) are initially filled with null.  You must fill them with instances.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Ensure that your [[Slices|Slices studio]] is conforming to spec.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT iterate over all of the original unsliced data from slice.getOriginalUnslicedData().  Use [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/slice/core/Slice.html#getMinInclusive-- getMinInclusive()] &lt;br /&gt;
 and [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/slice/core/Slice.html#getMaxExclusive-- getMaxExclusive()] when processing your slice.}}&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
To allow our frameworks to work well with JDK8 Streams, we employ a couple of standard interfaces over creating out own custom ones.&lt;br /&gt;
&lt;br /&gt;
==BiConsumer==&lt;br /&gt;
We use the standard [https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html BiConsumer&amp;lt;T,U&amp;gt;] interface with an [https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html#accept-T-U- BiConsumer's accept(t,u)] method in the place of a mythical, custom MapContext&amp;lt;K,V&amp;gt; interface with an emit(key,value) method.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public interface BiConsumer&amp;lt;T, U&amp;gt; {&lt;br /&gt;
    // invoke accept with each key and value you wish to emit&lt;br /&gt;
    void accept(T t, U u);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Collector==&lt;br /&gt;
read [https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html the javadoc for Collector]&lt;br /&gt;
&lt;br /&gt;
check out the [[Collector_MapReduce_Studio#Background Collector Studio Background]]&lt;br /&gt;
&lt;br /&gt;
==Slices==&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html class Slices]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html#createNSlices-T:A-int- &amp;lt;nowiki&amp;gt;List&amp;lt;Slice&amp;lt;T[]&amp;gt;&amp;gt; createNSlices(T[] data, int numSlices)&amp;lt;/nowiki&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
==MultiWrapMap==&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/util/MultiWrapMap.html class MultiWrapMap&amp;lt;K,V&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
=A Path To Victory=&lt;br /&gt;
* [[Int_Sum_MapReduce_Apps_Studio]]&lt;br /&gt;
* [[Collector_MapReduce_Studio]]&lt;br /&gt;
* [[Mutual_Friends_MapReduce_Application]]&lt;br /&gt;
* [[#Optional_Warm_Up]]&lt;br /&gt;
* [[#Simple_MapReduce_Framework]]&lt;br /&gt;
* [[Cholera_MapReduce_Application]]&lt;br /&gt;
* [[#Matrix_MapReduce_Framework]]&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Optional Warm Up=&lt;br /&gt;
==WordCountConcreteStaticMapReduce==&lt;br /&gt;
{{CodeToImplement|WordCountConcreteStaticMapReduce|map&amp;lt;br&amp;gt;reduceCreateList&amp;lt;br&amp;gt;reduceAccumulate&amp;lt;br&amp;gt;reduceCombine&amp;lt;br&amp;gt;reduceFinish&amp;lt;br&amp;gt;mapAll&amp;lt;br&amp;gt;accumulateAll&amp;lt;br&amp;gt;finishAll|mapreduce.framework.warmup.wordcount}}&lt;br /&gt;
===Mapper===&lt;br /&gt;
{{Sequential|static void map(TextSection textSection, BiConsumer&amp;lt;String, Integer&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
===Reducer===&lt;br /&gt;
{{Sequential|static List&amp;lt;Integer&amp;gt; reduceCreateList()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceAccumulate(List&amp;lt;Integer&amp;gt; list, int v)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceCombine(List&amp;lt;Integer&amp;gt; a, List&amp;lt;Integer&amp;gt; b)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static int reduceFinish(List&amp;lt;Integer&amp;gt; list)}}&lt;br /&gt;
===Framework===&lt;br /&gt;
{{Parallel|List&amp;lt;KeyValuePair&amp;lt;String, Integer&amp;gt;&amp;gt;[] mapAll(TextSection[] input)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static Map&amp;lt;String, List&amp;lt;Integer&amp;gt;&amp;gt; accumulateAll(List&amp;lt;KeyValuePair&amp;lt;String, Integer&amp;gt;&amp;gt;[] mapAllResults)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|static Map&amp;lt;String, Integer&amp;gt; finishAll(Map&amp;lt;String, List&amp;lt;Integer&amp;gt;&amp;gt; accumulateAllResult)}}&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|WarmUpWordCountMapReduceTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==MutualFriendsConcreteStaticMapReduce==&lt;br /&gt;
{{CodeToImplement|MutualFriendsConcreteStaticMapReduce|map&amp;lt;br&amp;gt;reduceCreateList&amp;lt;br&amp;gt;reduceAccumulate&amp;lt;br&amp;gt;reduceCombine&amp;lt;br&amp;gt;reduceFinish&amp;lt;br&amp;gt;mapAll&amp;lt;br&amp;gt;accumulateAll&amp;lt;br&amp;gt;finishAll|mapreduce.framework.warmup.friends}}&lt;br /&gt;
===Mapper===&lt;br /&gt;
{{Sequential|static void map(Account account, BiConsumer&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, Set&amp;lt;AccountId&amp;gt;&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
===Reducer===&lt;br /&gt;
{{Sequential|static List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; reduceCreateList()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceAccumulate(List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; list, Set&amp;lt;AccountId&amp;gt; v)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceCombine(List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; a, List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; b)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static MutualFriendIds reduceFinish(List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; list)}}&lt;br /&gt;
===Framework===&lt;br /&gt;
{{Parallel|static List&amp;lt;KeyValuePair&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt;[] mapAll(Account[] input)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static Map&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt; accumulateAll(List&amp;lt;KeyValuePair&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt;[] mapAllResults)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|static Map&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, MutualFriendIds&amp;gt; finishAll(Map&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt; accumulateAllResult)}}&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|WarmUpMutualFriendsMapReduceTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
=Required Lab=&lt;br /&gt;
&lt;br /&gt;
==Simple MapReduce Framework==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SimpleMapReduceFramework|mapAll&amp;lt;br&amp;gt;accumulateAll&amp;lt;br&amp;gt;finishAll|mapreduce.framework.lab.simple}}&lt;br /&gt;
&lt;br /&gt;
Navigate to the &amp;lt;code&amp;gt;SimpleMapReduceFramework.java&amp;lt;/code&amp;gt; class and there will be three methods for you to complete: mapAll, accumulateAll, and finishAll. These frameworks are meant to be extremely general and applied to more specific uses of MapReduce.  Whereas the warm ups for this lab serve to prepare you to build this required section of the lab, this simple framework is in many ways a warm up for the matrix implementation.&lt;br /&gt;
&lt;br /&gt;
===mapAll===&lt;br /&gt;
{{Parallel|List&amp;lt;KeyValuePair&amp;lt;K, V&amp;gt;&amp;gt;[] mapAll(E[] input)}}&lt;br /&gt;
&lt;br /&gt;
With this method, you will map all of the elements of an array of data into a new array of equivalent size consisting of a list of key value pairs. In order to do this, you must define the map() method for the mapper by specifying that it should add a new key value pair to a previously empty list. This list should then be added to the array of lists you previously defined, therefore completing the mapping stage of MapReduce. This should all be done in parallel.&lt;br /&gt;
&lt;br /&gt;
Hint: you should create an array of lists equivalent in size to the original array. Each list will contain all of the emitted (key,value) pairs for its item.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1RG1RBPSDZu4LpVu-AC3lolWX4P3Tnl1cCMvjJ5Za74A/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g30d086461f_0_64 slide]&lt;br /&gt;
&lt;br /&gt;
===accumulateAll===&lt;br /&gt;
{{Sequential|Map&amp;lt;K, A&amp;gt; accumulateAll(List&amp;lt;KeyValuePair&amp;lt;K, V&amp;gt;&amp;gt;[] mapAllResults)}}&lt;br /&gt;
&lt;br /&gt;
This middle step is often excluded in more advanced MapReduce applications. When run in parallel, it is the only step of the framework that must be completed sequentially. In the matrix framework implementation, we will do away with this step altogether for the sake of performance.&lt;br /&gt;
&lt;br /&gt;
In this method, you will take in the array of lists you previously created and accumulate the key value pairs in the lists into a newly defined map.  To help deal with this issue, you must make use of the Collector provided to you. More specifically, access the accumulator in the collector by calling the &amp;lt;code&amp;gt;accumulator()&amp;lt;/code&amp;gt; method and accept the key/value pair when you add it to the map. You probably noticed that the method must return a map of &amp;lt;K, A&amp;gt;, which differs from the &amp;lt;K, V&amp;gt; generics fed into the method. The framework is designed this way as the data originally fed into the mapping stage can be collected into a mutable container before reaching the finish/reduce stage. In order to access the correct value for the map if the key has no associated value yet, use the supplier associated with the Collector with the &amp;lt;code&amp;gt;supplier()&amp;lt;/code&amp;gt; method.&lt;br /&gt;
&lt;br /&gt;
Hint: Look into the &amp;lt;code&amp;gt;compute()&amp;lt;/code&amp;gt; method for maps.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1RG1RBPSDZu4LpVu-AC3lolWX4P3Tnl1cCMvjJ5Za74A/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g30d086461f_0_99 slide]&lt;br /&gt;
&lt;br /&gt;
===finishAll===&lt;br /&gt;
{{Parallel|Map&amp;lt;K, R&amp;gt; finishAll(Map&amp;lt;K, A&amp;gt; accumulateAllResult)}}&lt;br /&gt;
&lt;br /&gt;
This final step reduces the accumulated data and returns the final map in its reduced form. Again, you may notice that the method returns a map of &amp;lt;K, R&amp;gt; instead of the &amp;lt;K, A&amp;gt; which was returned in the accumulateAll method. This happens for the exact same reason as the accumulateAll method, as the framework is designed to handle cases in which the reduced data differs in type from the accumulated data.&lt;br /&gt;
&lt;br /&gt;
To reduce the data down, use the map returned from the accumulateAll stage and put the results of the reduction into a new map. The provided Collector will come in extremely handy for this stage, more specifically the finisher which can be called using the &amp;lt;code&amp;gt;finisher()&amp;lt;/code&amp;gt; method. This step should run in parallel and will probably be the easiest of the three methods.&lt;br /&gt;
&lt;br /&gt;
'''NOTE: It is acceptable to build a contrived implementation of finishAll() with a [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]. While all of the parallelism is nullified by the bottle necks created by the ConcurrentHashMap to keep it thread safe, we have deemed it better to move on to the matrix implementation than to worry about the hoops you would need to jump through to do this step truly in parallel.  Reach out to an instructor for details on how to do it without the ConcurrentHashMap bottleneck, if you are interested.'''&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1RG1RBPSDZu4LpVu-AC3lolWX4P3Tnl1cCMvjJ5Za74A/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g30d086461f_0_200 slide]&lt;br /&gt;
&lt;br /&gt;
==Matrix MapReduce Framework==&lt;br /&gt;
{{CodeToImplement|MatrixMapReduceFramework|mapAndAccumulateAll&amp;lt;br&amp;gt;combineAndFinishAll|mapreduce.framework.lab.matrix}}&lt;br /&gt;
&lt;br /&gt;
Navigate to the &amp;lt;code&amp;gt;MatrixMapReduceFramework.java&amp;lt;/code&amp;gt; class and there will be two methods for you to complete: mapAndAccumulateAll and combineAndFinishAll. These frameworks are meant to be extremely general and applied to more specific uses of MapReduce.&lt;br /&gt;
&lt;br /&gt;
The matrix framework is much more complex than the simple framework, but it boosts performance by grouping the map and accumulate stages so that everything can run in parallel. It does so by slicing up the given data into the specified mapTaskCount number of slices and assigns a reduce task number to each entry using the provided getReduceIndex() method. This, in effect, creates a matrix of maps, hence the name of the framework. In the combineAndFinishAll stage, the matrix comes in handy by allowing us to go directly down the matrix (as each key is essentially grouped into a bucket), combining and reducing elements all-in-one. This concept was explained in more depth during class.&lt;br /&gt;
&lt;br /&gt;
===mapAndAccumulateAll===&lt;br /&gt;
{{Parallel|Map&amp;lt;K, A&amp;gt;[][] mapAndAccumulateAll(E[] input)}}&lt;br /&gt;
&lt;br /&gt;
In this stage, you will map and accumulate a given array of data into a matrix of maps. This method should run in parallel while combining the map and accumulate portions of the simple framework (which we recommend you attempt first). As mentioned previously, the input should be sliced into a mapTaskCount number of slices and then mapped/accumulated into its rightful spot in the matrix. Although you can slice up the data into chunks yourself, we recommend using the &amp;lt;code&amp;gt;Slice&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Slices&amp;lt;/code&amp;gt; classes introduced earlier in the course.&lt;br /&gt;
&lt;br /&gt;
For each slice, the mapper should map the input into its rightful spot in the matrix and accumulate it into that specific map. Essentially, you will need to nestle the actions of the accumulate method into the mapper. In order to find where the input should go in the matrix, remember that each slice keeps track of its position relative to the other slices and the getReduceIndex method, mentioned above.&lt;br /&gt;
&lt;br /&gt;
Hint: The number of rows should match the number of slices.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_319 slide]&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_495 slide]&lt;br /&gt;
&lt;br /&gt;
===combineAndFinishAll===&lt;br /&gt;
{{Parallel|Map&amp;lt;K, R&amp;gt; combineAndFinishAll(Map&amp;lt;K, A&amp;gt;[][] input)}}&lt;br /&gt;
&lt;br /&gt;
In this stage, you will take the matrix you just completed and combine all of the separate rows down to one array. Afterward, you will convert this combined array of maps into one final map. This method should run in parallel.&lt;br /&gt;
&lt;br /&gt;
As mentioned previously, you should go directly down the matrix to access the same bucket across the different slices you created in the mapAndAccumulateAll step. For all of the maps in a column, you should go through each entry and combine it down into one row. You will need to make use of the Collector’s finisher again, but you will also need to make use of the combiner. You can access the Collector’s combiner using the &amp;lt;code&amp;gt;combiner()&amp;lt;/code&amp;gt; method. Although the combine step differs from the simple framework, the finish step should mirror what you did previously.&lt;br /&gt;
&lt;br /&gt;
Hint: You can use the provided MultiWrapMap class to return the final row as a valid output. You should also combine before you finish.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_398 slide]&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_523 slide]&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|FrameworksLabTestSuite|mapreduce}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|SimpleFrameworkTestSuite|mapreduce}}&lt;br /&gt;
{{TestSuite|MatrixFrameworkTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
Simple framework subtotal: 40&lt;br /&gt;
* Correct mapAll (10)&lt;br /&gt;
* Correct accumulateAll (20)&lt;br /&gt;
* Correct finishAll (10)&lt;br /&gt;
&lt;br /&gt;
Matrix framework subtotal: 50&lt;br /&gt;
* Correct mapAndAccumulateAll (25)&lt;br /&gt;
* Correct combineAndFinishAll (25)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Frameworks_Lab&amp;diff=2192</id>
		<title>MapReduce Frameworks Lab</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Frameworks_Lab&amp;diff=2192"/>
		<updated>2018-07-24T05:05:59Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: Finn Voichick and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
Dealing with [https://en.wikipedia.org/wiki/Big_data big data] is Hansel-level hot right now.  We will build two implementations to better understand the inner workings of Hadoop and Spark-like frameworks.  Your frameworks will actually be more support more than just MapReduce.&lt;br /&gt;
&lt;br /&gt;
The Matrix implementation gives us experience with dividing the work up into thread confined tasks whose results are then combined together.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[https://en.wikipedia.org/wiki/MapReduce wikipedia article on MapReduce]&lt;br /&gt;
&lt;br /&gt;
As the name suggests, MapReduce refers to the process of mapping then reducing some stream of data. At its core, all a MapReduce algorithm entails is transforming a list of one kind of item before collecting those items and reducing them down to a single value using some computation. As you can probably tell, the concept of MapReduce is extremely general and can apply to a wide berth of problems. In this assignment, we will use MapReduce to simulate the Facebook mutual friends algorithm (finding the number of mutual friends between two people) and word count algorithm. As studios, you will use MapReduce to find which infected well(s) is causing an outbreak of cholera in historic London and to map a deck of cards.&lt;br /&gt;
&lt;br /&gt;
For more information on the general concept of MapReduce, refer to [https://stackoverflow.com/questions/28982/simple-explanation-of-mapreduce this] article.&lt;br /&gt;
&lt;br /&gt;
=Java Advice=&lt;br /&gt;
==Parameterized Type Array Tip==&lt;br /&gt;
Creating arrays of parameterized types in Java is madness inducing.  Some details are available in [https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays Java Generics Restrictions].&lt;br /&gt;
&lt;br /&gt;
The example below creates an array of List&amp;lt;String&amp;gt;.  The &amp;lt;code&amp;gt;@SuppressWarnings&amp;lt;/code&amp;gt; annotation is optional.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;@SuppressWarnings(&amp;quot;unchecked&amp;quot;)&lt;br /&gt;
List&amp;lt;String&amp;gt;[] result = new List[length];&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Use map.entrySet()==&lt;br /&gt;
Prefer the use of [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#entrySet-- map.entrySet()] over map.keySet() followed by looking up the value with map.get(key).&lt;br /&gt;
&lt;br /&gt;
==Use the appropriate version of forall==&lt;br /&gt;
there are many overloaded versions of forall including:&lt;br /&gt;
&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- range of ints from min to maxExclusive]&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-T:A-edu.wustl.cse231s.v5.api.CheckedConsumer- array]&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-java.lang.Iterable-edu.wustl.cse231s.v5.api.CheckedConsumer- Iterable]&lt;br /&gt;
&lt;br /&gt;
choose the correct one for each situation where &amp;quot;correct&amp;quot; is often the one that produces the cleanest code.&lt;br /&gt;
&lt;br /&gt;
=Mistakes To Avoid=&lt;br /&gt;
{{Warning | Arrays (and Matrices) are initially filled with null.  You must fill them with instances.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Ensure that your [[Slices|Slices studio]] is conforming to spec.}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT iterate over all of the original unsliced data from slice.getOriginalUnslicedData().  Use [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/slice/core/Slice.html#getMinInclusive-- getMinInclusive()] &lt;br /&gt;
 and [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/slice/core/Slice.html#getMaxExclusive-- getMaxExclusive()] when processing your slice.}}&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
To allow our frameworks to work well with JDK8 Streams, we employ a couple of standard interfaces over creating out own custom ones.&lt;br /&gt;
&lt;br /&gt;
==BiConsumer==&lt;br /&gt;
We use the standard [https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html BiConsumer&amp;lt;T,U&amp;gt;] interface with an [https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html#accept-T-U- BiConsumer's accept(t,u)] method in the place of a mythical, custom MapContext&amp;lt;K,V&amp;gt; interface with an emit(key,value) method.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public interface BiConsumer&amp;lt;T, U&amp;gt; {&lt;br /&gt;
    // invoke accept with each key and value you wish to emit&lt;br /&gt;
    void accept(T t, U u);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Collector==&lt;br /&gt;
read [https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html the javadoc for Collector]&lt;br /&gt;
&lt;br /&gt;
check out the [[Collector_MapReduce_Studio#Background Collector Studio Background]]&lt;br /&gt;
&lt;br /&gt;
==Slices==&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html class Slices]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html#createNSlices-T:A-int- &amp;lt;nowiki&amp;gt;List&amp;lt;Slice&amp;lt;T[]&amp;gt;&amp;gt; createNSlices(T[] data, int numSlices)&amp;lt;/nowiki&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
==MultiWrapMap==&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/util/MultiWrapMap.html class MultiWrapMap&amp;lt;K,V&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
=A Path To Victory=&lt;br /&gt;
* [[Int_Sum_MapReduce_Apps_Studio]]&lt;br /&gt;
* [[Collector_MapReduce_Studio]]&lt;br /&gt;
* [[Mutual_Friends_MapReduce_Application]]&lt;br /&gt;
* [[#Optional_Warm_Up]]&lt;br /&gt;
* [[#Simple_MapReduce_Framework]]&lt;br /&gt;
* [[Cholera_MapReduce_Application]]&lt;br /&gt;
* [[#Matrix_MapReduce_Framework]]&lt;br /&gt;
&lt;br /&gt;
=Optional Warm Up=&lt;br /&gt;
==WordCountConcreteStaticMapReduce==&lt;br /&gt;
{{CodeToImplement|WordCountConcreteStaticMapReduce|map&amp;lt;br&amp;gt;reduceCreateList&amp;lt;br&amp;gt;reduceAccumulate&amp;lt;br&amp;gt;reduceCombine&amp;lt;br&amp;gt;reduceFinish&amp;lt;br&amp;gt;mapAll&amp;lt;br&amp;gt;accumulateAll&amp;lt;br&amp;gt;finishAll|mapreduce.framework.warmup.wordcount}}&lt;br /&gt;
===Mapper===&lt;br /&gt;
{{Sequential|static void map(TextSection textSection, BiConsumer&amp;lt;String, Integer&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
===Reducer===&lt;br /&gt;
{{Sequential|static List&amp;lt;Integer&amp;gt; reduceCreateList()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceAccumulate(List&amp;lt;Integer&amp;gt; list, int v)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceCombine(List&amp;lt;Integer&amp;gt; a, List&amp;lt;Integer&amp;gt; b)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static int reduceFinish(List&amp;lt;Integer&amp;gt; list)}}&lt;br /&gt;
===Framework===&lt;br /&gt;
{{Parallel|List&amp;lt;KeyValuePair&amp;lt;String, Integer&amp;gt;&amp;gt;[] mapAll(TextSection[] input)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static Map&amp;lt;String, List&amp;lt;Integer&amp;gt;&amp;gt; accumulateAll(List&amp;lt;KeyValuePair&amp;lt;String, Integer&amp;gt;&amp;gt;[] mapAllResults)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|static Map&amp;lt;String, Integer&amp;gt; finishAll(Map&amp;lt;String, List&amp;lt;Integer&amp;gt;&amp;gt; accumulateAllResult)}}&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|WarmUpWordCountMapReduceTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==MutualFriendsConcreteStaticMapReduce==&lt;br /&gt;
{{CodeToImplement|MutualFriendsConcreteStaticMapReduce|map&amp;lt;br&amp;gt;reduceCreateList&amp;lt;br&amp;gt;reduceAccumulate&amp;lt;br&amp;gt;reduceCombine&amp;lt;br&amp;gt;reduceFinish&amp;lt;br&amp;gt;mapAll&amp;lt;br&amp;gt;accumulateAll&amp;lt;br&amp;gt;finishAll|mapreduce.framework.warmup.friends}}&lt;br /&gt;
===Mapper===&lt;br /&gt;
{{Sequential|static void map(Account account, BiConsumer&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, Set&amp;lt;AccountId&amp;gt;&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
===Reducer===&lt;br /&gt;
{{Sequential|static List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; reduceCreateList()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceAccumulate(List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; list, Set&amp;lt;AccountId&amp;gt; v)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static void reduceCombine(List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; a, List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; b)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static MutualFriendIds reduceFinish(List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt; list)}}&lt;br /&gt;
===Framework===&lt;br /&gt;
{{Parallel|static List&amp;lt;KeyValuePair&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt;[] mapAll(Account[] input)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|static Map&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt; accumulateAll(List&amp;lt;KeyValuePair&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt;[] mapAllResults)}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|static Map&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, MutualFriendIds&amp;gt; finishAll(Map&amp;lt;OrderedPair&amp;lt;AccountId&amp;gt;, List&amp;lt;Set&amp;lt;AccountId&amp;gt;&amp;gt;&amp;gt; accumulateAllResult)}}&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|WarmUpMutualFriendsMapReduceTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
=Required Lab=&lt;br /&gt;
&lt;br /&gt;
==Simple MapReduce Framework==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SimpleMapReduceFramework|mapAll&amp;lt;br&amp;gt;accumulateAll&amp;lt;br&amp;gt;finishAll|mapreduce.framework.lab.simple}}&lt;br /&gt;
&lt;br /&gt;
Navigate to the &amp;lt;code&amp;gt;SimpleMapReduceFramework.java&amp;lt;/code&amp;gt; class and there will be three methods for you to complete: mapAll, accumulateAll, and finishAll. These frameworks are meant to be extremely general and applied to more specific uses of MapReduce.  Whereas the warm ups for this lab serve to prepare you to build this required section of the lab, this simple framework is in many ways a warm up for the matrix implementation.&lt;br /&gt;
&lt;br /&gt;
===mapAll===&lt;br /&gt;
{{Parallel|List&amp;lt;KeyValuePair&amp;lt;K, V&amp;gt;&amp;gt;[] mapAll(E[] input)}}&lt;br /&gt;
&lt;br /&gt;
With this method, you will map all of the elements of an array of data into a new array of equivalent size consisting of a list of key value pairs. In order to do this, you must define the map() method for the mapper by specifying that it should add a new key value pair to a previously empty list. This list should then be added to the array of lists you previously defined, therefore completing the mapping stage of MapReduce. This should all be done in parallel.&lt;br /&gt;
&lt;br /&gt;
Hint: you should create an array of lists equivalent in size to the original array. Each list will contain all of the emitted (key,value) pairs for its item.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1RG1RBPSDZu4LpVu-AC3lolWX4P3Tnl1cCMvjJ5Za74A/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g30d086461f_0_64 slide]&lt;br /&gt;
&lt;br /&gt;
===accumulateAll===&lt;br /&gt;
{{Sequential|Map&amp;lt;K, A&amp;gt; accumulateAll(List&amp;lt;KeyValuePair&amp;lt;K, V&amp;gt;&amp;gt;[] mapAllResults)}}&lt;br /&gt;
&lt;br /&gt;
This middle step is often excluded in more advanced MapReduce applications. When run in parallel, it is the only step of the framework that must be completed sequentially. In the matrix framework implementation, we will do away with this step altogether for the sake of performance.&lt;br /&gt;
&lt;br /&gt;
In this method, you will take in the array of lists you previously created and accumulate the key value pairs in the lists into a newly defined map.  To help deal with this issue, you must make use of the Collector provided to you. More specifically, access the accumulator in the collector by calling the &amp;lt;code&amp;gt;accumulator()&amp;lt;/code&amp;gt; method and accept the key/value pair when you add it to the map. You probably noticed that the method must return a map of &amp;lt;K, A&amp;gt;, which differs from the &amp;lt;K, V&amp;gt; generics fed into the method. The framework is designed this way as the data originally fed into the mapping stage can be collected into a mutable container before reaching the finish/reduce stage. In order to access the correct value for the map if the key has no associated value yet, use the supplier associated with the Collector with the &amp;lt;code&amp;gt;supplier()&amp;lt;/code&amp;gt; method.&lt;br /&gt;
&lt;br /&gt;
Hint: Look into the &amp;lt;code&amp;gt;compute()&amp;lt;/code&amp;gt; method for maps.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1RG1RBPSDZu4LpVu-AC3lolWX4P3Tnl1cCMvjJ5Za74A/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g30d086461f_0_99 slide]&lt;br /&gt;
&lt;br /&gt;
===finishAll===&lt;br /&gt;
{{Parallel|Map&amp;lt;K, R&amp;gt; finishAll(Map&amp;lt;K, A&amp;gt; accumulateAllResult)}}&lt;br /&gt;
&lt;br /&gt;
This final step reduces the accumulated data and returns the final map in its reduced form. Again, you may notice that the method returns a map of &amp;lt;K, R&amp;gt; instead of the &amp;lt;K, A&amp;gt; which was returned in the accumulateAll method. This happens for the exact same reason as the accumulateAll method, as the framework is designed to handle cases in which the reduced data differs in type from the accumulated data.&lt;br /&gt;
&lt;br /&gt;
To reduce the data down, use the map returned from the accumulateAll stage and put the results of the reduction into a new map. The provided Collector will come in extremely handy for this stage, more specifically the finisher which can be called using the &amp;lt;code&amp;gt;finisher()&amp;lt;/code&amp;gt; method. This step should run in parallel and will probably be the easiest of the three methods.&lt;br /&gt;
&lt;br /&gt;
'''NOTE: It is acceptable to build a contrived implementation of finishAll() with a [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]. While all of the parallelism is nullified by the bottle necks created by the ConcurrentHashMap to keep it thread safe, we have deemed it better to move on to the matrix implementation than to worry about the hoops you would need to jump through to do this step truly in parallel.  Reach out to an instructor for details on how to do it without the ConcurrentHashMap bottleneck, if you are interested.'''&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1RG1RBPSDZu4LpVu-AC3lolWX4P3Tnl1cCMvjJ5Za74A/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g30d086461f_0_200 slide]&lt;br /&gt;
&lt;br /&gt;
==Matrix MapReduce Framework==&lt;br /&gt;
{{CodeToImplement|MatrixMapReduceFramework|mapAndAccumulateAll&amp;lt;br&amp;gt;combineAndFinishAll|mapreduce.framework.lab.matrix}}&lt;br /&gt;
&lt;br /&gt;
Navigate to the &amp;lt;code&amp;gt;MatrixMapReduceFramework.java&amp;lt;/code&amp;gt; class and there will be two methods for you to complete: mapAndAccumulateAll and combineAndFinishAll. These frameworks are meant to be extremely general and applied to more specific uses of MapReduce.&lt;br /&gt;
&lt;br /&gt;
The matrix framework is much more complex than the simple framework, but it boosts performance by grouping the map and accumulate stages so that everything can run in parallel. It does so by slicing up the given data into the specified mapTaskCount number of slices and assigns a reduce task number to each entry using the provided getReduceIndex() method. This, in effect, creates a matrix of maps, hence the name of the framework. In the combineAndFinishAll stage, the matrix comes in handy by allowing us to go directly down the matrix (as each key is essentially grouped into a bucket), combining and reducing elements all-in-one. This concept was explained in more depth during class.&lt;br /&gt;
&lt;br /&gt;
===mapAndAccumulateAll===&lt;br /&gt;
{{Parallel|Map&amp;lt;K, A&amp;gt;[][] mapAndAccumulateAll(E[] input)}}&lt;br /&gt;
&lt;br /&gt;
In this stage, you will map and accumulate a given array of data into a matrix of maps. This method should run in parallel while combining the map and accumulate portions of the simple framework (which we recommend you attempt first). As mentioned previously, the input should be sliced into a mapTaskCount number of slices and then mapped/accumulated into its rightful spot in the matrix. Although you can slice up the data into chunks yourself, we recommend using the &amp;lt;code&amp;gt;Slice&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Slices&amp;lt;/code&amp;gt; classes introduced earlier in the course.&lt;br /&gt;
&lt;br /&gt;
For each slice, the mapper should map the input into its rightful spot in the matrix and accumulate it into that specific map. Essentially, you will need to nestle the actions of the accumulate method into the mapper. In order to find where the input should go in the matrix, remember that each slice keeps track of its position relative to the other slices and the getReduceIndex method, mentioned above.&lt;br /&gt;
&lt;br /&gt;
Hint: The number of rows should match the number of slices.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_319 slide]&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_495 slide]&lt;br /&gt;
&lt;br /&gt;
===combineAndFinishAll===&lt;br /&gt;
{{Parallel|Map&amp;lt;K, R&amp;gt; combineAndFinishAll(Map&amp;lt;K, A&amp;gt;[][] input)}}&lt;br /&gt;
&lt;br /&gt;
In this stage, you will take the matrix you just completed and combine all of the separate rows down to one array. Afterward, you will convert this combined array of maps into one final map. This method should run in parallel.&lt;br /&gt;
&lt;br /&gt;
As mentioned previously, you should go directly down the matrix to access the same bucket across the different slices you created in the mapAndAccumulateAll step. For all of the maps in a column, you should go through each entry and combine it down into one row. You will need to make use of the Collector’s finisher again, but you will also need to make use of the combiner. You can access the Collector’s combiner using the &amp;lt;code&amp;gt;combiner()&amp;lt;/code&amp;gt; method. Although the combine step differs from the simple framework, the finish step should mirror what you did previously.&lt;br /&gt;
&lt;br /&gt;
Hint: You can use the provided MultiWrapMap class to return the final row as a valid output. You should also combine before you finish.&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_398 slide]&lt;br /&gt;
[https://docs.google.com/presentation/d/1iqJw_bldkVv3AhSCM740FxSTd31-zZBjk71icZ233lk/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g343eac61f6_0_523 slide]&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|FrameworksLabTestSuite|mapreduce}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|SimpleFrameworkTestSuite|mapreduce}}&lt;br /&gt;
{{TestSuite|MatrixFrameworkTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
Simple framework subtotal: 40&lt;br /&gt;
* Correct mapAll (10)&lt;br /&gt;
* Correct accumulateAll (20)&lt;br /&gt;
* Correct finishAll (10)&lt;br /&gt;
&lt;br /&gt;
Matrix framework subtotal: 50&lt;br /&gt;
* Correct mapAndAccumulateAll (25)&lt;br /&gt;
* Correct combineAndFinishAll (25)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Reducer_Assignment&amp;diff=2191</id>
		<title>MapReduce Reducer Assignment</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Reducer_Assignment&amp;diff=2191"/>
		<updated>2018-07-24T04:53:49Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Use */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: Finn Voichick and Dennis Cosgrove&lt;br /&gt;
=Motivation=&lt;br /&gt;
&amp;lt;code&amp;gt;interface Collector&amp;lt;T,A,R&amp;gt;&amp;lt;/code&amp;gt; is fundamental to the MapReduce Frameworks lab.  Your frameworks will be general enough such that MapReduce is just a subset of what you will support.&lt;br /&gt;
&lt;br /&gt;
In this studio we will build a ClassicReducer Collector which will implement the MapReduce style of accumulating all of the emitted values per key in a List.&lt;br /&gt;
&lt;br /&gt;
We will also build a custom IntSumCollector to demonstrate the desired flexibility of the Collector interface.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
We debated between creating our own custom Reducer&amp;lt;V,A,R&amp;gt; interface versus adopting the standard [https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html interface Collector&amp;lt;T,A,R&amp;gt;] from the standard [http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html Java streams framework] as the basis for the MapReduce Frameworks Lab.  &lt;br /&gt;
&lt;br /&gt;
While It might have been slightly less confusing at the outset if we used something like this mythical non-existant interface below:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public interface Reducer&amp;lt;V, A, R&amp;gt; {&lt;br /&gt;
	A createMutableContainer();&lt;br /&gt;
	void accumulate(A container, V item);&lt;br /&gt;
	A combine(A containerA, A containerB);&lt;br /&gt;
	R reduce(A container);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
we chose to go with the standard Collector&amp;lt;T,A,R&amp;gt; despite the extra level of indirection it requires (returning @Functional interfaces whose single abstract methods do the work).&lt;br /&gt;
&lt;br /&gt;
We provide this mythical &amp;lt;code&amp;gt;class CollectorReducerAdapter&amp;lt;/code&amp;gt; as a [https://en.wikipedia.org/wiki/Rosetta_Stone Rosetta Stone] of sorts in an effort to reveal what each method is responsible for:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public class CollectorReducerAdapter&amp;lt;V, A, R&amp;gt; implements Reducer&amp;lt;V, A, R&amp;gt; {&lt;br /&gt;
	private final Collector&amp;lt;V,A,R&amp;gt; collector;&lt;br /&gt;
	public CollectorReducerAdapter(Collector&amp;lt;V,A,R&amp;gt; collector) {&lt;br /&gt;
		this.collector = collector;&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public A createMutableContainer() {&lt;br /&gt;
		return collector.supplier().get();&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public void accumulate(A container, V item) {&lt;br /&gt;
		collector.accumulator().accept(container, item);&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public A combine(A containerA, A containerB) {&lt;br /&gt;
		return collector.combiner().apply(containerA, containerB);&lt;br /&gt;
	}&lt;br /&gt;
	@Override&lt;br /&gt;
	public R reduce(A container) {&lt;br /&gt;
		return collector.finisher().apply(container);&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Collector==&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public interface Collector&amp;lt;T, A, R&amp;gt; {&lt;br /&gt;
&lt;br /&gt;
	// invoke supplier().get() to create a new mutable container&lt;br /&gt;
	Supplier&amp;lt;A&amp;gt; supplier();&lt;br /&gt;
&lt;br /&gt;
	// invoke accumulator().accept(container, item) to add item to a container&lt;br /&gt;
	BiConsumer&amp;lt;A, T&amp;gt; accumulator();&lt;br /&gt;
&lt;br /&gt;
	// invoke combiner().apply(containerA, containerB) to combine one container into the other&lt;br /&gt;
	BinaryOperator&amp;lt;A&amp;gt; combiner();&lt;br /&gt;
&lt;br /&gt;
	// invoke finisher().apply(container) to reduce a container to its final form&lt;br /&gt;
	Function&amp;lt;A, R&amp;gt; finisher();&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===supplier get===&lt;br /&gt;
We use supplier().get() to create a new mutable container.  For classic map reduce this would be a [https://docs.oracle.com/javase/8/docs/api/java/util/List.html List&amp;lt;V&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
mythical code analogy: &amp;lt;code&amp;gt;container = collector.supplier().get()&amp;lt;/code&amp;gt; &amp;lt;math&amp;gt;\leftrightarrow&amp;lt;/math&amp;gt; &amp;lt;code&amp;gt;container = accumulatorReducer.createContainer()&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===accumulator accept===&lt;br /&gt;
We use accumulator().accept(container,item) to accumulate a value.  For classic map reduce this would add an item to a list.&lt;br /&gt;
&lt;br /&gt;
mythical code analogy: &amp;lt;code&amp;gt;collector.accumulator().accept(container,item);&amp;lt;/code&amp;gt; &amp;lt;math&amp;gt;\leftrightarrow&amp;lt;/math&amp;gt; &amp;lt;code&amp;gt;accumulatorReducer.accumulate(container,item)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===combiner apply===&lt;br /&gt;
We use combiner().apply(containerA,containerB) to combine two accumulators.  You may combine containerB into containerA or containerA into containerB.  Just return whichever is the combined result. &lt;br /&gt;
&lt;br /&gt;
mythical code analogy: &amp;lt;code&amp;gt;collector.combiner().apply(containerA,containerB)&amp;lt;/code&amp;gt; &amp;lt;math&amp;gt;\leftrightarrow&amp;lt;/math&amp;gt; &amp;lt;code&amp;gt;accumulatorReducer.combine(containerA,containerB)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===finisher apply===&lt;br /&gt;
We use finisher().apply(container) to reduce an accumulator.&lt;br /&gt;
&lt;br /&gt;
mythical code analogy: &amp;lt;code&amp;gt;collector.finisher().apply(container)&amp;lt;/code&amp;gt; &amp;lt;math&amp;gt;\leftrightarrow&amp;lt;/math&amp;gt; &amp;lt;code&amp;gt;r = accumulatorReducer.reduce(container)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html interface Collector&amp;lt;T,A,R&amp;gt;]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html interface Supplier&amp;lt;T&amp;gt;]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html interface BiConsumer&amp;lt;T,U&amp;gt;]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/function/BinaryOperator.html interface BinaryOperator&amp;lt;T&amp;gt;]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html interface Function&amp;lt;T,R&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
[https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/mutable/MutableInt.html class MutableInt]&lt;br /&gt;
&lt;br /&gt;
Knowing how to use [[Reference_Page#Anonymous_Classes|anonymous classes]] will be very helpful!&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==ClassicReducer==&lt;br /&gt;
The classic MapReduce Collector will collect all of the emitted values in a [https://docs.oracle.com/javase/8/docs/api/java/util/List.html List].&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ClassicReducer|supplier&amp;lt;br&amp;gt;accumulator&amp;lt;br&amp;gt;combiner|mapreduce.collector.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|Supplier&amp;lt;List&amp;lt;V&amp;gt;&amp;gt; supplier()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|BiConsumer&amp;lt;List&amp;lt;V&amp;gt;, V&amp;gt; accumulator()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|BinaryOperator&amp;lt;List&amp;lt;V&amp;gt;&amp;gt; combiner()}}&lt;br /&gt;
&lt;br /&gt;
==IntSumCollector==&lt;br /&gt;
MapReduce Apps like Word Count offer glaring opportunities to optimize the classic MapReduce append all of the 1s in a List and add them up later.  In this section of the studio you will use [https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/mutable/MutableInt.html MutableInt] to simply add the values as they come in.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|IntSumCollector|supplier&amp;lt;br&amp;gt;accumulator&amp;lt;br&amp;gt;combiner&amp;lt;br&amp;gt;finisher|mapreduce.collector.intsum.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public Supplier&amp;lt;MutableInt&amp;gt; supplier()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public BiConsumer&amp;lt;MutableInt, Integer&amp;gt; accumulator()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public BinaryOperator&amp;lt;MutableInt&amp;gt; combiner()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public Function&amp;lt;MutableInt, Integer&amp;gt; finisher()}}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|CollectorStudioTestSuite|mapreduce}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|ClassicReducerTestSuite|mapreduce}}&lt;br /&gt;
&lt;br /&gt;
{{TestSuite|IntSumCollectorTestSuite|mapreduce}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Mapper_Assignment&amp;diff=2190</id>
		<title>MapReduce Mapper Assignment</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MapReduce_Mapper_Assignment&amp;diff=2190"/>
		<updated>2018-07-24T04:43:23Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
In previous semesters the MapReduce lab has proven to be the most challenging.  We have split things up to allow you to get familiar with the how Mappers and Reducers work first.  We will build a card mapper that matches the spec outlined in the prep video, a simple word counting mapper, an analogous k-mer counting mapper, and an integer sum reducer to wrap things up.&lt;br /&gt;
&lt;br /&gt;
The k-mer counting mapper will prepare us for (and hopefully lessen the burden of) upcoming lab 6.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&amp;lt;youtube&amp;gt;mySyARBDwoI&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html BiConsumer]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html#accept-T-U- accept(t,u)] (note: closest relative to &amp;quot;emit&amp;quot; from RiceX prep)&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html Collector]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html#finisher-- finisher()] (note: closest relative to &amp;quot;reduce&amp;quot; from RiceX prep)&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Deck.html Deck] (note: Iterable&amp;lt;Card&amp;gt;)&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Card.html Card]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Card.html#getRank-- getRank()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Card.html#getSuit-- getSuit()]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Rank.html Rank]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Rank.html#isNumeric-- isNumeric()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Rank.html#getNumericValue-- getNumericValue()]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/cards/core/Suit.html Suit]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/wordcount/core/TextSection.html TextSection]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/mapreduce/apps/wordcount/core/TextSection.html#getWords-- getWords()]&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
==Card Mapper==&lt;br /&gt;
The specification for this mapper is outlined in the prep video:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;bcjSe0xCHbE&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Non-numeric cards are considered to be bad data and ignored.  Numeric cards should be emitted with their suit as the key and the numeric value as the value.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|CardMapper|map|mapreduce.app.cards.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public void map(Deck deck, BiConsumer&amp;lt;Suit, Integer&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
==Word Count Mapper==&lt;br /&gt;
Counting occurrences of words in text is a classic example of mapreduce.  We will ignore any zero length words and convert the remaining words to lower-case so as to get a case insensitive count.  Emitting each lower-cased word as the key with the value of 1 should do the trick here.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|WordCountMapper|map|mapreduce.apps.wordcount.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public void map(TextSection textSection, BiConsumer&amp;lt;String, Integer&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|The javadocs have an error.  They should read &amp;quot; the values of all of the key-value pairs will be one.&amp;quot;}}&lt;br /&gt;
&lt;br /&gt;
The goal of this implementation is to count the number of times a word appears in a given text, using MapReduce. To accomplish this, you will need to create both the mapper and the reducer. Navigate to the &amp;lt;code&amp;gt;WordCountMapper.java&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IntegerSumClassicReducer.java&amp;lt;/code&amp;gt; classes. You will specifically define how the framework accomplishes the map and reduce methods.&lt;br /&gt;
&lt;br /&gt;
The only method you will need to alter is the map method. In this method, you need to record every instance of a given word and feed it into the keyValuePairConsumer. To do this, access all of the words in the TextSection and if the length of the word is greater than zero (meaning it is not just blank space), convert it into lower-case and accept it into the consumer.&lt;br /&gt;
&lt;br /&gt;
Hint: Look at the methods in TextSection and the toLowerCase() method for strings for assistance.&lt;br /&gt;
&lt;br /&gt;
==K-mer Count Mapper==&lt;br /&gt;
&lt;br /&gt;
K-mer counting is a useful technique in bioinformatics: http://www.csbio.unc.edu/mcmillan/Comp555S17/Lecture02.pdf&lt;br /&gt;
&lt;br /&gt;
Background information on k-mer counting can be found here: https://en.wikipedia.org/wiki/K-mer&lt;br /&gt;
&lt;br /&gt;
This mapper is similar to the word count mapper except that the k-mers overlap with each other while words are separate.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|KMerMapper|map|mapreduce.apps.kmer.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public void map(byte[] sequence, BiConsumer&amp;lt;String, Integer&amp;gt; keyValuePairConsumer)}}&lt;br /&gt;
&lt;br /&gt;
Be sure to use the provided toStringKMer(sequence, offset, kMerLength) method to generate your k-mers:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	private static String toStringKMer(byte[] sequence, int offset, int kMerLength) {&lt;br /&gt;
		return new String(sequence, offset, kMerLength, StandardCharsets.UTF_8);&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Int Sum Reducer==&lt;br /&gt;
{{CodeToImplement|IntegerSumClassicReducer|finisher|mapreduce.apps.intsum.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public Function&amp;lt;List&amp;lt;Integer&amp;gt;, Integer&amp;gt; finisher()}}&lt;br /&gt;
&lt;br /&gt;
The sea of code created by the anonymous inner class can admittedly be a bit intimidating at first:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public Function&amp;lt;List&amp;lt;Integer&amp;gt;, Integer&amp;gt; finisher() {&lt;br /&gt;
		return new Function&amp;lt;List&amp;lt;Integer&amp;gt;, Integer&amp;gt;() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public Integer apply(List&amp;lt;Integer&amp;gt; list) {&lt;br /&gt;
				throw new NotYetImplementedException();&lt;br /&gt;
			}&lt;br /&gt;
		};&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
but in the end, the apply method is passed a list of integers which it should simply sum up and return.  Feel free to replace the bulky anonymous inner class with a lambda if you would like.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|IntSumStudioTestSuite|mapreduce}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iterator,_Collection,_and_Map&amp;diff=2189</id>
		<title>Iterator, Collection, and Map</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Iterator,_Collection,_and_Map&amp;diff=2189"/>
		<updated>2018-07-23T06:47:41Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: Ben Choi and Dennis Cosgrove&lt;br /&gt;
&lt;br /&gt;
=Motivation=&lt;br /&gt;
We gain experience with interfaces and classes.  In addition we will deal with generic types.  &lt;br /&gt;
&lt;br /&gt;
We implement our own Iterator, Collection, and Map @NotThreadSafe classes.  Later in the semester we will implement a @ThreadSafe version of a Map.&lt;br /&gt;
&lt;br /&gt;
In the creation of our Map class, we will gain experience with hashing which we will leverage throughout the semester.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
* [[Rundown_on_Everything_Java]]&lt;br /&gt;
* [[Interfaces]]&lt;br /&gt;
&amp;lt;youtube&amp;gt;njTh_OwMljA&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;shs0KM3wKv8&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Java Util Documentation==&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html Iterator]&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html Collection]&lt;br /&gt;
* [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map]&lt;br /&gt;
==VisuAlgo==&lt;br /&gt;
* [https://visualgo.net/en/list linked list] &lt;br /&gt;
* [https://visualgo.net/en/hashtable hash table]&lt;br /&gt;
==Related Videos==&lt;br /&gt;
&amp;lt;youtube&amp;gt;A-rTJTHq5B4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;PfKnQzbztfo&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Mistakes To Avoid=&lt;br /&gt;
{{Warning | Do NOT use &amp;lt;nowiki&amp;gt;==&amp;lt;/nowiki&amp;gt;  Use [https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#equals-java.lang.Object-java.lang.Object- Objects.equals(a,b)]. }}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT use % which can return a negative number.  Use [https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int- Math.floorMod(x,y)]. }}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT parallelize. }}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT simply remove and add for put on a Map.  Look for the entry and set its value if you find it.  Otherwise add it. }}&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
To be an [https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html Iterable] object a class must implement all of the abstract methods on Iterable.  There happens to be only 1: &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Iterator&amp;lt;T&amp;gt; iterator()&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When you have an instance of Iterable you can then obviously invoke the iterator() method, then loop over the resulting iterator to process the elements in the Iterable:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	private static void printAllViaIterator(Iterable&amp;lt;String&amp;gt; iterable) {&lt;br /&gt;
		Iterator&amp;lt;String&amp;gt; iterator = iterable.iterator();&lt;br /&gt;
		while(iterator.hasNext()) {&lt;br /&gt;
			String element = iterator.next();&lt;br /&gt;
			System.out.println(element);&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As a bit of sweet syntactic sugar, any Iterable can be used in a [https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html for-each loop]:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	private static void printAllViaForEach(Iterable&amp;lt;String&amp;gt; iterable) {&lt;br /&gt;
		for (String element : iterable) {&lt;br /&gt;
			System.out.println(element);&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Any class that implements Iterable must implement the iterator() method.  A Collection isa Iterable.  The interface Collection extends the interface Iterable.  To be an Iterable&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;		List&amp;lt;String&amp;gt; states = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
		states.add(&amp;quot;Delaware&amp;quot;);&lt;br /&gt;
		states.add(&amp;quot;Idaho&amp;quot;);&lt;br /&gt;
		states.add(&amp;quot;Alaska&amp;quot;);&lt;br /&gt;
		&lt;br /&gt;
		printAllViaIterator(states);&lt;br /&gt;
		printAllViaForEach(states);&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{ Tip | It is good practice to declare variables, parameters, and fields to be of the least specific type possible (but no less specific :). This is commonly an interface. }}&lt;br /&gt;
&lt;br /&gt;
{{ Warning | A common mistake we see is students attempting to create an instance of an interface when they need to create an instance of a class (e.g. &amp;lt;nowiki&amp;gt;List&amp;lt;String&amp;gt; states = new LinkedList&amp;lt;&amp;gt;();&amp;lt;/nowiki&amp;gt;). }}&lt;br /&gt;
&lt;br /&gt;
==LinkedCollection==&lt;br /&gt;
The most notable subinterface of Iterable is [https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html Collection].  Collection in turn has often used subiterfaces [https://docs.oracle.com/javase/8/docs/api/java/util/List.html List], [https://docs.oracle.com/javase/8/docs/api/java/util/Set.html Set], and [https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html Queue].&lt;br /&gt;
&lt;br /&gt;
The [https://docs.oracle.com/javase/8/docs/api/java/util/package-tree.html class and interface heirarchy doc] has the complete tree for the java.util package.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|LinkedCollection|iterator&amp;lt;br&amp;gt;size&amp;lt;br&amp;gt;add|util.lab.collection}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public Iterator&amp;lt;E&amp;gt; iterator()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int size()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public boolean add(E item)}}&lt;br /&gt;
&lt;br /&gt;
We will be creating our own implementation of Collection &amp;lt;code&amp;gt;class LinkedNodesCollection&amp;lt;/code&amp;gt;.  Like many of the Collections you may have used in the past (e.g. LinkedList, HashSet) we will inherit functionality from [https://docs.oracle.com/javase/8/docs/api/java/util/AbstractCollection.html AbstractCollection].  In fact, we will only need to implement three of the public methods: size(), iterator(), and add().  The bulk of AbstractCollection's implementation relies on our correct implementation of iterator().&lt;br /&gt;
&lt;br /&gt;
Correctly implementing size() should be trivial.  Just be sure to increment and decrement size when adding or removing elements respectively.&lt;br /&gt;
&lt;br /&gt;
{{Warning | remove is achieved via the iterator.  Be sure to keep the Collection up to date by invoking decrementSize(). }}&lt;br /&gt;
&lt;br /&gt;
add() will want to use the provided &amp;lt;code&amp;gt;class LinkedNode&amp;lt;E&amp;gt;&amp;lt;/code&amp;gt;.  Simply insert new elements in at the head of your collection as [https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html#offerFirst(E) deque.offerFirst(element)] does.&lt;br /&gt;
&lt;br /&gt;
Providing the required iterator() method will in turn require us to build [[#LinkedNodesIterator]].&lt;br /&gt;
&lt;br /&gt;
Note: The “head” is a sentinel node, meaning its sole purpose is to point its next reference to the true first node of the list.&lt;br /&gt;
&lt;br /&gt;
===Empty===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Collection&amp;lt;String&amp;gt; collection = new LinkedCollection&amp;lt;&amp;gt;();&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
would result in this data structure:&lt;br /&gt;
&lt;br /&gt;
[[File:LinkedCollectionEmpty.svg|800px]]&lt;br /&gt;
&lt;br /&gt;
===A===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Collection&amp;lt;String&amp;gt; collection = new LinkedNodesCollection&amp;lt;&amp;gt;();&lt;br /&gt;
collection.add(&amp;quot;A&amp;quot;);&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
would result in this data structure:&lt;br /&gt;
&lt;br /&gt;
[[File:LinkedCollectionA.svg|800px]]&lt;br /&gt;
&lt;br /&gt;
===AB===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Collection&amp;lt;String&amp;gt; collection = new LinkedNodesCollection&amp;lt;&amp;gt;();&lt;br /&gt;
collection.add(&amp;quot;A&amp;quot;);&lt;br /&gt;
collection.add(&amp;quot;B&amp;quot;);&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
would result in this data structure:&lt;br /&gt;
&lt;br /&gt;
[[File:LinkedCollectionAB.svg|800px]]&lt;br /&gt;
&lt;br /&gt;
===ABC===&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Collection&amp;lt;String&amp;gt; collection = new LinkedNodesCollection&amp;lt;&amp;gt;();&lt;br /&gt;
collection.add(&amp;quot;A&amp;quot;);&lt;br /&gt;
collection.add(&amp;quot;B&amp;quot;);&lt;br /&gt;
collection.add(&amp;quot;C&amp;quot;);&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
would result in this data structure:&lt;br /&gt;
&lt;br /&gt;
[[File:LinkedCollectionABC.svg|800px]]&lt;br /&gt;
&lt;br /&gt;
==LinkedNodesIterator==&lt;br /&gt;
* [https://wustl.box.com/s/039hubq2m836wdwjvrvxvtgpp6hij34v Video Demo: Using Iterable]&lt;br /&gt;
* [https://wustl.box.com/s/73996oeuhgnkg38og0l3amkr1ox0ev3d Video Demo: Implementing ArrayIterator]&lt;br /&gt;
{{CodeToImplement|LinkedNodesIterator|hasNext&amp;lt;br&amp;gt;next&amp;lt;br&amp;gt;remove|util.lab.collection}}&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;code&amp;gt;hasNext()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt;===&lt;br /&gt;
{{Sequential|public boolean hasNext()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public E next()}}&lt;br /&gt;
&lt;br /&gt;
Iterator should keep track of the previous, current, and (optionally) next node as you march through the LinkedNodesCollection. This means you will need to think about what member variables to create for this class.&lt;br /&gt;
&lt;br /&gt;
{{Warning | The iterator should start at the head (sentinel) node. }}&lt;br /&gt;
&lt;br /&gt;
====State of the Iterator When &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt; Would Return A====&lt;br /&gt;
[[File:LinkedCollectionABC iteratorNextA.svg|800px]]&lt;br /&gt;
====State of the Iterator When &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt; Would Return B====&lt;br /&gt;
[[File:LinkedCollectionABC iteratorNextB.svg|800px]]&lt;br /&gt;
====State of the Iterator When &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt; Would Return C====&lt;br /&gt;
[[File:LinkedCollectionABC iteratorNextC.svg|800px]]&lt;br /&gt;
====State of the Iterator When &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt; Would Throw NoSuchElementException====&lt;br /&gt;
[[File:LinkedCollectionABC iteratorNextException.svg|800px]]&lt;br /&gt;
&lt;br /&gt;
Check out the docs for [https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next-- next()] of when to throw [https://docs.oracle.com/javase/8/docs/api/java/util/NoSuchElementException.html NoSuchElementException] and [https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove-- remove()] for when to throw [https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html IllegalStateException]. Think of edge cases like when the collection is empty or when the iterator tries to remove the sentinel node.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Iterator&amp;lt;Integer&amp;gt; iterator = collection.iterator();&lt;br /&gt;
if(iterator.hasNext()==false) {&lt;br /&gt;
    iterator.next(); // NOTE: should throw NoSuchElementException&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===&amp;lt;code&amp;gt;remove()&amp;lt;/code&amp;gt;===&lt;br /&gt;
{{Sequential|public void remove()}}&lt;br /&gt;
====State of the Iterator When &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt; Would Return C (i.e. just returned B)====&lt;br /&gt;
note: this is the same diagram from above.&lt;br /&gt;
&lt;br /&gt;
[[File:LinkedCollectionABC iteratorNextC.svg|800px]]&lt;br /&gt;
====State of the Iterator When &amp;lt;code&amp;gt;next()&amp;lt;/code&amp;gt; Would Return C (i.e. just returned B) Then &amp;lt;code&amp;gt;remove()&amp;lt;/code&amp;gt; Was Invoked====&lt;br /&gt;
[[File:LinkedCollectionABC iteratorRemovedB.svg|800px]]&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Iterator&amp;lt;Integer&amp;gt; iterator = collection.iterator();&lt;br /&gt;
iterator.remove(); // NOTE: should throw IllegalStateException&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;Iterator&amp;lt;Integer&amp;gt; iterator = collection.iterator();&lt;br /&gt;
iterator.next();&lt;br /&gt;
iterator.remove();&lt;br /&gt;
iterator.remove(); // NOTE: should throw IllegalStateException&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==BucketsHashMap==&lt;br /&gt;
You will most likely want to complete your Collection and Iterator implementations before moving on to the Map implementations as they will be built with them.&lt;br /&gt;
&lt;br /&gt;
A Map (also sometimes referred to as a Dictionary or a Hashtable) is an abstract data structure which has the capabilities of associating a value with a key: &amp;lt;code&amp;gt;map.put(key, value)&amp;lt;/code&amp;gt;, looking up the associated value with a key: &amp;lt;code&amp;gt;map.get(key)&amp;lt;/code&amp;gt;, and removing &amp;lt;code&amp;gt;map.remove(key)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The standard Java Collections Framework [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map] provides a number of other nice methods, but put, get, and remove are the core of any Map in any programming language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
https://en.wikipedia.org/wiki/Hash_table#/media/File:Hash_table_5_0_1_1_1_1_1_LL.svg&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
*For the compute method, a BiFunction is simply Java’s '''functional interface''' for something that takes in two input parameters and spits out a result. &amp;lt;code&amp;gt;? super K&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;? super V&amp;lt;/code&amp;gt; indicates a class K or V extends ('''superclass'''), while &amp;lt;code&amp;gt;? extends V&amp;lt;/code&amp;gt; indicates a class that extends V ('''subclass'''). The &amp;lt;code&amp;gt;?&amp;lt;/code&amp;gt; is referred to as a '''wildcard generic'''. Follow the links below for Oracle’s documentation on the topic.&lt;br /&gt;
**[https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html Wildcard Guidelines]&lt;br /&gt;
**[https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html Wildcards]&lt;br /&gt;
*When writing the compute method, use remappingFunction’s apply method to generate a new value and set it as the new value for the entry if it is not null. The method should return this new value. Otherwise, the method should return null and the entry should be removed from the map.&lt;br /&gt;
*Lambda expressions come in handy when using the compute method, but you will not use lambda expressions to author the method.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|BucketsHashMap|getBucketIndex&amp;lt;br&amp;gt;getBucketFor&amp;lt;br&amp;gt;size&amp;lt;br&amp;gt;put&amp;lt;br&amp;gt;remove&amp;lt;br&amp;gt;get|util.lab.map}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private int getBucketIndex(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private Collection&amp;lt;Entry&amp;lt;K, V&amp;gt;&amp;gt; getBucketFor(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public int size()}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public V put(K key, V value)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public V remove(Object key)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public V get(Object key)}}&lt;br /&gt;
&lt;br /&gt;
A simple way to provide the correct semantics of a map is to simply keep a single collection of key value pairs.  The standard interface for a key value pair is [https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html Map's Entry] with the critical methods:&lt;br /&gt;
&lt;br /&gt;
* K getKey()&lt;br /&gt;
* V getValue()&lt;br /&gt;
* V setValue(V value)&lt;br /&gt;
&lt;br /&gt;
We have provided an implementation of Entry for you called [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/util/KeyMutableValuePair.html KeyMutableValuePair&amp;lt;K,V&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
 BucketsHashMap will use an entry’s key to place an entry into one of several buckets. &lt;br /&gt;
&lt;br /&gt;
If you have not taken CSE 247, this might not make as much sense. In short, these buckets exist to cut down the runtime of searching for entries within the map, as it is much quicker to search 1/total number of buckets than one large bucket which contains every entry.&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Hash_table hash table on wikipedia]&lt;br /&gt;
&lt;br /&gt;
[[File:Hash_table_5_0_1_1_1_1_1_LL.svg|frame|[https://commons.wikimedia.org/wiki/File:Hash_table_5_0_1_1_1_1_1_LL.svg mediawiki hash table image]]]&lt;br /&gt;
&lt;br /&gt;
In this class, you will use the entry’s key’s hashcode to determine which of the buckets it should fall into. In order to calculate the index of the bucket that the entry belongs in, we will make use of the hash function, which in turn uses Math.floorMod to calculate a modulo (remainder or % in Java) based on the number of buckets and the key’s hashcode. We will also make use of the getListFor method, which utilizes the hash method in order to return a '''pointer''' to the correct bucket.&lt;br /&gt;
&lt;br /&gt;
reference material: [https://www.cs.cmu.edu/~adamchik/15-121/lectures/Hashing/hashing.html Concept of Hashing]&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT implement put as a remove followed by an add.  While correct, it is undesirable.  First look for the key and set its value if you find it before resorting to adding a new entry when you cannot find a previous entry with the key. }}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
Throughout the process, refer to the associated tests to check your progress. Feel free to run tests individually depending on which method you are working on or run the test suite in order to run every test in the associated package.&lt;br /&gt;
{{TestSuite|UtilTestSuite|util.lab}}&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
LinkedNodesIterator subtotal: 25&lt;br /&gt;
* Correct hasNext (5)&lt;br /&gt;
* Correct next (10)&lt;br /&gt;
* Correct remove (10)&lt;br /&gt;
&lt;br /&gt;
LinkedNodesCollection subtotal: 20&lt;br /&gt;
* Correct iterator (5)&lt;br /&gt;
* Correct size (5)&lt;br /&gt;
* Correct add (10)&lt;br /&gt;
&lt;br /&gt;
BucketsHashMap subtotal: 45&lt;br /&gt;
* Correct hash (2.5)&lt;br /&gt;
* Correct getBucketFor (2.5)&lt;br /&gt;
* Correct size (5)&lt;br /&gt;
* Correct put (15)&lt;br /&gt;
* Correct remove (10)&lt;br /&gt;
* Correct get (10)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Floodfill_Application&amp;diff=2188</id>
		<title>Floodfill Application</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Floodfill_Application&amp;diff=2188"/>
		<updated>2018-07-23T06:46:59Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Floodfill is an problem that is well-solved recursively.  It allows us an opportunity to think about the similarities and differences between creating a task for each sub-problem and wrapping all of your recursive calls in a single async.  Further, we will harken back to this studio later in the semester when we discuss determinism.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
In this studio, you will be using a parallel and recursive method to create an app that fills in a space with color, much like the paint bucket in [https://www.gimp.org/ GNU Image Manipulation Program].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;hoVbNF8CpBk&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:FloodFillTool.png]]&lt;br /&gt;
[[File:FloodFillShape.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
https://en.wikipedia.org/wiki/Flood_fill&lt;br /&gt;
&lt;br /&gt;
==Video==&lt;br /&gt;
[https://wustl.app.box.com/s/d800l5t04y2dthi4q3t4pddph9ms1d8p Demo Video]&lt;br /&gt;
&lt;br /&gt;
=Mistakes to Avoid=&lt;br /&gt;
{{Warning | Do NOT use &amp;lt;nowiki&amp;gt;==&amp;lt;/nowiki&amp;gt; to compare Colors.  Use Objects.equals(a,b)}.}&lt;br /&gt;
&lt;br /&gt;
==Sequential Implementation Increased Stack Size Requirement==&lt;br /&gt;
For this project, if you decide to first build a sequential version, you will need to change your VM Arguments slightly. In addition to the normal argument that needs to be pasted in for every assignment, you need to add &amp;lt;code&amp;gt;-Xss4m&amp;lt;/code&amp;gt;.  This will increase the size of the call stack, essentially increasing the maximum depth of your recursion.&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/pixels/MutablePixels.html MutablePixels]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/pixels/MutablePixels.html#isInBounds-int-int- isInBounds(x,y)]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/pixels/MutablePixels.html#getColor-int-int- getColor(x,y)]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/pixels/MutablePixels.html#setColor-int-int-javafx.scene.paint.Color- setColor(x,y,color)]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/javafx/api/javafx/scene/paint/Color.html Color]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/javafx/api/javafx/scene/paint/Color.html#equals-java.lang.Object- equals(other)]&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
The class is composed of two methods: floodFill and floodFillKernel.  The entire process in the kernel is triggered from the floodFill method. &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static void floodFill(MutablePixels pixels, Color nextColor, int x, int y)&lt;br /&gt;
			throws InterruptedException, ExecutionException {&lt;br /&gt;
		Color prevColor = pixels.getColor(x, y);&lt;br /&gt;
		if (nextColor.equals(prevColor)) {&lt;br /&gt;
			// pass&lt;br /&gt;
		} else {&lt;br /&gt;
			finish(() -&amp;gt; {&lt;br /&gt;
				floodFillKernel(pixels, prevColor, nextColor, x, y);&lt;br /&gt;
			});&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is so that the kernel can run recursively and asynchronously so the floodFill method can wrap the kernel in an all-inclusive finish.&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|FloodFiller|floodFillKernel|floodfill.studio}}&lt;br /&gt;
&lt;br /&gt;
The kernel should check if the given pixel is in bounds. If it is, it should check if the given pixel matches the targetColor (the color we wish to change). If it is, it should then replace the color with the replacementColor and asynchronously call the method again to repeat the process for the surrounding pixels. The purpose of the assignment is to understand recursion and how to make it work in parallel.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|floodFillKernel}}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Visualization==&lt;br /&gt;
[[File:FloodFillViz.png]]&lt;br /&gt;
{{Viz|FloodFillVizApp|floodfill.viz}}&lt;br /&gt;
===JavaFX Setup===&lt;br /&gt;
In order to run the visualization app you will need to [[Eclipse_Tips#JavaFX_Setup|setup e(fx)clipse]].&lt;br /&gt;
&lt;br /&gt;
==Correctness==&lt;br /&gt;
A test suite exists but is limited and not all that exciting.  Demo to an instructor to get credit for your studio locked in.&lt;br /&gt;
{{TestSuite|FloodFillTestSuite|floodfill}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Threads_and_Executors&amp;diff=2187</id>
		<title>Threads and Executors</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Threads_and_Executors&amp;diff=2187"/>
		<updated>2018-07-23T06:46:01Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [[User:Finn|Finn Voichick]] and [[User:cosgroved|Dennis Cosgrove]]&lt;br /&gt;
=Motivation=&lt;br /&gt;
The [http://x10-lang.org/ X10 family of programming languages], including [https://wiki.rice.edu/confluence/display/HABANERO/Habanero+Extreme+Scale+Software+Research+Project Habanero] and our own modest [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5], provide a less cumbersome way to write parallel programs with [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] and [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#finish-edu.wustl.cse231s.v5.api.CheckedRunnable- finish].&lt;br /&gt;
&lt;br /&gt;
Finish has particularly nice semantics: keeping track of and joining all of its descendant tasks.  &lt;br /&gt;
In this lab we will remove the training wheels for a moment to get some experience with some core Java parallel features [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html Thread] and [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html ExecutorService].&lt;br /&gt;
&lt;br /&gt;
Tracking all of the descendant tasks provides us with an opportunity to use a thread safe data structure ([https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue]) as well as deal with the [[#.28Optional_But_Recommended.29_Join_All_Warm_Up | complications of weakly consistent iterators]].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ Java 8 Concurrency Tutorial: Threads and Executors]&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
==(Optional But Recommended) Join All Warm Up==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue] is a thread safe data structure.  Multiple threads can add and remove from it without fear.  The order they will be in might not be deterministic, but it won't lose anybody.  We will end up using a ConcurrentLinkedQueue to track all of the spawned Futures in the [[#XQuicksort]] section of this lab.&lt;br /&gt;
&lt;br /&gt;
Sadly, [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue's documentation] reports that:&lt;br /&gt;
&lt;br /&gt;
: ''&amp;quot;Iterators are weakly consistent, returning elements reflecting the state of the queue at some point at or since the creation of the iterator.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
This means that if all of the items aren't in the queue when you start iterating through them, then you are not guaranteed to get updated when new items get added.&lt;br /&gt;
&lt;br /&gt;
Therefore, using the standard iterating for loop from &amp;lt;code&amp;gt;ThreadsRightNow&amp;lt;/code&amp;gt; will NOT work for &amp;lt;code&amp;gt;ThreadsEventually&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;/* package-private */ static int joinAllInQueueViaIteration(Queue&amp;lt;Thread&amp;gt; queue) throws InterruptedException {&lt;br /&gt;
	int count = 0;&lt;br /&gt;
	for (Thread thread : queue) {&lt;br /&gt;
		thread.join();&lt;br /&gt;
		count++;&lt;br /&gt;
	}&lt;br /&gt;
	return count;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Think about how you can make sure that all of threads are joined.&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Drain the queue by repeatedly polling until it is empty.  Be sure to actually join the threads.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ThreadsEventually|joinAllInQueueViaPoll|tnx.warmup.joinall}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static int joinAllInQueueViaPoll(Queue&amp;lt;Thread&amp;gt; queue)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: this method should return the number of threads joined.&lt;br /&gt;
&lt;br /&gt;
Completing this optional warm up will help you when you implement [[#XQuicksort]].&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|JoinAllTestSuite|tnx.warmup.joinall}}&lt;br /&gt;
&lt;br /&gt;
==Threads==&lt;br /&gt;
While we strive to make CSE 231 generally applicable across libraries and languages, it would be madness to have a parallel programming class in Java and not have students know how to create a Thread, start it, and join it.  In this section of the lab, you will do just that.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;P8z7dFIdcmM&amp;lt;/youtube&amp;gt; box link: [https://wustl.box.com/s/pngsojhj8291qj8q78ypmzl0jd1l69sw Thread Start and Join]&lt;br /&gt;
===Code To Use===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html interface ThreadFactory]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html#newThread-java.lang.Runnable- newThread]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html class Thread]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable- constructor]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- join]&lt;br /&gt;
&lt;br /&gt;
As always, the [[Reference_Page#Threads|wiki's reference page]] can be of help.&lt;br /&gt;
&lt;br /&gt;
===SimpleThreadFactory===&lt;br /&gt;
{{CodeToImplement|SimpleThreadFactory|newThread|tnx.lab.thread}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|Thread newThread(Runnable target)}}&lt;br /&gt;
&lt;br /&gt;
Create and return a [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable- new thread with the target Runnable parameter] you are passed.&lt;br /&gt;
&lt;br /&gt;
Do *NOT* [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start] this thread.  &lt;br /&gt;
&lt;br /&gt;
Certainly, do *NOT* [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#run-- run] this thread.&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Do_not_pass_Go._Do_not_collect_$200. Do not pass Go.  Do not collect $200.]&lt;br /&gt;
&lt;br /&gt;
To repeat: just create a new Thread with the target Runnable and return it.&lt;br /&gt;
&lt;br /&gt;
===TAgeSum===&lt;br /&gt;
{{CodeToImplement|TAgeSum|sumUpperLowerSplit|tnx.lab.thread}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|int sumUpperLowerSplit(int[] ages, ThreadFactory threadFactory)}}&lt;br /&gt;
&lt;br /&gt;
You will need use the passed in ThreadFactory to [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html#newThread-java.lang.Runnable- create a new thread] or two (at your preference), [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start] any threads you create, and [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join-- join] them.&lt;br /&gt;
&lt;br /&gt;
Think about where you need to start and join any Threads to ensure both correctness and an appropriate amount of parallelism.&lt;br /&gt;
&lt;br /&gt;
==Executors==&lt;br /&gt;
&amp;lt;youtube&amp;gt;8qh9LMhvNXI&amp;lt;/youtube&amp;gt; &amp;lt;!-- box link: [https://wustl.box.com/s/2pqv6vsbirt6zi4304ycrh7jfgkb0dhi Executor submit and Future get]--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;tuAkLb99sLE&amp;lt;/youtube&amp;gt; &amp;lt;!-- box link: [https://wustl.box.com/s/17q7xupx1tagdnnfg057teme4lbq4w6r Executor invokeAll]--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code To Use===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html interface ExecutorService]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.util.concurrent.Callable- submit(task)]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#invokeAll-java.util.Collection- invokeAll(tasks)]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html interface Future]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-- get()]&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/count/assignment/NucleobaseCounting.html NucleobaseCounting]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/count/assignment/NucleobaseCounting.html#countRangeSequential-byte:A-edu.wustl.cse231s.bioinformatics.Nucleobase-int-int- countRangeSequential(chromosome,targetNucleobase,min,maxExclusive)]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html Slices]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html#createNSlices-byte:A-int- &amp;lt;nowiki&amp;gt;createNSlices(data, numSlices)&amp;lt;/nowiki&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As always, the [[Reference_Page#Executors|wiki's reference page]] can be of help.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
===Mistake To Avoid: Do NOT call shutdown===&lt;br /&gt;
Each method you write will be passed an executor.  You need not (and should NOT) invoke [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown-- shutdown()].  That is the responsibility of whoever created the executor.  For example, a JUnit test would do this if it was appropriate (i.e. it created an executor and was not using the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#commonPool-- common pool]).&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===XNucleobaseCount===&lt;br /&gt;
This part of the assignment should be very familiar as it is to a large degree implementing the [[Nucleobase_Counting|Nucleobase Counting assignment]] with Executors instead of Habanero.  It also adds a divide and conquer implementation of nucleobase counting. &lt;br /&gt;
{{CodeToImplement|XNucleobaseCount|countLowerUpperSplit&amp;lt;br&amp;gt;countNWaySplit&amp;lt;br&amp;gt;countDivideAndConquer&amp;lt;br&amp;gt;countDivideAndConquerKernel|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
{{Tip|Use [http://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/count/assignment/NucleobaseCounting.html#countRangeSequential-byte:A-edu.wustl.cse231s.bioinformatics.Nucleobase-int-int- countRangeSequential()] from [[Nucleobase_Counting]]}}&lt;br /&gt;
====lower upper split====&lt;br /&gt;
{{Parallel|int countLowerUpperSplit(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase)}}&lt;br /&gt;
====n-way split====&lt;br /&gt;
{{Parallel|int countNWaySplit(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int numTasks)}}&lt;br /&gt;
&lt;br /&gt;
Please feel free to use your own [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html Slices] [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/slice/studio/Slices.html#createNSlices-byte:A-int- &amp;lt;nowiki&amp;gt;createNSlices(byte[] data, int numSlices)&amp;lt;/nowiki&amp;gt;].  Then use the [https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html Java for each loop] to iterate over the slices to create your tasks.&lt;br /&gt;
&lt;br /&gt;
====divide-and-conquer====&lt;br /&gt;
{{Parallel|int countDivideAndConquer(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int threshold)}}&lt;br /&gt;
&lt;br /&gt;
This method should just get things going by invoking the countDivideAndConquerKernel on the entire chromosome array.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|int countDivideAndConquerKernel(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int min, int maxExclusive, int threshold)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: When you get down below the threshold and convert from parallel to sequential execution, do NOT feel compelled to build a sequential divide and conquer.  Just invoke countRangeSequential on the remaining range.  It is not like divide and conquer gives you a performance benefit in counting like it would for sorting.&lt;br /&gt;
&lt;br /&gt;
===XQuicksort===&lt;br /&gt;
{{CodeToImplement|XQuicksort|sequentialQuicksort&amp;lt;br&amp;gt;sequentialQuicksortKernel&amp;lt;br&amp;gt;parallelQuicksort&amp;lt;br&amp;gt;parallelQuicksortKernel|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
Quicksort is an oldie but a goodie.  First developed in 1959 and [https://dl.acm.org/citation.cfm?doid=366622.366644 published in 1961] it is still the go to sorting algorithm today.  The JDK8 implementation of [https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-int:A- Arrays.sort(array)] is a DualPivotQuicksort.&lt;br /&gt;
&lt;br /&gt;
Quicksort is also amenable to parallelism.  Once the partitioning is done, both sides of the pivot can be sorted completely independently in parallel.  This lends itself very nicely to the X10 family of languages as you can freely [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/edu/wustl/cse231s/rice/habanero/Habanero.html#async-edu.rice.hj.api.HjSuspendable- async] as you divide and conquer, then join all of the tasks by wrapping it all in a single call to [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/edu/wustl/cse231s/rice/habanero/Habanero.html#finish-edu.rice.hj.api.HjSuspendable- finish].  &lt;br /&gt;
&lt;br /&gt;
In this assignment you will mimic this behavior by submitting tasks to an executor, tracking the returned futures in in a ConcurrentLinkedQueue, then invoking get on all of those futures to mimic the single finish.&lt;br /&gt;
&lt;br /&gt;
{{Warning| [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkQueue]'s iterators are weakly consistent.  Do the [[#.28Optional_But_Recommended.29_Join_All_Warm_Up | Join All Warm Up]] to gain experience with handling this issue. }}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;jP2998MvX9o&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;iqnvIeIhGPw&amp;lt;/youtube&amp;gt; [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/be41f5f2b11a4445aa4be174e94f1717/16 RiceX Lecture on Quicksort]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;SLauY6PpjW4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning|Unlike in Sarkar's and McDowell’s videos which use inclusive maximums, CSE 231 consistently uses exclusive maximums to avoid having to subtract 1 all of the time.}}&lt;br /&gt;
&lt;br /&gt;
====The Core Questions====&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
====Code To Use====&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sort/core/quick/Partitioner.html interface Partitioner]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sort/core/quick/Partitioner.html#partitionRange-int:A-int-int- partitionRange(data,min,maxExclusive)]&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sort/core/quick/PivotLocation.html class PivotLocation]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sort/core/quick/PivotLocation.html#getLeftSidesUpperExclusive-- getLeftSidesUpperExclusive()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/sort/core/quick/PivotLocation.html#getRightSidesLowerInclusive-- getRightSidesLowerInclusive()]&lt;br /&gt;
&lt;br /&gt;
====sequential====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
The provided sequentialQuicksort method hopes to get you on the right track.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static void sequentialQuicksort(int[] array) {&lt;br /&gt;
	sequentialQuicksortKernel(array, 0, array.length);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential|void sequentialQuicksort(int[] data, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|void sequentialQuicksortKernel(int[] data, int min, int maxExclusive, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
====parallel====&lt;br /&gt;
{{Parallel|void parallelQuicksort(ExecutorService executor, int[] data, int threshold, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
{{Tip | Make sure to use a thread safe data structure like [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue] and NOT an unsafe data structure like [https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html LinkedList]. }}&lt;br /&gt;
&lt;br /&gt;
{{Tip | &amp;lt;code&amp;gt;return null;&amp;lt;/code&amp;gt; from your lambdas to invoke the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.util.concurrent.Callable- overloaded Callable version of submit(task)] to deal with the checked exceptions. }}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|void parallelQuicksortKernel(ExecutorService executor, int[] data, int min, int maxExclusive, Queue&amp;lt;Future&amp;lt;?&amp;gt;&amp;gt; futures, int threshold, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
==(Optional) Parallel Partition Challenge==&lt;br /&gt;
The partitioning step can also be done in [http://www.classes.cec.wustl.edu/~cse341/web/handouts/lecture07.pdf parallel with scan].  While not particularly practical, it can get the CPL down to &amp;lt;math&amp;gt;\mathcal{O}(\lg^k{}n)&amp;lt;/math&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For details on how to complete this challenge, check out: [[Quicksort_Parallel_Partitioner]]&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|ThreadsAndExecutorsTestSuite|tnx.lab}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|ThreadsTestSuite|tnx.lab.thread}}&lt;br /&gt;
{{TestSuite|NucleobaseExecutorTestSuite|tnx.lab.executor}}&lt;br /&gt;
{{TestSuite|QuicksortExecutorTestSuite|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|NucleobaseCountTiming|tnx.lab.executor}}&lt;br /&gt;
{{Performance|QuicksortTiming|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
SimpleThreadFactory subtotal: 5&lt;br /&gt;
* Correct newThread (5)&lt;br /&gt;
&lt;br /&gt;
TAgeSum subtotal: 10&lt;br /&gt;
* Correct sumUpperLowerSplit (10)&lt;br /&gt;
&lt;br /&gt;
XNucleobaseCount subtotal: 40&lt;br /&gt;
* Correct count2WaySplit (10)&lt;br /&gt;
* Correct countNWaySplit (15)&lt;br /&gt;
* Correct countDivideAndConquer and countDivideAndConquerKernel (15)&lt;br /&gt;
&lt;br /&gt;
XQuicksort subtotal: 35&lt;br /&gt;
* Correct sequentialQuicksort and sequentialQuicksortKernel (10)&lt;br /&gt;
* Correct parallelQuicksort and parallelQuicksortKernel (25)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;br /&gt;
&lt;br /&gt;
=Pledge, Acknowledgments, Citations=&lt;br /&gt;
As always, fill out the Pledge, Acknowledgments, and Citations file: &amp;lt;code&amp;gt;lab3-pledge-acknowledgments-citations.txt&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2186</id>
		<title>MatrixMultiply</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2186"/>
		<updated>2018-07-23T06:41:36Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
We gain experience using the parallel for loop constructs.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&lt;br /&gt;
Matrix multiplication is a simple mathematical operation which we will replicate in this studio. For our purposes, we will only deal with square matrices (same number of rows and columns). However, we will approach this problem with several different parallel constructs and approaches.&lt;br /&gt;
&lt;br /&gt;
For those unfamiliar on how to multiply two matrices, take a look at these overviews:&lt;br /&gt;
* [https://www.mathsisfun.com/algebra/matrix-multiplying.html Math Is Fun]&lt;br /&gt;
* [http://mathworld.wolfram.com/MatrixMultiplication.html Wolfram MathWorld]&lt;br /&gt;
* [https://en.wikipedia.org/wiki/Matrix_multiplication Wikipedia]&lt;br /&gt;
==Math Definition==&lt;br /&gt;
If &amp;lt;math&amp;gt;\mathbf{A}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;n \times m&amp;lt;/math&amp;gt; matrix and &amp;lt;math&amp;gt;\mathbf{B}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;m  \times p&amp;lt;/math&amp;gt; matrix&lt;br /&gt;
&lt;br /&gt;
for each i=[0..n) and for each j=[0..p)&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;(\mathbf{A}\mathbf{B})_{ij} = \sum_{k=1}^m A_{ik}B_{kj}&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/wiki/Matrix_multiplication#General_definition_of_the_matrix_product Matrix Multiplication on Wikipedia]&lt;br /&gt;
&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
The point of the required portion of this studio is not to struggle with matrix multiplication, but rather to get some experience with the parallel for loop constructs in Habanero.&lt;br /&gt;
&lt;br /&gt;
Feel free to use the provided sequential implementation in SequentialMatrixMultiplier as a reference:&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public double[][] multiply(double[][] a, double[][] b) {&lt;br /&gt;
		double[][] result = MatrixUtils.createMultiplyResultBufferInitializedToZeros(a, b);&lt;br /&gt;
		int n = a.length;&lt;br /&gt;
		int m = a[0].length;&lt;br /&gt;
		int p = b[0].length;&lt;br /&gt;
		for (int i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
			for (int j = 0; j &amp;lt; p; j++) {&lt;br /&gt;
				// NOTE: result is already initialized to 0.0&lt;br /&gt;
				// result[i][j] = 0.0;&lt;br /&gt;
				for (int k = 0; k &amp;lt; m; k++) {&lt;br /&gt;
					result[i][j] += a[i][k] * b[k][j];&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
		return result;&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[[Reference_Page#Parallel_Loops|Wiki's reference page]]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(start, endExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(chunked(), start, endExclusive, body)]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(aMin, aMaxExclusive, bMin, bMaxExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(chunked(), aMin, aMaxExclusive, bMin, bMaxExclusive, body)]&lt;br /&gt;
&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-- chunked()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-int- chunked(size)]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Habanero Documentation==&lt;br /&gt;
WARNING: Habanero from Rice is '''inclusive'''.  So, its loops are specified from 0 to n-1.  CSE 231's wrapper is '''exclusive on max''' so it is specified 0 to n.&lt;br /&gt;
&lt;br /&gt;
[http://pasiphae.cs.rice.edu/#hjlib-for Habanero for loops]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Common Mistakes To Avoid=&lt;br /&gt;
{{Warning|CSE 231 is exclusive on max.  While we implemented our own X10/Habanero we changed forall(0, n-1, body) to forall(0, n, body) for everything.}}&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
&lt;br /&gt;
There are three methods you will need to implement, all of which are different ways to use parallel for loops to solve the problem. To assist you, the sequential implementation has already been completed for you. We recommend starting from the top and working your way down. There is also an optional recursive implementation and a manual grouping implementation which has been done for you (this is just to demonstrate how chunking works behind the scenes).&lt;br /&gt;
&lt;br /&gt;
==ForallForallMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|ForallForallMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, you will simply convert the sequential solution into a parallel one using two forall loops.&lt;br /&gt;
&lt;br /&gt;
==Forall2dMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will cut down the syntax of the two forall implementation with the use of HJ’s &amp;lt;code&amp;gt;forall2d&amp;lt;/code&amp;gt; method. Functionally, this method serves the purpose of using two forall loops. [[Reference_Page#Forall_2d|Take a look at the reference page]] if you have questions on how to utilize this loop.&lt;br /&gt;
&lt;br /&gt;
==Forall2dChunkedMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dChunkedMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will add a minor performance boost to the process by using the forall-chunked construct. Although similar to the traditional forall loop, it increases performance using iteration grouping/chunking. This topic is discussed in detail in this [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/6349730bb2a149a0b33fa23db7afddee/?activate_block_id=i4x%3A%2F%2FRiceX%2FCOMP322%2Fsequential%2F6349730bb2a149a0b33fa23db7afddee Rice video] and explained in the [http://pasiphae.cs.rice.edu/#hjlib-for-parallelchunkediterationwithimplicitfinish HJ documentation]. There is no need to specify anything, allow the runtime to determine the chunking.&lt;br /&gt;
&lt;br /&gt;
NOTE: we contemplated also assigning building a 1D forall chunked version.  We deemed this more work that it was worth given that you are already building the 2d version.  Just know that forall(chunked(), ...) exists for 1d loops as well.  &lt;br /&gt;
&lt;br /&gt;
Use chunking.  It is a nice feature.&lt;br /&gt;
&lt;br /&gt;
=Optional Divide and Conquer Challenges=&lt;br /&gt;
In this implementation, you will solve the matrix multiply problem sequentially and in parallel using recursion. Although this class should be able to take in a matrix of any size, try to imagine this as a 2x2 matrix in order to make it easier to solve. Once you solve the sequential method, the parallel method should look very similar with exception of an async/finish block.&lt;br /&gt;
&lt;br /&gt;
In order to obtain the desired result matrix, you will need to recursively call the correct submatrices for each of the four result submatrices. Imagining this as a 2x2 matrix, remember that the dot products of the rows of the first matrix and the columns of the second matrix create the result matrix.&lt;br /&gt;
&lt;br /&gt;
Hint: Each result submatrix should have two recursive calls, for a total of eight recursive calls.&lt;br /&gt;
&lt;br /&gt;
==SequentialDivideAndConquerMatrixMultiplier==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SubMatrix|sequentialDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
In &amp;lt;code&amp;gt;class SubMatrix&amp;lt;/code&amp;gt;, method &amp;lt;code&amp;gt;sequentialDivideAndConquerMultiplyKernel&amp;lt;/code&amp;gt; you will find your base case and the sub matrices prepared for you.  &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
	private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result) {&lt;br /&gt;
		if( result.size == 1 ) {&lt;br /&gt;
			result.values[result.row][result.col] += a.values[a.row][a.col] * b.values[b.row][b.col];&lt;br /&gt;
		} else {&lt;br /&gt;
			SubMatrix a11 = a.newSub11();&lt;br /&gt;
			SubMatrix a12 = a.newSub12();&lt;br /&gt;
			SubMatrix a21 = a.newSub21();&lt;br /&gt;
			SubMatrix a22 = a.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix b11 = b.newSub11();&lt;br /&gt;
			SubMatrix b12 = b.newSub12();&lt;br /&gt;
			SubMatrix b21 = b.newSub21();&lt;br /&gt;
			SubMatrix b22 = b.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix result11 = result.newSub11();&lt;br /&gt;
			SubMatrix result12 = result.newSub12();&lt;br /&gt;
			SubMatrix result21 = result.newSub21();&lt;br /&gt;
			SubMatrix result22 = result.newSub22();&lt;br /&gt;
&lt;br /&gt;
			throw new NotYetImplementedException();&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You simply need to make the appropriate recursive calls to compute the result on the right:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} &amp;amp; \mathbf{A}_{12} \\&lt;br /&gt;
\mathbf{A}_{21} &amp;amp; \mathbf{A}_{22} \\&lt;br /&gt;
\end{pmatrix} \begin{pmatrix}&lt;br /&gt;
\mathbf{B}_{11} &amp;amp; \mathbf{B}_{12} \\&lt;br /&gt;
\mathbf{B}_{21} &amp;amp; \mathbf{B}_{22} \\&lt;br /&gt;
\end{pmatrix} = \begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
==ParallelDivideAndConquerMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|SubMatrix|parallelDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void parallelDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
Again, given the following:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
What computation can be done in parallel?  What computation must be performed sequentially?&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=Provided Example Implementations=&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
==ForallGroupedMatrixMultiplier==&lt;br /&gt;
For 231 we are encouraging you to prefer the use of chunked().  However, if you want greater control over how your loops are broken up, please look to this as an example of how to use forall grouped.&lt;br /&gt;
&lt;br /&gt;
==Forall2dGroupedMatrixMultiplier==&lt;br /&gt;
Same as above but with forall2d.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.studio}}&lt;br /&gt;
==Optional Fun Divide And Conquer Matrix Multiply Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.fun}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|MatrixMultiplicationTiming|matrixmultiply.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2185</id>
		<title>MatrixMultiply</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2185"/>
		<updated>2018-07-23T06:38:59Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Use */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
We gain experience using the parallel for loop constructs.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&lt;br /&gt;
Matrix multiplication is a simple mathematical operation which we will replicate in this studio. For our purposes, we will only deal with square matrices (same number of rows and columns). However, we will approach this problem with several different parallel constructs and approaches.&lt;br /&gt;
&lt;br /&gt;
For those unfamiliar on how to multiply two matrices, take a look at these overviews:&lt;br /&gt;
* [https://www.mathsisfun.com/algebra/matrix-multiplying.html Math Is Fun]&lt;br /&gt;
* [http://mathworld.wolfram.com/MatrixMultiplication.html Wolfram MathWorld]&lt;br /&gt;
* [https://en.wikipedia.org/wiki/Matrix_multiplication Wikipedia]&lt;br /&gt;
==Math Definition==&lt;br /&gt;
If &amp;lt;math&amp;gt;\mathbf{A}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;n \times m&amp;lt;/math&amp;gt; matrix and &amp;lt;math&amp;gt;\mathbf{B}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;m  \times p&amp;lt;/math&amp;gt; matrix&lt;br /&gt;
&lt;br /&gt;
for each i=[0..n) and for each j=[0..p)&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;(\mathbf{A}\mathbf{B})_{ij} = \sum_{k=1}^m A_{ik}B_{kj}&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/wiki/Matrix_multiplication#General_definition_of_the_matrix_product Matrix Multiplication on Wikipedia]&lt;br /&gt;
&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
The point of the required portion of this studio is not to struggle with matrix multiplication, but rather to get some experience with the parallel for loop constructs in Habanero.&lt;br /&gt;
&lt;br /&gt;
Feel free to use the provided sequential implementation in SequentialMatrixMultiplier as a reference:&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public double[][] multiply(double[][] a, double[][] b) {&lt;br /&gt;
		double[][] result = MatrixUtils.createMultiplyResultBufferInitializedToZeros(a, b);&lt;br /&gt;
		int n = a.length;&lt;br /&gt;
		int m = a[0].length;&lt;br /&gt;
		int p = b[0].length;&lt;br /&gt;
		for (int i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
			for (int j = 0; j &amp;lt; p; j++) {&lt;br /&gt;
				// NOTE: result is already initialized to 0.0&lt;br /&gt;
				// result[i][j] = 0.0;&lt;br /&gt;
				for (int k = 0; k &amp;lt; m; k++) {&lt;br /&gt;
					result[i][j] += a[i][k] * b[k][j];&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
		return result;&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[[Reference_Page#Parallel_Loops|Wiki's reference page]]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(start, endExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(chunked(), start, endExclusive, body)]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(aMin, aMaxExclusive, bMin, bMaxExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(chunked(), aMin, aMaxExclusive, bMin, bMaxExclusive, body)]&lt;br /&gt;
&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-- chunked()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-int- chunked(size)]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Habanero Documentation==&lt;br /&gt;
WARNING: Habanero from Rice is '''inclusive'''.  So, its loops are specified from 0 to n-1.  CSE 231's wrapper is '''exclusive on max''' so it is specified 0 to n.&lt;br /&gt;
&lt;br /&gt;
[http://pasiphae.cs.rice.edu/#hjlib-for Habanero for loops]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Common Mistakes To Avoid=&lt;br /&gt;
{{Warning|CSE 231 is exclusive on max.  While we implemented our own X10/Habanero we changed forall(0, n-1, body) to forall(0, n, body) for everything.}}&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
&lt;br /&gt;
There are three methods you will need to implement, all of which are different ways to use parallel for loops to solve the problem. To assist you, the sequential implementation has already been completed for you. We recommend starting from the top and working your way down. There is also an optional recursive implementation and a manual grouping implementation which has been done for you (this is just to demonstrate how chunking works behind the scenes).&lt;br /&gt;
&lt;br /&gt;
==ForallForallMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|ForallForallMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, you will simply convert the sequential solution into a parallel one using two forall loops.&lt;br /&gt;
&lt;br /&gt;
==Forall2dMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will cut down the syntax of the two forall implementation with the use of HJ’s &amp;lt;code&amp;gt;forall2d&amp;lt;/code&amp;gt; method. Functionally, this method serves the purpose of using two forall loops. [[Syntax_of_231#Forall_2d|Take a look at the syntax page]] if you have questions on how to utilize this loop.&lt;br /&gt;
&lt;br /&gt;
==Forall2dChunkedMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dChunkedMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will add a minor performance boost to the process by using the forall-chunked construct. Although similar to the traditional forall loop, it increases performance using iteration grouping/chunking. This topic is discussed in detail in this [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/6349730bb2a149a0b33fa23db7afddee/?activate_block_id=i4x%3A%2F%2FRiceX%2FCOMP322%2Fsequential%2F6349730bb2a149a0b33fa23db7afddee Rice video] and explained in the [http://pasiphae.cs.rice.edu/#hjlib-for-parallelchunkediterationwithimplicitfinish HJ documentation]. There is no need to specify anything, allow the runtime to determine the chunking.&lt;br /&gt;
&lt;br /&gt;
NOTE: we contemplated also assigning building a 1D forall chunked version.  We deemed this more work that it was worth given that you are already building the 2d version.  Just know that forall(chunked(), ...) exists for 1d loops as well.  &lt;br /&gt;
&lt;br /&gt;
Use chunking.  It is a nice feature.&lt;br /&gt;
&lt;br /&gt;
=Optional Divide and Conquer Challenges=&lt;br /&gt;
In this implementation, you will solve the matrix multiply problem sequentially and in parallel using recursion. Although this class should be able to take in a matrix of any size, try to imagine this as a 2x2 matrix in order to make it easier to solve. Once you solve the sequential method, the parallel method should look very similar with exception of an async/finish block.&lt;br /&gt;
&lt;br /&gt;
In order to obtain the desired result matrix, you will need to recursively call the correct submatrices for each of the four result submatrices. Imagining this as a 2x2 matrix, remember that the dot products of the rows of the first matrix and the columns of the second matrix create the result matrix.&lt;br /&gt;
&lt;br /&gt;
Hint: Each result submatrix should have two recursive calls, for a total of eight recursive calls.&lt;br /&gt;
&lt;br /&gt;
==SequentialDivideAndConquerMatrixMultiplier==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SubMatrix|sequentialDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
In &amp;lt;code&amp;gt;class SubMatrix&amp;lt;/code&amp;gt;, method &amp;lt;code&amp;gt;sequentialDivideAndConquerMultiplyKernel&amp;lt;/code&amp;gt; you will find your base case and the sub matrices prepared for you.  &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
	private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result) {&lt;br /&gt;
		if( result.size == 1 ) {&lt;br /&gt;
			result.values[result.row][result.col] += a.values[a.row][a.col] * b.values[b.row][b.col];&lt;br /&gt;
		} else {&lt;br /&gt;
			SubMatrix a11 = a.newSub11();&lt;br /&gt;
			SubMatrix a12 = a.newSub12();&lt;br /&gt;
			SubMatrix a21 = a.newSub21();&lt;br /&gt;
			SubMatrix a22 = a.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix b11 = b.newSub11();&lt;br /&gt;
			SubMatrix b12 = b.newSub12();&lt;br /&gt;
			SubMatrix b21 = b.newSub21();&lt;br /&gt;
			SubMatrix b22 = b.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix result11 = result.newSub11();&lt;br /&gt;
			SubMatrix result12 = result.newSub12();&lt;br /&gt;
			SubMatrix result21 = result.newSub21();&lt;br /&gt;
			SubMatrix result22 = result.newSub22();&lt;br /&gt;
&lt;br /&gt;
			throw new NotYetImplementedException();&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You simply need to make the appropriate recursive calls to compute the result on the right:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} &amp;amp; \mathbf{A}_{12} \\&lt;br /&gt;
\mathbf{A}_{21} &amp;amp; \mathbf{A}_{22} \\&lt;br /&gt;
\end{pmatrix} \begin{pmatrix}&lt;br /&gt;
\mathbf{B}_{11} &amp;amp; \mathbf{B}_{12} \\&lt;br /&gt;
\mathbf{B}_{21} &amp;amp; \mathbf{B}_{22} \\&lt;br /&gt;
\end{pmatrix} = \begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
==ParallelDivideAndConquerMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|SubMatrix|parallelDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void parallelDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
Again, given the following:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
What computation can be done in parallel?  What computation must be performed sequentially?&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=Provided Example Implementations=&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
==ForallGroupedMatrixMultiplier==&lt;br /&gt;
For 231 we are encouraging you to prefer the use of chunked().  However, if you want greater control over how your loops are broken up, please look to this as an example of how to use forall grouped.&lt;br /&gt;
&lt;br /&gt;
==Forall2dGroupedMatrixMultiplier==&lt;br /&gt;
Same as above but with forall2d.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.studio}}&lt;br /&gt;
==Optional Fun Divide And Conquer Matrix Multiply Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.fun}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|MatrixMultiplicationTiming|matrixmultiply.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Race_Conditions_Studio&amp;diff=2184</id>
		<title>Race Conditions Studio</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Race_Conditions_Studio&amp;diff=2184"/>
		<updated>2018-07-23T06:35:41Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Use */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
Race conditions can lead to difficult bugs to find and fix.  We gain experience finding them and fixing them.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
In this studio, you will take in a collection of strings, clean up each string, and add it into another collection of strings concurrently. You will also take in a collection of words, assign a point value to each word, and then put it into a map. Although not terribly exciting, the point of this studio is to teach you how to avoid data races when performing concurrent tasks. In order to accomplish these tasks, you will use the ConcurrentLinkedQueue, array, and ConcurrentHashMap classes.&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
Really think about these questions in each case. Knowing the answers to these will tell you where the problem is.&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html ConcurrentHashMap]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- compute(key, remappingFunction)]&lt;br /&gt;
&lt;br /&gt;
Check out the [[Reference_Page#Compute|compute section of the reference page]] for some insight on this feature of maps&lt;br /&gt;
&lt;br /&gt;
=Code To Debug=&lt;br /&gt;
==Word Score==&lt;br /&gt;
{{CodeToDebug|SuspectWordScore|toCleanedWordsViaArray|racecondition.studio.wordscore}}&lt;br /&gt;
{{Parallel|public static List&amp;lt;String&amp;gt; toCleanedWordsViaArray(Collection&amp;lt;String&amp;gt; sourceLines)}}&lt;br /&gt;
&lt;br /&gt;
==Merge Sort==&lt;br /&gt;
{{CodeToDebug|SuspectMergeSort|parallelMergeSortKernel|racecondition.studio.mergesort}}&lt;br /&gt;
{{Parallel|private static void parallelMergeSortKernel(int[] data, int lowInclusive, int highExclusive, int threshold, Combiner combiner)}}&lt;br /&gt;
&lt;br /&gt;
==Word Count==&lt;br /&gt;
{{CodeToDebug|SuspectWordCountTest|countWords|racecondition.studio.wordcount}}&lt;br /&gt;
{{Parallel|public static Map&amp;lt;String, Integer&amp;gt; countWords(Iterable&amp;lt;String&amp;gt; words)}}&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|RaceConditionTestSuite|racecondition.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Warning|Run Tests Repeatedly To Better Determine That You Are Not Just Getting A Lucky Run.}}&lt;br /&gt;
&lt;br /&gt;
{{TestSuite|RepeatRaceConditionTestSuite|racecondition.studio.bettersafethansorry}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=Where to Start=&lt;br /&gt;
&lt;br /&gt;
Navigate to the '''data races''' directory. The &amp;lt;code&amp;gt;WordScoreDataRace.java&amp;lt;/code&amp;gt; class is the only one you will need to alter, but the &amp;lt;code&amp;gt;WordScoreUtils.java&amp;lt;/code&amp;gt; class contains useful methods that will help with the studio.&lt;br /&gt;
&lt;br /&gt;
==toCleanedWords==&lt;br /&gt;
&lt;br /&gt;
This method should take in a collection of strings, clean it, then add the strings into another collection of strings. The &amp;lt;code&amp;gt;WordScoreUtils.toCleandWords()&amp;lt;/code&amp;gt; method should come in handy for cleaning up the string. All of this should be done in parallel and you should use a ConcurrentLinkedQueue to accomplish this task.&lt;br /&gt;
&lt;br /&gt;
Hint: try using the non-concurrent equivalent and see what happens.&lt;br /&gt;
&lt;br /&gt;
==toCleanedWordsViaArray==&lt;br /&gt;
&lt;br /&gt;
This method should do the same thing as the toCleandWords method, but it should use arrays to avoid a data race.&lt;br /&gt;
Hint: use the Arrays.asList() method to turn your array result into a list so that you can return the data structure the method desires.&lt;br /&gt;
&lt;br /&gt;
==createLetterToScoreMap==&lt;br /&gt;
&lt;br /&gt;
This method should take in a collection of strings, assign a point value to the string, then put it into a map. The map should be composed of the words and their associated point values. The &amp;lt;code&amp;gt;WordScoreUtils.calculateScore()&amp;lt;/code&amp;gt; method should come in handy for assigning the correct point value for each word. If the map already contains a given word (there is a duplicate word), nothing should be done to the map.&lt;br /&gt;
&lt;br /&gt;
==createLetterToScoreMapViaArray==&lt;br /&gt;
&lt;br /&gt;
This method should do the same thing as the createLetterToScoreMap method, but it should use an array of entries to avoid a data race. To do this, the &amp;lt;code&amp;gt;EntryUtils.createEntryArray()&amp;lt;/code&amp;gt; method should come in handy. For each string within the collection, get the point value as you did before and create a new entry for the array using the &amp;lt;code&amp;gt;EntryUtils.createEntry()&amp;lt;/code&amp;gt; method. You can convert the array of entries into a map using the &amp;lt;code&amp;gt;EntryUtils.createTreeMapFromArrayOfEntries()&amp;lt;/code&amp;gt; method.&lt;br /&gt;
--&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Threads_and_Executors&amp;diff=2183</id>
		<title>Threads and Executors</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Threads_and_Executors&amp;diff=2183"/>
		<updated>2018-07-23T06:34:36Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Use */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [[User:Finn|Finn Voichick]] and [[User:cosgroved|Dennis Cosgrove]]&lt;br /&gt;
=Motivation=&lt;br /&gt;
The [http://x10-lang.org/ X10 family of programming languages], including [https://wiki.rice.edu/confluence/display/HABANERO/Habanero+Extreme+Scale+Software+Research+Project Habanero] and our own modest [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html V5], provide a less cumbersome way to write parallel programs with [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] and [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#finish-edu.wustl.cse231s.v5.api.CheckedRunnable- finish].&lt;br /&gt;
&lt;br /&gt;
Finish has particularly nice semantics: keeping track of and joining all of its descendant tasks.  &lt;br /&gt;
In this lab we will remove the training wheels for a moment to get some experience with some core Java parallel features [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html Thread] and [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html ExecutorService].&lt;br /&gt;
&lt;br /&gt;
Tracking all of the descendant tasks provides us with an opportunity to use a thread safe data structure ([https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue]) as well as deal with the [[#.28Optional_But_Recommended.29_Join_All_Warm_Up | complications of weakly consistent iterators]].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ Java 8 Concurrency Tutorial: Threads and Executors]&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
==(Optional But Recommended) Join All Warm Up==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue] is a thread safe data structure.  Multiple threads can add and remove from it without fear.  The order they will be in might not be deterministic, but it won't lose anybody.  We will end up using a ConcurrentLinkedQueue to track all of the spawned Futures in the [[#XQuicksort]] section of this lab.&lt;br /&gt;
&lt;br /&gt;
Sadly, [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue's documentation] reports that:&lt;br /&gt;
&lt;br /&gt;
: ''&amp;quot;Iterators are weakly consistent, returning elements reflecting the state of the queue at some point at or since the creation of the iterator.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
This means that if all of the items aren't in the queue when you start iterating through them, then you are not guaranteed to get updated when new items get added.&lt;br /&gt;
&lt;br /&gt;
Therefore, using the standard iterating for loop from &amp;lt;code&amp;gt;ThreadsRightNow&amp;lt;/code&amp;gt; will NOT work for &amp;lt;code&amp;gt;ThreadsEventually&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;/* package-private */ static int joinAllInQueueViaIteration(Queue&amp;lt;Thread&amp;gt; queue) throws InterruptedException {&lt;br /&gt;
	int count = 0;&lt;br /&gt;
	for (Thread thread : queue) {&lt;br /&gt;
		thread.join();&lt;br /&gt;
		count++;&lt;br /&gt;
	}&lt;br /&gt;
	return count;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Think about how you can make sure that all of threads are joined.&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Drain the queue by repeatedly polling until it is empty.  Be sure to actually join the threads.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ThreadsEventually|joinAllInQueueViaPoll|tnx.warmup.joinall}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static int joinAllInQueueViaPoll(Queue&amp;lt;Thread&amp;gt; queue)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: this method should return the number of threads joined.&lt;br /&gt;
&lt;br /&gt;
Completing this optional warm up will help you when you implement [[#XQuicksort]].&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|JoinAllTestSuite|tnx.warmup.joinall}}&lt;br /&gt;
&lt;br /&gt;
==Threads==&lt;br /&gt;
While we strive to make CSE 231 generally applicable across libraries and languages, it would be madness to have a parallel programming class in Java and not have students know how to create a Thread, start it, and join it.  In this section of the lab, you will do just that.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;P8z7dFIdcmM&amp;lt;/youtube&amp;gt; box link: [https://wustl.box.com/s/pngsojhj8291qj8q78ypmzl0jd1l69sw Thread Start and Join]&lt;br /&gt;
===Code To Use===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html interface ThreadFactory]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html#newThread-java.lang.Runnable- newThread]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html class Thread]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable- constructor]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- join]&lt;br /&gt;
&lt;br /&gt;
As always, the [[Reference_Page#Threads|wiki's reference page]] can be of help.&lt;br /&gt;
&lt;br /&gt;
===SimpleThreadFactory===&lt;br /&gt;
{{CodeToImplement|SimpleThreadFactory|newThread|tnx.lab.thread}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|Thread newThread(Runnable target)}}&lt;br /&gt;
&lt;br /&gt;
Create and return a [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable- new thread with the target Runnable parameter] you are passed.&lt;br /&gt;
&lt;br /&gt;
Do *NOT* [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start] this thread.  &lt;br /&gt;
&lt;br /&gt;
Certainly, do *NOT* [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#run-- run] this thread.&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Do_not_pass_Go._Do_not_collect_$200. Do not pass Go.  Do not collect $200.]&lt;br /&gt;
&lt;br /&gt;
To repeat: just create a new Thread with the target Runnable and return it.&lt;br /&gt;
&lt;br /&gt;
===TAgeSum===&lt;br /&gt;
{{CodeToImplement|TAgeSum|sumUpperLowerSplit|tnx.lab.thread}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|int sumUpperLowerSplit(int[] ages, ThreadFactory threadFactory)}}&lt;br /&gt;
&lt;br /&gt;
You will need use the passed in ThreadFactory to [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html#newThread-java.lang.Runnable- create a new thread] or two (at your preference), [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start] any threads you create, and [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join-- join] them.&lt;br /&gt;
&lt;br /&gt;
Think about where you need to start and join any Threads to ensure both correctness and an appropriate amount of parallelism.&lt;br /&gt;
&lt;br /&gt;
==Executors==&lt;br /&gt;
&amp;lt;youtube&amp;gt;8qh9LMhvNXI&amp;lt;/youtube&amp;gt; &amp;lt;!-- box link: [https://wustl.box.com/s/2pqv6vsbirt6zi4304ycrh7jfgkb0dhi Executor submit and Future get]--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;tuAkLb99sLE&amp;lt;/youtube&amp;gt; &amp;lt;!-- box link: [https://wustl.box.com/s/17q7xupx1tagdnnfg057teme4lbq4w6r Executor invokeAll]--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code To Use===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html interface ExecutorService]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.util.concurrent.Callable- submit(task)]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#invokeAll-java.util.Collection- invokeAll(tasks)]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html interface Future]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-- get()]&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/count/assignment/NucleobaseCounting.html NucleobaseCounting]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/count/assignment/NucleobaseCounting.html#countRangeSequential-byte:A-edu.wustl.cse231s.bioinformatics.Nucleobase-int-int- countRangeSequential(chromosome,targetNucleobase,min,maxExclusive)]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html Slices]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html#createNSlices-byte:A-int- &amp;lt;nowiki&amp;gt;createNSlices(data, numSlices)&amp;lt;/nowiki&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As always, the [[Reference_Page#Executors|wiki's reference page]] can be of help.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
===Mistake To Avoid: Do NOT call shutdown===&lt;br /&gt;
Each method you write will be passed an executor.  You need not (and should NOT) invoke [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown-- shutdown()].  That is the responsibility of whoever created the executor.  For example, a JUnit test would do this if it was appropriate (i.e. it created an executor and was not using the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#commonPool-- common pool]).&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===XNucleobaseCount===&lt;br /&gt;
This part of the assignment should be very familiar as it is to a large degree implementing the [[Nucleobase_Counting|Nucleobase Counting assignment]] with Executors instead of Habanero.  It also adds a divide and conquer implementation of nucleobase counting. &lt;br /&gt;
{{CodeToImplement|XNucleobaseCount|countLowerUpperSplit&amp;lt;br&amp;gt;countNWaySplit&amp;lt;br&amp;gt;countDivideAndConquer&amp;lt;br&amp;gt;countDivideAndConquerKernel|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
{{Tip|Use [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/count/assignment/NucleobaseCounting.html#countRangeSequential-byte:A-edu.wustl.cse231s.bioinformatics.Nucleobase-int-int- countRangeSequential()] from [[Nucleobase_Counting]]}}&lt;br /&gt;
====lower upper split====&lt;br /&gt;
{{Parallel|int countLowerUpperSplit(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase)}}&lt;br /&gt;
====n-way split====&lt;br /&gt;
{{Parallel|int countNWaySplit(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int numTasks)}}&lt;br /&gt;
&lt;br /&gt;
Please feel free to use your own [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html Slices] [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html#createNSlices-byte:A-int- &amp;lt;nowiki&amp;gt;createNSlices(byte[] data, int numSlices)&amp;lt;/nowiki&amp;gt;].  Then use the [https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html Java for each loop] to iterate over the slices to create your tasks.&lt;br /&gt;
&lt;br /&gt;
====divide-and-conquer====&lt;br /&gt;
{{Parallel|int countDivideAndConquer(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int threshold)}}&lt;br /&gt;
&lt;br /&gt;
This method should just get things going by invoking the countDivideAndConquerKernel on the entire chromosome array.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|int countDivideAndConquerKernel(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int min, int maxExclusive, int threshold)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: When you get down below the threshold and convert from parallel to sequential execution, do NOT feel compelled to build a sequential divide and conquer.  Just invoke countRangeSequential on the remaining range.  It is not like divide and conquer gives you a performance benefit in counting like it would for sorting.&lt;br /&gt;
&lt;br /&gt;
===XQuicksort===&lt;br /&gt;
{{CodeToImplement|XQuicksort|sequentialQuicksort&amp;lt;br&amp;gt;sequentialQuicksortKernel&amp;lt;br&amp;gt;parallelQuicksort&amp;lt;br&amp;gt;parallelQuicksortKernel|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
Quicksort is an oldie but a goodie.  First developed in 1959 and [https://dl.acm.org/citation.cfm?doid=366622.366644 published in 1961] it is still the go to sorting algorithm today.  The JDK8 implementation of [https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-int:A- Arrays.sort(array)] is a DualPivotQuicksort.&lt;br /&gt;
&lt;br /&gt;
Quicksort is also amenable to parallelism.  Once the partitioning is done, both sides of the pivot can be sorted completely independently in parallel.  This lends itself very nicely to the X10 family of languages as you can freely [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/edu/wustl/cse231s/rice/habanero/Habanero.html#async-edu.rice.hj.api.HjSuspendable- async] as you divide and conquer, then join all of the tasks by wrapping it all in a single call to [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/edu/wustl/cse231s/rice/habanero/Habanero.html#finish-edu.rice.hj.api.HjSuspendable- finish].  &lt;br /&gt;
&lt;br /&gt;
In this assignment you will mimic this behavior by submitting tasks to an executor, tracking the returned futures in in a ConcurrentLinkedQueue, then invoking get on all of those futures to mimic the single finish.&lt;br /&gt;
&lt;br /&gt;
{{Warning| [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkQueue]'s iterators are weakly consistent.  Do the [[#.28Optional_But_Recommended.29_Join_All_Warm_Up | Join All Warm Up]] to gain experience with handling this issue. }}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;jP2998MvX9o&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;iqnvIeIhGPw&amp;lt;/youtube&amp;gt; [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/be41f5f2b11a4445aa4be174e94f1717/16 RiceX Lecture on Quicksort]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;SLauY6PpjW4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning|Unlike in Sarkar's and McDowell’s videos which use inclusive maximums, CSE 231 consistently uses exclusive maximums to avoid having to subtract 1 all of the time.}}&lt;br /&gt;
&lt;br /&gt;
====The Core Questions====&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
====Code To Use====&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/Partitioner.html interface Partitioner]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/Partitioner.html#partitionRange-int:A-int-int- partitionRange(data,min,maxExclusive)]&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/PivotLocation.html class PivotLocation]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/PivotLocation.html#getLeftSidesUpperExclusive-- getLeftSidesUpperExclusive()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/PivotLocation.html#getRightSidesLowerInclusive-- getRightSidesLowerInclusive()]&lt;br /&gt;
&lt;br /&gt;
====sequential====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
The provided sequentialQuicksort method hopes to get you on the right track.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static void sequentialQuicksort(int[] array) {&lt;br /&gt;
	sequentialQuicksortKernel(array, 0, array.length);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential|void sequentialQuicksort(int[] data, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|void sequentialQuicksortKernel(int[] data, int min, int maxExclusive, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
====parallel====&lt;br /&gt;
{{Parallel|void parallelQuicksort(ExecutorService executor, int[] data, int threshold, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
{{Tip | Make sure to use a thread safe data structure like [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue] and NOT an unsafe data structure like [https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html LinkedList]. }}&lt;br /&gt;
&lt;br /&gt;
{{Tip | &amp;lt;code&amp;gt;return null;&amp;lt;/code&amp;gt; from your lambdas to invoke the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.util.concurrent.Callable- overloaded Callable version of submit(task)] to deal with the checked exceptions. }}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|void parallelQuicksortKernel(ExecutorService executor, int[] data, int min, int maxExclusive, Queue&amp;lt;Future&amp;lt;?&amp;gt;&amp;gt; futures, int threshold, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
==(Optional) Parallel Partition Challenge==&lt;br /&gt;
The partitioning step can also be done in [http://www.classes.cec.wustl.edu/~cse341/web/handouts/lecture07.pdf parallel with scan].  While not particularly practical, it can get the CPL down to &amp;lt;math&amp;gt;\mathcal{O}(\lg^k{}n)&amp;lt;/math&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For details on how to complete this challenge, check out: [[Quicksort_Parallel_Partitioner]]&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|ThreadsAndExecutorsTestSuite|tnx.lab}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|ThreadsTestSuite|tnx.lab.thread}}&lt;br /&gt;
{{TestSuite|NucleobaseExecutorTestSuite|tnx.lab.executor}}&lt;br /&gt;
{{TestSuite|QuicksortExecutorTestSuite|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|NucleobaseCountTiming|tnx.lab.executor}}&lt;br /&gt;
{{Performance|QuicksortTiming|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
SimpleThreadFactory subtotal: 5&lt;br /&gt;
* Correct newThread (5)&lt;br /&gt;
&lt;br /&gt;
TAgeSum subtotal: 10&lt;br /&gt;
* Correct sumUpperLowerSplit (10)&lt;br /&gt;
&lt;br /&gt;
XNucleobaseCount subtotal: 40&lt;br /&gt;
* Correct count2WaySplit (10)&lt;br /&gt;
* Correct countNWaySplit (15)&lt;br /&gt;
* Correct countDivideAndConquer and countDivideAndConquerKernel (15)&lt;br /&gt;
&lt;br /&gt;
XQuicksort subtotal: 35&lt;br /&gt;
* Correct sequentialQuicksort and sequentialQuicksortKernel (10)&lt;br /&gt;
* Correct parallelQuicksort and parallelQuicksortKernel (25)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;br /&gt;
&lt;br /&gt;
=Pledge, Acknowledgments, Citations=&lt;br /&gt;
As always, fill out the Pledge, Acknowledgments, and Citations file: &amp;lt;code&amp;gt;lab3-pledge-acknowledgments-citations.txt&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Threads_and_Executors&amp;diff=2182</id>
		<title>Threads and Executors</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Threads_and_Executors&amp;diff=2182"/>
		<updated>2018-07-23T06:33:40Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Code To Use */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;credit for this assignment: [[User:Finn|Finn Voichick]] and [[User:cosgroved|Dennis Cosgrove]]&lt;br /&gt;
=Motivation=&lt;br /&gt;
The [http://x10-lang.org/ X10 family of programming languages], including [https://wiki.rice.edu/confluence/display/HABANERO/Habanero+Extreme+Scale+Software+Research+Project Habanero] and our own modest [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html V5], provide a less cumbersome way to write parallel programs with [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] and [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#finish-edu.wustl.cse231s.v5.api.CheckedRunnable- finish].&lt;br /&gt;
&lt;br /&gt;
Finish has particularly nice semantics: keeping track of and joining all of its descendant tasks.  &lt;br /&gt;
In this lab we will remove the training wheels for a moment to get some experience with some core Java parallel features [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html Thread] and [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html ExecutorService].&lt;br /&gt;
&lt;br /&gt;
Tracking all of the descendant tasks provides us with an opportunity to use a thread safe data structure ([https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue]) as well as deal with the [[#.28Optional_But_Recommended.29_Join_All_Warm_Up | complications of weakly consistent iterators]].&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
[http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ Java 8 Concurrency Tutorial: Threads and Executors]&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
==(Optional But Recommended) Join All Warm Up==&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue] is a thread safe data structure.  Multiple threads can add and remove from it without fear.  The order they will be in might not be deterministic, but it won't lose anybody.  We will end up using a ConcurrentLinkedQueue to track all of the spawned Futures in the [[#XQuicksort]] section of this lab.&lt;br /&gt;
&lt;br /&gt;
Sadly, [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue's documentation] reports that:&lt;br /&gt;
&lt;br /&gt;
: ''&amp;quot;Iterators are weakly consistent, returning elements reflecting the state of the queue at some point at or since the creation of the iterator.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
This means that if all of the items aren't in the queue when you start iterating through them, then you are not guaranteed to get updated when new items get added.&lt;br /&gt;
&lt;br /&gt;
Therefore, using the standard iterating for loop from &amp;lt;code&amp;gt;ThreadsRightNow&amp;lt;/code&amp;gt; will NOT work for &amp;lt;code&amp;gt;ThreadsEventually&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;/* package-private */ static int joinAllInQueueViaIteration(Queue&amp;lt;Thread&amp;gt; queue) throws InterruptedException {&lt;br /&gt;
	int count = 0;&lt;br /&gt;
	for (Thread thread : queue) {&lt;br /&gt;
		thread.join();&lt;br /&gt;
		count++;&lt;br /&gt;
	}&lt;br /&gt;
	return count;&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Think about how you can make sure that all of threads are joined.&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Drain the queue by repeatedly polling until it is empty.  Be sure to actually join the threads.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|ThreadsEventually|joinAllInQueueViaPoll|tnx.warmup.joinall}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static int joinAllInQueueViaPoll(Queue&amp;lt;Thread&amp;gt; queue)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: this method should return the number of threads joined.&lt;br /&gt;
&lt;br /&gt;
Completing this optional warm up will help you when you implement [[#XQuicksort]].&lt;br /&gt;
&lt;br /&gt;
===Testing Your Solution===&lt;br /&gt;
====Correctness====&lt;br /&gt;
{{TestSuite|JoinAllTestSuite|tnx.warmup.joinall}}&lt;br /&gt;
&lt;br /&gt;
==Threads==&lt;br /&gt;
While we strive to make CSE 231 generally applicable across libraries and languages, it would be madness to have a parallel programming class in Java and not have students know how to create a Thread, start it, and join it.  In this section of the lab, you will do just that.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;P8z7dFIdcmM&amp;lt;/youtube&amp;gt; box link: [https://wustl.box.com/s/pngsojhj8291qj8q78ypmzl0jd1l69sw Thread Start and Join]&lt;br /&gt;
===Code To Use===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html interface ThreadFactory]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html#newThread-java.lang.Runnable- newThread]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html class Thread]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable- constructor]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- join]&lt;br /&gt;
&lt;br /&gt;
As always, the [[Reference_Page#Threads|wiki's reference page]] can be of help.&lt;br /&gt;
&lt;br /&gt;
===SimpleThreadFactory===&lt;br /&gt;
{{CodeToImplement|SimpleThreadFactory|newThread|tnx.lab.thread}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|Thread newThread(Runnable target)}}&lt;br /&gt;
&lt;br /&gt;
Create and return a [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#Thread-java.lang.Runnable- new thread with the target Runnable parameter] you are passed.&lt;br /&gt;
&lt;br /&gt;
Do *NOT* [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start] this thread.  &lt;br /&gt;
&lt;br /&gt;
Certainly, do *NOT* [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#run-- run] this thread.&lt;br /&gt;
&lt;br /&gt;
[https://en.wikipedia.org/wiki/Do_not_pass_Go._Do_not_collect_$200. Do not pass Go.  Do not collect $200.]&lt;br /&gt;
&lt;br /&gt;
To repeat: just create a new Thread with the target Runnable and return it.&lt;br /&gt;
&lt;br /&gt;
===TAgeSum===&lt;br /&gt;
{{CodeToImplement|TAgeSum|sumUpperLowerSplit|tnx.lab.thread}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|int sumUpperLowerSplit(int[] ages, ThreadFactory threadFactory)}}&lt;br /&gt;
&lt;br /&gt;
You will need use the passed in ThreadFactory to [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadFactory.html#newThread-java.lang.Runnable- create a new thread] or two (at your preference), [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start-- start] any threads you create, and [https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join-- join] them.&lt;br /&gt;
&lt;br /&gt;
Think about where you need to start and join any Threads to ensure both correctness and an appropriate amount of parallelism.&lt;br /&gt;
&lt;br /&gt;
==Executors==&lt;br /&gt;
&amp;lt;youtube&amp;gt;8qh9LMhvNXI&amp;lt;/youtube&amp;gt; &amp;lt;!-- box link: [https://wustl.box.com/s/2pqv6vsbirt6zi4304ycrh7jfgkb0dhi Executor submit and Future get]--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;tuAkLb99sLE&amp;lt;/youtube&amp;gt; &amp;lt;!-- box link: [https://wustl.box.com/s/17q7xupx1tagdnnfg057teme4lbq4w6r Executor invokeAll]--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Code To Use===&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html interface ExecutorService]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.util.concurrent.Callable- submit(task)]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#invokeAll-java.util.Collection- invokeAll(tasks)]&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html interface Future]&lt;br /&gt;
:[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-- get()]&lt;br /&gt;
&lt;br /&gt;
[http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/count/assignment/NucleobaseCounting.html NucleobaseCounting]&lt;br /&gt;
: [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/count/assignment/NucleobaseCounting.html#countRangeSequential-byte:A-edu.wustl.cse231s.bioinformatics.Nucleobase-int-int- countRangeSequential(chromosome,targetNucleobase,min,maxExclusive)]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html Slices]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html#createNSlices-byte:A-int- &amp;lt;nowiki&amp;gt;createNSlices(data, numSlices)&amp;lt;/nowiki&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
As always, the [[Syntax_of_231#Executors|wiki's syntax page]] can be of help.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
&lt;br /&gt;
===Mistake To Avoid: Do NOT call shutdown===&lt;br /&gt;
Each method you write will be passed an executor.  You need not (and should NOT) invoke [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown-- shutdown()].  That is the responsibility of whoever created the executor.  For example, a JUnit test would do this if it was appropriate (i.e. it created an executor and was not using the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#commonPool-- common pool]).&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===XNucleobaseCount===&lt;br /&gt;
This part of the assignment should be very familiar as it is to a large degree implementing the [[Nucleobase_Counting|Nucleobase Counting assignment]] with Executors instead of Habanero.  It also adds a divide and conquer implementation of nucleobase counting. &lt;br /&gt;
{{CodeToImplement|XNucleobaseCount|countLowerUpperSplit&amp;lt;br&amp;gt;countNWaySplit&amp;lt;br&amp;gt;countDivideAndConquer&amp;lt;br&amp;gt;countDivideAndConquerKernel|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
{{Tip|Use [http://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/count/assignment/NucleobaseCounting.html#countRangeSequential-byte:A-edu.wustl.cse231s.bioinformatics.Nucleobase-int-int- countRangeSequential()] from [[Nucleobase_Counting]]}}&lt;br /&gt;
====lower upper split====&lt;br /&gt;
{{Parallel|int countLowerUpperSplit(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase)}}&lt;br /&gt;
====n-way split====&lt;br /&gt;
{{Parallel|int countNWaySplit(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int numTasks)}}&lt;br /&gt;
&lt;br /&gt;
Please feel free to use your own [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html Slices] [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/slice/studio/Slices.html#createNSlices-byte:A-int- &amp;lt;nowiki&amp;gt;createNSlices(byte[] data, int numSlices)&amp;lt;/nowiki&amp;gt;].  Then use the [https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html Java for each loop] to iterate over the slices to create your tasks.&lt;br /&gt;
&lt;br /&gt;
====divide-and-conquer====&lt;br /&gt;
{{Parallel|int countDivideAndConquer(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int threshold)}}&lt;br /&gt;
&lt;br /&gt;
This method should just get things going by invoking the countDivideAndConquerKernel on the entire chromosome array.&lt;br /&gt;
&lt;br /&gt;
{{Parallel|int countDivideAndConquerKernel(ExecutorService executor, byte[] chromosome, Nucleobase nucleobase, int min, int maxExclusive, int threshold)}}&lt;br /&gt;
&lt;br /&gt;
NOTE: When you get down below the threshold and convert from parallel to sequential execution, do NOT feel compelled to build a sequential divide and conquer.  Just invoke countRangeSequential on the remaining range.  It is not like divide and conquer gives you a performance benefit in counting like it would for sorting.&lt;br /&gt;
&lt;br /&gt;
===XQuicksort===&lt;br /&gt;
{{CodeToImplement|XQuicksort|sequentialQuicksort&amp;lt;br&amp;gt;sequentialQuicksortKernel&amp;lt;br&amp;gt;parallelQuicksort&amp;lt;br&amp;gt;parallelQuicksortKernel|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
Quicksort is an oldie but a goodie.  First developed in 1959 and [https://dl.acm.org/citation.cfm?doid=366622.366644 published in 1961] it is still the go to sorting algorithm today.  The JDK8 implementation of [https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-int:A- Arrays.sort(array)] is a DualPivotQuicksort.&lt;br /&gt;
&lt;br /&gt;
Quicksort is also amenable to parallelism.  Once the partitioning is done, both sides of the pivot can be sorted completely independently in parallel.  This lends itself very nicely to the X10 family of languages as you can freely [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/edu/wustl/cse231s/rice/habanero/Habanero.html#async-edu.rice.hj.api.HjSuspendable- async] as you divide and conquer, then join all of the tasks by wrapping it all in a single call to [http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/apidocs/edu/wustl/cse231s/rice/habanero/Habanero.html#finish-edu.rice.hj.api.HjSuspendable- finish].  &lt;br /&gt;
&lt;br /&gt;
In this assignment you will mimic this behavior by submitting tasks to an executor, tracking the returned futures in in a ConcurrentLinkedQueue, then invoking get on all of those futures to mimic the single finish.&lt;br /&gt;
&lt;br /&gt;
{{Warning| [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkQueue]'s iterators are weakly consistent.  Do the [[#.28Optional_But_Recommended.29_Join_All_Warm_Up | Join All Warm Up]] to gain experience with handling this issue. }}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;jP2998MvX9o&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;iqnvIeIhGPw&amp;lt;/youtube&amp;gt; [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/be41f5f2b11a4445aa4be174e94f1717/16 RiceX Lecture on Quicksort]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;SLauY6PpjW4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning|Unlike in Sarkar's and McDowell’s videos which use inclusive maximums, CSE 231 consistently uses exclusive maximums to avoid having to subtract 1 all of the time.}}&lt;br /&gt;
&lt;br /&gt;
====The Core Questions====&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
====Code To Use====&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/Partitioner.html interface Partitioner]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/Partitioner.html#partitionRange-int:A-int-int- partitionRange(data,min,maxExclusive)]&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/PivotLocation.html class PivotLocation]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/PivotLocation.html#getLeftSidesUpperExclusive-- getLeftSidesUpperExclusive()]&lt;br /&gt;
:[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/sort/core/quick/PivotLocation.html#getRightSidesLowerInclusive-- getRightSidesLowerInclusive()]&lt;br /&gt;
&lt;br /&gt;
====sequential====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
The provided sequentialQuicksort method hopes to get you on the right track.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;public static void sequentialQuicksort(int[] array) {&lt;br /&gt;
	sequentialQuicksortKernel(array, 0, array.length);&lt;br /&gt;
}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Sequential|void sequentialQuicksort(int[] data, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|void sequentialQuicksortKernel(int[] data, int min, int maxExclusive, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
====parallel====&lt;br /&gt;
{{Parallel|void parallelQuicksort(ExecutorService executor, int[] data, int threshold, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
{{Tip | Make sure to use a thread safe data structure like [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html ConcurrentLinkedQueue] and NOT an unsafe data structure like [https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html LinkedList]. }}&lt;br /&gt;
&lt;br /&gt;
{{Tip | &amp;lt;code&amp;gt;return null;&amp;lt;/code&amp;gt; from your lambdas to invoke the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#submit-java.util.concurrent.Callable- overloaded Callable version of submit(task)] to deal with the checked exceptions. }}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|void parallelQuicksortKernel(ExecutorService executor, int[] data, int min, int maxExclusive, Queue&amp;lt;Future&amp;lt;?&amp;gt;&amp;gt; futures, int threshold, Partitioner partitioner)}}&lt;br /&gt;
&lt;br /&gt;
==(Optional) Parallel Partition Challenge==&lt;br /&gt;
The partitioning step can also be done in [http://www.classes.cec.wustl.edu/~cse341/web/handouts/lecture07.pdf parallel with scan].  While not particularly practical, it can get the CPL down to &amp;lt;math&amp;gt;\mathcal{O}(\lg^k{}n)&amp;lt;/math&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For details on how to complete this challenge, check out: [[Quicksort_Parallel_Partitioner]]&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
There is a top-level test suite comprised of sub test suites which can be invoked separately when you want to focus on one part of the assignment.&lt;br /&gt;
===top level===&lt;br /&gt;
{{TestSuite|ThreadsAndExecutorsTestSuite|tnx.lab}}&lt;br /&gt;
===sub===&lt;br /&gt;
{{TestSuite|ThreadsTestSuite|tnx.lab.thread}}&lt;br /&gt;
{{TestSuite|NucleobaseExecutorTestSuite|tnx.lab.executor}}&lt;br /&gt;
{{TestSuite|QuicksortExecutorTestSuite|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|NucleobaseCountTiming|tnx.lab.executor}}&lt;br /&gt;
{{Performance|QuicksortTiming|tnx.lab.executor}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
&lt;br /&gt;
SimpleThreadFactory subtotal: 5&lt;br /&gt;
* Correct newThread (5)&lt;br /&gt;
&lt;br /&gt;
TAgeSum subtotal: 10&lt;br /&gt;
* Correct sumUpperLowerSplit (10)&lt;br /&gt;
&lt;br /&gt;
XNucleobaseCount subtotal: 40&lt;br /&gt;
* Correct count2WaySplit (10)&lt;br /&gt;
* Correct countNWaySplit (15)&lt;br /&gt;
* Correct countDivideAndConquer and countDivideAndConquerKernel (15)&lt;br /&gt;
&lt;br /&gt;
XQuicksort subtotal: 35&lt;br /&gt;
* Correct sequentialQuicksort and sequentialQuicksortKernel (10)&lt;br /&gt;
* Correct parallelQuicksort and parallelQuicksortKernel (25)&lt;br /&gt;
&lt;br /&gt;
Whole project:&lt;br /&gt;
* Clarity and efficiency (10)&lt;br /&gt;
&lt;br /&gt;
=Pledge, Acknowledgments, Citations=&lt;br /&gt;
As always, fill out the Pledge, Acknowledgments, and Citations file: &amp;lt;code&amp;gt;lab3-pledge-acknowledgments-citations.txt&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Fibonacci&amp;diff=2181</id>
		<title>Fibonacci</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Fibonacci&amp;diff=2181"/>
		<updated>2018-07-23T06:33:00Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Parallel Docs */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
It is important to always reduce the work, then parallelize if possible.  In this studio you will build a beautiful, elegant solution to Fibonacci which can be easily parallelized yielding off-the-charts ideal parallelism.  Sadly, it performs terribly since the work is exponential.  It is far better to build a linear or log time algorithm whether or not it can be parallelized.&lt;br /&gt;
&lt;br /&gt;
We will gain experience with the future construct.&lt;br /&gt;
&lt;br /&gt;
We will convert recurrence relations into code.&lt;br /&gt;
&lt;br /&gt;
Additionally, (and of minor importance) we gain experience working with the [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger] class.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
The fibonacci sequence is a mathematical concept often used in computer science as a means to demonstrate iteration and recursion. Although you should be familiar with it from CSE 131, we will use the fibonacci sequence to demonstrate memoization and dynamic programming. Follow these links for a quick recap on [http://classes.engineering.wustl.edu/cse231/core/index.php/FAQ#Unit_2:_Futures.2FAccumulators.2FData_Races.2FMemoization memoization, dynamic programming], and the [https://en.wikipedia.org/wiki/Fibonacci_number fibonacci sequence].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;SjSHVDfXHQ4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://www.scientificamerican.com/video/the-mind-blowing-mathematics-of-sunflowers/ Scientific American Video]: [[File:Fibonacci spiral.jpg|400px]]&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
&amp;lt;youtube&amp;gt;PELL8QxKl4M&amp;lt;/youtube&amp;gt;&lt;br /&gt;
===Parallel Docs===&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#future-edu.wustl.cse231s.v5.api.CheckedCallable- future(body)] &lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html interface Future&amp;lt;V&amp;gt;].  &lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-- get()]&lt;br /&gt;
&lt;br /&gt;
Check out the [[Reference_Page#Future|wiki's reference page]] to see how Future's can be used!&lt;br /&gt;
&lt;br /&gt;
===BigInteger Docs===&lt;br /&gt;
fibonacci(47) is greater than [https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#MAX_VALUE Integer.MAX_VALUE] which would [https://en.wikipedia.org/wiki/Integer_overflow overflow] if we used the [https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html primitive int data type].  We use [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger] instead to prevent this problem.&lt;br /&gt;
&lt;br /&gt;
[https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html BigInteger]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#ZERO BigInteger.ZERO]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#ONE BigInteger.ONE]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add-java.math.BigInteger- bi.add(other)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#multiply-java.math.BigInteger- bi.multiply(other)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#valueOf-long- bi.valueOf(val)]&lt;br /&gt;
: [https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#shiftLeft-int- bi.shiftLeft(n)]&lt;br /&gt;
&lt;br /&gt;
=Studio (Required)=&lt;br /&gt;
==RecurrenceRelationSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(\Phi^n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|RecurrenceRelationSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
implement a recursive method for:&lt;br /&gt;
&lt;br /&gt;
===recurrence relation===&lt;br /&gt;
: &amp;lt;math&amp;gt;F_n = F_{n-1} + F_{n-2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===seed values===&lt;br /&gt;
: &amp;lt;math&amp;gt;F_0=0&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;F_1=1&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==RecurrenceRelationParallelFibonacciCalculator==&lt;br /&gt;
{{WorkCPLIdealParallelism|&amp;lt;math&amp;gt;O(\Phi^n)&amp;lt;/math&amp;gt;|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;|&amp;lt;math&amp;gt;\dfrac{\Phi^n}{n}&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|RecurrenceRelationParallelFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Parallel|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
Use futures to add parallelism to the recurrence relation solution.&lt;br /&gt;
&lt;br /&gt;
==MemoizationSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|MemoizationSequentialFibonacciCalculator|fibonacciMemo|fibonacci.studio}}&lt;br /&gt;
{{Sequential|private BigInteger fibonacciMemo(BigInteger[] memos, int n)}}&lt;br /&gt;
&lt;br /&gt;
Implement the recurrence relation algorithm but employ memoization for the win.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public BigInteger fibonacci(int n) {&lt;br /&gt;
		BigInteger[] memos = new BigInteger[n + 1];&lt;br /&gt;
		return fibonacciMemo(memos, n);&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT invoke fibonacci from fibonacciMemo.  Invoke fibonacciMemo from fibonacciMemo. }}&lt;br /&gt;
{{Warning | The entire point of memoization is to avoid recalculating the same computation.  Be sure to store the value for each calculation as it is made even if that means splitting up a line of code.}}&lt;br /&gt;
&lt;br /&gt;
==DynamicIterativeSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|DynamicIterativeSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
Imagine you are simply writing out Fibonacci numbers:&lt;br /&gt;
&lt;br /&gt;
: 0, 1, 1, 2, 3, 5, 8, 13...&lt;br /&gt;
&lt;br /&gt;
Convert that process of summing the two previous numbers over and over into code.&lt;br /&gt;
&lt;br /&gt;
==LinearRecurrenceSequentialFibonacciCalculator==&lt;br /&gt;
{{Work|&amp;lt;math&amp;gt;O(n)&amp;lt;/math&amp;gt;}} &lt;br /&gt;
&lt;br /&gt;
note: can be memoized to {{Work|&amp;lt;math&amp;gt;O(\log{}n)&amp;lt;/math&amp;gt;}}&lt;br /&gt;
{{CodeToImplement|LinearRecurrenceSequentialFibonacciCalculator|fibonacci|fibonacci.studio}}&lt;br /&gt;
{{Sequential|public BigInteger fibonacci(int n)}}&lt;br /&gt;
&lt;br /&gt;
{{Warning | Do NOT invoke &amp;lt;code&amp;gt;fibonacci(k)&amp;lt;/code&amp;gt; or  &amp;lt;code&amp;gt;fibonacci(k-1)&amp;lt;/code&amp;gt; multiple times if you can catch the result in a variable and reuse it. }}&lt;br /&gt;
{{Tip | There is no need to store k in a BigInteger.  Since it is smaller than n, it will fit just fine in an int. }}&lt;br /&gt;
{{Tip | You can shift left by 1 if you would prefer to not have to multiply by the big integer value of 2.}}&lt;br /&gt;
===recurrence relation===&lt;br /&gt;
&lt;br /&gt;
: if n is odd&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;k = \dfrac{n+1}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;F_n = (F_{k} \times F_{k}) + (F_{k-1} \times F_{k-1})&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:else&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;k = \dfrac{n}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:: &amp;lt;math&amp;gt;F_n = ((2 \times F_{k-1}) + F_{k}) \times F_{k}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===seed values===&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;F_0=0&amp;lt;/math&amp;gt;&lt;br /&gt;
: &amp;lt;math&amp;gt;F_1=1&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Fun (Optional)=&lt;br /&gt;
==RecurrenceRelationParallelWithThresholdFibonacciCalculator==&lt;br /&gt;
Similar to [[#RecurrenceRelationParallelFibonacciCalculator]] but with a threshold in place to prevent creating too many tasks for the number of processors.&lt;br /&gt;
&lt;br /&gt;
==MemoizationParallelFibonacciCalculator==&lt;br /&gt;
Create all of your futures [0..N] up front and then call get on memo[n].&lt;br /&gt;
==DynamicRecursiveSequentialFibonacciCalculator==&lt;br /&gt;
==RoundPhiToTheNOverSqrt5SequentialFibonacciCalculator==&lt;br /&gt;
&amp;lt;math&amp;gt;\dfrac{\Phi^n}{\sqrt{5}}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|FibonacciTestSuite|fibonacci.studio}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|FibonacciTiming|fibonacci.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Performance|FibonacciIterations|fibonacci.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Nucleobase_Counting&amp;diff=2180</id>
		<title>Nucleobase Counting</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Nucleobase_Counting&amp;diff=2180"/>
		<updated>2018-07-23T06:30:27Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Parallel Constructs */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
* get our feet wet with parallel programming&lt;br /&gt;
* gain experience with the async and finish constructs&lt;br /&gt;
* take different approaches to splitting up the work&lt;br /&gt;
&lt;br /&gt;
We will solve the problem sequentially, then split the work up into 2 tasks, then coarsen the work n-ways, and finally split up the work in a divide-and-conquer recursive style.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&lt;br /&gt;
==Bioinformatics==&lt;br /&gt;
For this assignment, you will be writing sequential and parallel code to count nucleobases in a human X chromosome.&lt;br /&gt;
 &lt;br /&gt;
DNA is made up of four nucleobases: cytosine, guanine, adenine, and thymine. A strand of DNA can thus be represented as a string of letters representing these nucleobases, for example: “ACCGCATAAAGTCC.” However, DNA sequencing is typically not 100% accurate, so some of the nucleobases are not read with high certainty. These bases can be represented as an “N.” A sequence then might look something like “NCCGCATNAAGTCC.” Your goal is to write code that counts the number of occurrences a particular nucleobase or uncertain reads.&lt;br /&gt;
&lt;br /&gt;
We will be using actual data pulled from the US National Library of Medicine, a database maintained by the National Institute of Health. We have already provided you the code that you need to access the chromosome from the database and check your work. You must implement a sequential solution and three parallel solutions to count the given bases in these sequences.&lt;br /&gt;
&lt;br /&gt;
For some more optional background on DNA and nucleotide bases, please check out&lt;br /&gt;
*https://en.wikipedia.org/wiki/DNA&lt;br /&gt;
*https://en.wikipedia.org/wiki/FASTA_format&lt;br /&gt;
&lt;br /&gt;
==Parallel Programming==&lt;br /&gt;
===Parallel Constructs===&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#finish-edu.wustl.cse231s.v5.api.CheckedRunnable- finish]&lt;br /&gt;
* [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async]&lt;br /&gt;
* Feel free to use the [[Reference_Page#Async|course reference page]] if you need a reminder on how to use asyncs and finishes&lt;br /&gt;
&lt;br /&gt;
===Related Videos===&lt;br /&gt;
&amp;lt;youtube&amp;gt;ShcnjoO89ZU&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;DjVep9485l4&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;1x-jGwcW4WU&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;0_JrsJrqgDg&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;8oq9CKgIOiE&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;--GfpYtL0lI&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
* [https://wustl.app.box.com/s/2w4c9xn5du3sqwmmji7v8w35ntpq1j7z Finish &amp;amp; Async: Lower Upper Split]&lt;br /&gt;
* [https://wustl.app.box.com/s/dx0f8ycz82e3r894rnpk0cjw8tj8jqzu Dealing With Final: Using Array Slots]&lt;br /&gt;
* [https://wustl.app.box.com/s/wix18u57v7x1rdx1d1dgfedf6ibr0n92 Dealing With Final: IntegerRange]&lt;br /&gt;
* [https://wustl.app.box.com/s/p3ooceekguiaygg4hggw76rbpt28kf6o CSE]&lt;br /&gt;
* [https://wustl.app.box.com/s/smckzu78cvg8seocgluuo1afydgd0gmt Finish &amp;amp; Async Coarsening: N-Way Split]&lt;br /&gt;
* [https://wustl.app.box.com/s/wqrauxpsz8xskt897qyukm6rkx9u4zmn Divide and Conquer: Array Sum Example]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=The Core Questions=&lt;br /&gt;
*What are the tasks?&lt;br /&gt;
*What is the data?&lt;br /&gt;
*Is the data mutable?&lt;br /&gt;
*If so, how is it shared?&lt;br /&gt;
&lt;br /&gt;
=Mistakes to Avoid=&lt;br /&gt;
{{Warning | Be sure to remove each NotYetImplementedException as you implement your solutions.}}&lt;br /&gt;
{{Warning | Do NOT copy the data.  We are simply reading the chromosome data, so there is no reason to copy it.}}&lt;br /&gt;
{{Warning | Do NOT share data beyond what is necessary.  Do NOT use static class fields when you could use local variables instead.}}&lt;br /&gt;
&lt;br /&gt;
=Getting Started=&lt;br /&gt;
*[[Initial_Setup]]&lt;br /&gt;
*[[Cloning_Repo]]&lt;br /&gt;
*[[JavaFX_Setup]]&lt;br /&gt;
&lt;br /&gt;
=Code to Implement=&lt;br /&gt;
==Midpoint==&lt;br /&gt;
{{CodeToImplement|MidpointUtils|caclulateMidpoint|midpoint.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static int calculateMidpoint(int a, int b)}}&lt;br /&gt;
&lt;br /&gt;
In this method, you will need to calculate the midpoint between two numbers. This is as simple as finding the average between the two numbers. There is no need to worry about rounding correctly, just drop everything after the decimal point if the midpoint is not automatically an int.&lt;br /&gt;
&lt;br /&gt;
There are at least two correct ways to implement the midpoint:  &lt;br /&gt;
&lt;br /&gt;
: Option A: &amp;lt;math&amp;gt;\frac{min+max}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
: Option B: &amp;lt;math&amp;gt;min+\frac{max-min}{2}&amp;lt;/math&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is hard to find 1D references for midpoint.  [http://mathworld.wolfram.com/ Wolfram MathWorld] has a breakdown of [http://mathworld.wolfram.com/Midpoint.html Midpoint in 2D and 3D].  Pick any dimension you like.&lt;br /&gt;
&lt;br /&gt;
==Threshold==&lt;br /&gt;
{{CodeToImplement|GreaterThanThresholdPredicate|constructor&amp;lt;br&amp;gt;test|midpoint.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public GreaterThanThresholdPredicate(int threshold)}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public boolean test(int value)}}&lt;br /&gt;
&lt;br /&gt;
==Count Range==&lt;br /&gt;
{{CodeToImplement|NucleobaseCounting|countRange&amp;lt;br&amp;gt;countSequential&amp;lt;br&amp;gt;countParallelLowerUpperSplit&amp;lt;br&amp;gt;countParallelNWaySplit&amp;lt;br&amp;gt;countParallelDivideAndConquerKernel|count.lab}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static int countRangeSequential(byte[] chromosome, Nucleobase targetNucleobase, int min, int maxExclusive)}}&lt;br /&gt;
&lt;br /&gt;
This utility method should count the number of times a particular nucleobase occurs in the array between [min, maxExclusive).&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Use a for loop to iterate from min to maxExclusive.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Sequential Solution==&lt;br /&gt;
&lt;br /&gt;
{{Sequential|public static int countSequential(byte[] chromosome, Nucleobase targetNucleobase)}}&lt;br /&gt;
&lt;br /&gt;
This solution should be achieved with a simple call to one of the utility methods you wrote.&lt;br /&gt;
&amp;lt;spoiler show=&amp;quot;spoiler&amp;quot; hide=&amp;quot;spoiler&amp;quot;&amp;gt;Invoke countRangeSequential from 0 to the chromosome array length.&amp;lt;/spoiler&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Parallel Solutions==&lt;br /&gt;
&lt;br /&gt;
You need to implement three different parallel solutions to this problem. The first will involve splitting the array into two equal halves, then going through each half of the array in parallel. The second will involve splitting the array into n different pieces, then going through each of those pieces of the array in parallel.  The third and final implementation will recursively divide the array until a threshold is reached.&lt;br /&gt;
 &lt;br /&gt;
===Lower/Upper Split===&lt;br /&gt;
{{Parallel|public static int countParallelLowerUpperSplit(byte[] chromosome, Nucleobase targetNucleobase)}}&lt;br /&gt;
&lt;br /&gt;
In order to start with then two equal halves solution, please modify the &amp;lt;code&amp;gt;countParallelUpperLowerSplit&amp;lt;/code&amp;gt; method.&lt;br /&gt;
&lt;br /&gt;
===Coarsening N-Way Split===&lt;br /&gt;
{{Parallel|public static int countParallelNWaySplit(byte[] chromosome, Nucleobase targetNucleobase, int numTasks)}}&lt;br /&gt;
&lt;br /&gt;
After you’re finished with that, please modify the &amp;lt;code&amp;gt;countParallelNWaySplit&amp;lt;/code&amp;gt; method for splitting the work up into n tasks solution.&lt;br /&gt;
&lt;br /&gt;
If the chromosome was 1,000,000 long, and you were asked to split it up in 10 tasks, each task should obviously process 100,000.  Things get slightly tricky if the chromosome were 1,000,005 long.&lt;br /&gt;
&lt;br /&gt;
===Divide and Conquer===&lt;br /&gt;
In a pattern that we will use repeatedly in the course, we have a public method that is asked to count an entire chromosome.  This method just calls the kernel method to do all of the work:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	public static int countParallelDivideAndConquer(byte[] chromosome, Nucleobase targetNucleobase, IntPredicate isParallelRangeLengthPredicate)&lt;br /&gt;
			throws InterruptedException, ExecutionException {&lt;br /&gt;
		return countParallelDivideAndConquerKernel(chromosome, targetNucleobase, isParallelRangeLengthPredicate, 0, chromosome.length);&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Parallel|static int countParallelDivideAndConquerKernel(byte[] chromosome, Nucleobase targetNucleobase, IntPredicate isParallelRangeLengthPredicate,&lt;br /&gt;
			int min, int maxExclusive)}}&lt;br /&gt;
&lt;br /&gt;
The kernel method will recursively divide the work up in parallel until the range drops below the threshold specified by isParallelRangeLengthPredicate.  At that point it will simply use the sequential count range utility method.&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|CountTestSuite|count.lab}}&lt;br /&gt;
&lt;br /&gt;
Launch CountTestSuite.java as a JUnit Test to run all of the tests.  CountTestSuite.java is located in src/test/java count.lab package.  You can initiate this via right clicking on CountTestSuite.java and selecting &amp;quot;Run As...&amp;quot; -&amp;gt; &amp;quot;JUnit Test&amp;quot;.&lt;br /&gt;
[[http://www.cse.wustl.edu/~cosgroved/courses/cse231/f17/hw1/run-junit-test-suite.png screenshot]]&lt;br /&gt;
&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|NucleobaseCountTiming|count.lab}}&lt;br /&gt;
After your JUnit tests are passing and you are confident that your solutions are correct, move on to checking out the timing performance of your different solutions with different task counts.&lt;br /&gt;
&lt;br /&gt;
=Rubric=&lt;br /&gt;
&lt;br /&gt;
As always, please make sure to cite your work appropriately.&lt;br /&gt;
&lt;br /&gt;
Total points: 100&lt;br /&gt;
* Correct countRangeSequential (10)&lt;br /&gt;
* Correct countSequential (5)&lt;br /&gt;
* Correct calculateMidpoint (5)&lt;br /&gt;
* Correct countParallelLowerUpperSplit (10)&lt;br /&gt;
* Parallel countParallelLowerUpperSplit (10)&lt;br /&gt;
* Correct countParallelNWaySplit (15)&lt;br /&gt;
* Parallel countParallelNWaySplit (10)&lt;br /&gt;
* Correct GreaterThanThresholdPredicate (5)&lt;br /&gt;
* Correct countParallelDivideAndConquerKernel (10)&lt;br /&gt;
* Parallel countParallelDivideAndConquerKernel (10)&lt;br /&gt;
* Clarity and efficiency (10)&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=FAQ&amp;diff=2179</id>
		<title>FAQ</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=FAQ&amp;diff=2179"/>
		<updated>2018-07-23T06:27:33Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Unit 1: Async/Finish */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;We have gathered the most frequently asked questions on Piazza and the Q&amp;amp;S forms on this wiki for your convenience.&lt;br /&gt;
&lt;br /&gt;
=General=&lt;br /&gt;
==Parallel vs. Concurrent==&lt;br /&gt;
What is the difference between Parallel and Concurrent computing?&lt;br /&gt;
&lt;br /&gt;
:''Parallel programming is about using additional computational resources to produce an answer faster.''&lt;br /&gt;
:''Concurrent programming is about correctly and efficiently controlling access by multiple threads to shared resources.''&lt;br /&gt;
&lt;br /&gt;
::---[https://homes.cs.washington.edu/~djg/ Prof. Grossman]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/presentation/d/1GMJIxTNbOK39VuJRpI-iIRQcbvVsBbuNvwHcy42d8n4/pub?start=false&amp;amp;loop=false&amp;amp;delayms=3000&amp;amp;slide=id.g247370a3ae_1_670 slide]&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
{{Quote|text=Parallel programming is about using additional computational resources to produce an answer faster. Concurrent programming is about correctly and efficiently controlling access by multiple threads to shared resources. |author=Dan Grossman }}&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
:''Concurrency is about dealing with a lot of things at once and parallelism is about doing a lot of things at once.''&lt;br /&gt;
::---Rob Pike - 'Concurrency Is Not Parallelism'&lt;br /&gt;
&lt;br /&gt;
&amp;lt;youtube&amp;gt;cN_DpYBzKso&amp;lt;/youtube&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Dealing with Errors=&lt;br /&gt;
==Fixing Maven when you encounter java.lang.NoClassDefFoundError and/or java.lang.ClassNotFoundError==&lt;br /&gt;
===On Mac===&lt;br /&gt;
# Close Eclipse&lt;br /&gt;
# Launch Terminal&lt;br /&gt;
# mv ~/.m2/repository ~/.m2/dead&lt;br /&gt;
# Open Eclipse&lt;br /&gt;
# Type Alt+F5 (note may need to press function (fn) key to trigger F5)&lt;br /&gt;
# Project Menu -&amp;gt; Clean...&lt;br /&gt;
===On Windows===&lt;br /&gt;
# Close Eclipse&lt;br /&gt;
# Launch Command Prompt&lt;br /&gt;
# cd .m2&lt;br /&gt;
# rename repository dead&lt;br /&gt;
# Open Eclipse&lt;br /&gt;
# Type Alt+F5 (note may need to press function key to trigger F5)&lt;br /&gt;
# Project Menu -&amp;gt; Clean...&lt;br /&gt;
&lt;br /&gt;
=Unit 1: Async/Finish=&lt;br /&gt;
&lt;br /&gt;
*For the demo, he uses a threshold to determine whether or not to use the parallel version. How does he decide that threshold? Is it machine dependent? Or algorithm dependent?&lt;br /&gt;
**The threshold is often specified as an input parameter in a parallel method. The user often sets the value depending on the algorithm based on the overhead of starting a parallel process.&lt;br /&gt;
*Is async and finish features of the Java language or specific to this class?&lt;br /&gt;
**Async and finish are features of Habanero Java, a tool built by Rice University. We have re-purposed it for our own needs in what we call V5. Neither are native to Java but we will use it in this class for its simplicity. Later in the semester we cover some parallel/concurrent tools that are native to Java.&lt;br /&gt;
*When doing Quicksort, why is it more efficient to place the finish inside the main method?&lt;br /&gt;
**When performing recursive methods in parallel, it is most efficient to place the finish around the initial call as you want the subsequent inner calls to run asynchronously. Thus, you should wrap the async around the inner recursive call and the finish around the initial outer call.&lt;br /&gt;
*Are we assuming that the core of the CPU is infinite?&lt;br /&gt;
**When dealing with theory, we will assume it is infinite unless otherwise specified. When coding, we will take hybrid approaches where we will sometimes assume it is infinite and sometimes code realistically to adjust for the finite number of cores.&lt;br /&gt;
*In the videos and quizzes, we assumed finish and asyncs added no work to the computation graph. In reality, is there some amount of work needed for them?&lt;br /&gt;
**Yes, that work is what we are referring to when we talk about overhead. In order to account for this, you should only run a program in parallel if the amount of work overshadows the overhead costs.&lt;br /&gt;
*How does concurrency affect timing with a single core?&lt;br /&gt;
**With a single core, it becomes impossible to launch programs in parallel, but concurrent programming is still possible. Under such a scenario, whatever you async'd will still execute as separate threads, but it will simply run on the single core. Thus, the order in which the threads execute is still not guaranteed, meaning it will not run like sequential code. For a more detailed explanation, refer to [https://stackoverflow.com/questions/1897993/what-is-the-difference-between-concurrent-programming-and-parallel-programming this] article.&lt;br /&gt;
&lt;br /&gt;
=Unit 2: Futures/Accumulators/Data Races/Memoization=&lt;br /&gt;
&lt;br /&gt;
*Why is it recommended to use immutable objects as far as possible in order to avoid data races?&lt;br /&gt;
**By the very definition of a data race, immutable objects avoid data races as they prevent threads from writing to them. Refer to the [http://classes.engineering.wustl.edu/cse231/core/index.php/Rundown_on_Everything_Java#Data_Races wiki post] on data races to get a better understanding of the definition of a data race.&lt;br /&gt;
*How are you able to tell when there is a data race in your code?&lt;br /&gt;
**A good rule of thumb is to look for shared mutable data in your code. Whenever you write to data in an async block, make sure that data you write to is adequately protected.&lt;br /&gt;
*Can we use the presence of functional and structural determinism to prove that a program is data race free? I understand that being DRF implies functional and structural determinism, but is the reverse also true?&lt;br /&gt;
**The reverse is not true and DRF actually does not guarantee determinism. This is a complicated topic, but the constructs introduced in Unit 5 will break the &amp;quot;DRF implies determinism&amp;quot; guarantee.&lt;br /&gt;
*Can a program have functional determinism but not structural determinism and vice versa?&lt;br /&gt;
**Yes and a program can also have neither.&lt;br /&gt;
*If a program lacks structural determinism but has functional determinism, is that &amp;quot;bad&amp;quot;? Should you always try to give it structural determinism?&lt;br /&gt;
**Not necessarily, sometimes it does not matter. [[Floodfill]] is a good example of this.&lt;br /&gt;
*When is async and finish better than futures?&lt;br /&gt;
**There are several cases when async/finish would be more appropriate than futures, but generally, anything that would not involve returning a value.&lt;br /&gt;
*What's the difference between memoization and dynamic programming?&lt;br /&gt;
**Memoization is the process of storing the value of an expensive calculation in order to avoid doing the calculation again. Dynamic programming, on the other hand, is the process of breaking up a large problem into smaller, more manageable subproblems (this can, but does not have to, include memoization).&lt;br /&gt;
*Are there ever situations where it would be better to run a function twice rather than utilizing memoization?&lt;br /&gt;
**The purpose of memoization is to balance performance and storage. If the calculation is not taxing but produces a variable that will eat up a lot of storage, it might be better not to store the value if it is only an intermediary variable.&lt;br /&gt;
&lt;br /&gt;
=Unit 3: Forall/Barriers=&lt;br /&gt;
&lt;br /&gt;
*How can you determine if forall is better or finish-async, or are they functionally the same?&lt;br /&gt;
**A forall loop is functionally the same as putting a regular for loop in between a finish and an async. It is up to you which you want to use, but the forall loop serves the purpose of making your code more readable.&lt;br /&gt;
*Can barriers be used in regular asyncs, or do they have to be parallel loops (like forall)?&lt;br /&gt;
**Barriers can be used wherever you put them, but are especially useful for parallel loops.&lt;br /&gt;
*Is a barrier simply analogous to a finish-block within a forall loop?&lt;br /&gt;
**No, it would be more accurate to think of a barrier as a type of phaser with an implicit wait command.&lt;br /&gt;
&lt;br /&gt;
=Unit 4: Phasers/Deadlock=&lt;br /&gt;
&lt;br /&gt;
*How would you recreate fuzzy barriers with asyncs and finishes?&lt;br /&gt;
**You cannot, fuzzy barriers create previously impossible computation graphs.&lt;br /&gt;
*Is it possible for two phasers to be dependent on each other, thereby breaking the program?&lt;br /&gt;
**Yes, this is called a deadlock.&lt;br /&gt;
*What kind of error will be thrown if we enter deadlock? Or would the program never terminate?&lt;br /&gt;
**Unless you explicitly define an error that would appear after a set amount of time, the program would just never terminate.&lt;br /&gt;
*Why use await instead of normal futures?&lt;br /&gt;
**Either one works, but you would need to use await if you wanted to execute task B after A without using the value generated from A or if A does not return a value (futures return values).&lt;br /&gt;
&lt;br /&gt;
=Unit 5: Isolated/Synchronized/Locks/Atomics=&lt;br /&gt;
&lt;br /&gt;
*What are locks and semaphores?&lt;br /&gt;
**Locks prevent a protected piece of code from running in parallel, forcing threads to access data one after the other. Each class has its own intrinsic lock and locks can also be set explicitly. Semaphores restrict threads from accessing a protected piece of data, but unlike locks, [https://stackoverflow.com/questions/34519/what-is-a-semaphore semaphores can allow more than one consumer access to a specific piece of data.]&lt;br /&gt;
*What is the difference between isolated and synchronized?&lt;br /&gt;
**They serve the same functional purpose, but isolated has the added perk of being able to specify read/write access with object-based isolation. You can use whichever you prefer.&lt;br /&gt;
*Does isolation naturally take up more resources? That is to say, in cases where data race is not a problem, would there be no reason to use isolation?&lt;br /&gt;
**Isolated is only used to protect shared mutable data, so it would be useless to call it when a program is already DRF.&lt;br /&gt;
*Are there such things as atomic strings or even data structures?&lt;br /&gt;
**Yes, there are several protected data structures built into Java. Check out [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html java.util.concurrent] for some more examples!&lt;br /&gt;
*Are atomic variables just a shorthand for object-based isolated constructs?&lt;br /&gt;
**You can think of them that way, but many of them are specifically optimized so that they often surpass simple object-based isolation in performance.&lt;br /&gt;
*Can we go over the difference between Atomic Integers and finish accumulators?&lt;br /&gt;
**You can choose to use them the exact same way if you would like, but atomic integers are slightly more versatile as they have more options for operations.&lt;br /&gt;
*How do we quantitatively define low, medium, and high contention?&lt;br /&gt;
**This is something you will just have to feel out. If you are only accessing one piece of shared mutable data, that might be low contention. If, however, you are reading and writing to multiple variables in parallel to the point that the parallel implementation performs worse than a sequential approach, this would be high contention. You will become better at judging this as the semester goes on.&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2178</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2178"/>
		<updated>2018-07-23T06:06:09Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. This section should hopefully help you figure out how to use the Java concepts needed to complete the assignments in the class.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out [[Rundown on Everything Java]].&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Check out the dedicated [[Generics]] page for a deep dive on how Java's generic types work!&lt;br /&gt;
&lt;br /&gt;
===Interfaces===&lt;br /&gt;
Check out the dedicated [[Interfaces]] page for an in-depth discussion on interfaces in Java!&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Basic Util Data Structures=&lt;br /&gt;
&lt;br /&gt;
Java's Data Structures are a core part of this class, as we will be constantly working with data and making our own data. In no time at all will you become very familiar with some of the more useful data structures!&lt;br /&gt;
&lt;br /&gt;
Remember that mainly syntax is shown here, with [[Rundown on Everything Java]] being the best place to go for more detailed information on certain topics.&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Looping through entries is also very easy to do!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = mapFilledWithEntries();&lt;br /&gt;
for(Entry&amp;lt;K,V&amp;gt; entry: map.entrySet()){&lt;br /&gt;
	K entryKey = entry.getKey();&lt;br /&gt;
	V entryValue = entry.getValue();&lt;br /&gt;
	doSomething(entryKey, entryValue);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are a fundamental building block of task level parallelism. The execution of an async will spawn a new child task, and any code written within the braces of an async will be done in that new task parallel to the parent task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, both &amp;lt;code&amp;gt;doSomething()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse()&amp;lt;/code&amp;gt; are being done at the same time as one another.&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with V5, we can use asyncs ''without'' having a new task spawn. This can be really helpful when building and debugging your programs, as it will give you quick and simple means to switch back and forth between parallel and sequential. To do this, use the following version of the method: &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;. In the following example, switching the first line can switch whether or not the two things are run in parallel or not!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;boolean isParallelDesired = true;&lt;br /&gt;
async(isParallelDesired, () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
doMoreSomethingElses();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example, &amp;lt;code&amp;gt;doSomething();&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse();&amp;lt;/code&amp;gt; will run in parallel with each other, but &amp;lt;code&amp;gt;doMoreSomethingElses();&amp;lt;/code&amp;gt; will not begin until the first two things have fully completed. &lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
{{Warning| CSE 231s is all exclusive max, all the time.  forall, forasync, and forseq are all exclusive max.}}&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
Similar to general asyncs, by doing &amp;lt;code&amp;gt;forall(boolean isParallelDesired, int minInclusive, int maxExclusive, Consumer body)&amp;lt;/code&amp;gt;, we can control whether the code runs in parallel or sequentially. Use this to make debugging a lot simpler!&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also do &amp;lt;code&amp;gt;chunked(100)&amp;lt;/code&amp;gt; to specify the size each chunk should be.&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential. &lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential.&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential, and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
'''With the recent introduction of the &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; option, Forseq has become a less useful tool since its purpose can be achieved elsewhere.'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel task that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As shown, &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt; returns something of type [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html Future&amp;lt;R&amp;gt;], which is a Java X10 construct.&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Util Concurrent=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers.&lt;br /&gt;
&lt;br /&gt;
Once again, you can find more in-depth explanations of how some of these tools work by checking out these pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2177</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2177"/>
		<updated>2018-07-23T06:01:41Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Entries */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. This section should hopefully help you figure out how to use the Java concepts needed to complete the assignments in the class.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out [[Rundown on Everything Java]].&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Check out the dedicated [[Generics]] page for a deep dive on how Java's generic types work!&lt;br /&gt;
&lt;br /&gt;
===Interfaces===&lt;br /&gt;
Check out the dedicated [[Interfaces]] page for an in-depth discussion on interfaces in Java!&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Basic Util Data Structures=&lt;br /&gt;
&lt;br /&gt;
Java's Data Structures are a core part of this class, as we will be constantly working with data and making our own data. In no time at all will you become very familiar with some of the more useful data structures!&lt;br /&gt;
&lt;br /&gt;
Remember that mainly syntax is shown here, with [[Rundown on Everything Java]] being the best place to go for more detailed information on certain topics.&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Looping through entries is also very easy to do!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;Entries&amp;gt; list = listFilledWithEntries();&lt;br /&gt;
for(Entry entry: list){&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are a fundamental building block of task level parallelism. The execution of an async will spawn a new child task, and any code written within the braces of an async will be done in that new task parallel to the parent task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, both &amp;lt;code&amp;gt;doSomething()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse()&amp;lt;/code&amp;gt; are being done at the same time as one another.&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with V5, we can use asyncs ''without'' having a new task spawn. This can be really helpful when building and debugging your programs, as it will give you quick and simple means to switch back and forth between parallel and sequential. To do this, use the following version of the method: &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;. In the following example, switching the first line can switch whether or not the two things are run in parallel or not!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;boolean isParallelDesired = true;&lt;br /&gt;
async(isParallelDesired, () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
doMoreSomethingElses();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example, &amp;lt;code&amp;gt;doSomething();&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse();&amp;lt;/code&amp;gt; will run in parallel with each other, but &amp;lt;code&amp;gt;doMoreSomethingElses();&amp;lt;/code&amp;gt; will not begin until the first two things have fully completed. &lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
{{Warning| CSE 231s is all exclusive max, all the time.  forall, forasync, and forseq are all exclusive max.}}&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
Similar to general asyncs, by doing &amp;lt;code&amp;gt;forall(boolean isParallelDesired, int minInclusive, int maxExclusive, Consumer body)&amp;lt;/code&amp;gt;, we can control whether the code runs in parallel or sequentially. Use this to make debugging a lot simpler!&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also do &amp;lt;code&amp;gt;chunked(100)&amp;lt;/code&amp;gt; to specify the size each chunk should be.&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential. &lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential.&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential, and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
'''With the recent introduction of the &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; option, Forseq has become a less useful tool since its purpose can be achieved elsewhere.'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel task that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As shown, &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt; returns something of type [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html Future&amp;lt;R&amp;gt;], which is a Java X10 construct.&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Util Concurrent=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers.&lt;br /&gt;
&lt;br /&gt;
Once again, you can find more in-depth explanations of how some of these tools work by checking out these pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2176</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2176"/>
		<updated>2018-07-23T05:53:07Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. This section should hopefully help you figure out how to use the Java concepts needed to complete the assignments in the class.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out [[Rundown on Everything Java]].&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Check out the dedicated [[Generics]] page for a deep dive on how Java's generic types work!&lt;br /&gt;
&lt;br /&gt;
===Interfaces===&lt;br /&gt;
Check out the dedicated [[Interfaces]] page for an in-depth discussion on interfaces in Java!&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Basic Util Data Structures=&lt;br /&gt;
&lt;br /&gt;
Java's Data Structures are a core part of this class, as we will be constantly working with data and making our own data. In no time at all will you become very familiar with some of the more useful data structures!&lt;br /&gt;
&lt;br /&gt;
Remember that mainly syntax is shown here, with [[Rundown on Everything Java]] being the best place to go for more detailed information on certain topics.&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are a fundamental building block of task level parallelism. The execution of an async will spawn a new child task, and any code written within the braces of an async will be done in that new task parallel to the parent task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, both &amp;lt;code&amp;gt;doSomething()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse()&amp;lt;/code&amp;gt; are being done at the same time as one another.&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with V5, we can use asyncs ''without'' having a new task spawn. This can be really helpful when building and debugging your programs, as it will give you quick and simple means to switch back and forth between parallel and sequential. To do this, use the following version of the method: &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;. In the following example, switching the first line can switch whether or not the two things are run in parallel or not!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;boolean isParallelDesired = true;&lt;br /&gt;
async(isParallelDesired, () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
doMoreSomethingElses();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example, &amp;lt;code&amp;gt;doSomething();&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse();&amp;lt;/code&amp;gt; will run in parallel with each other, but &amp;lt;code&amp;gt;doMoreSomethingElses();&amp;lt;/code&amp;gt; will not begin until the first two things have fully completed. &lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
{{Warning| CSE 231s is all exclusive max, all the time.  forall, forasync, and forseq are all exclusive max.}}&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
Similar to general asyncs, by doing &amp;lt;code&amp;gt;forall(boolean isParallelDesired, int minInclusive, int maxExclusive, Consumer body)&amp;lt;/code&amp;gt;, we can control whether the code runs in parallel or sequentially. Use this to make debugging a lot simpler!&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also do &amp;lt;code&amp;gt;chunked(100)&amp;lt;/code&amp;gt; to specify the size each chunk should be.&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential. &lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential.&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential, and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
'''With the recent introduction of the &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; option, Forseq has become a less useful tool since its purpose can be achieved elsewhere.'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel task that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As shown, &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt; returns something of type [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html Future&amp;lt;R&amp;gt;], which is a Java X10 construct.&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Util Concurrent=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers.&lt;br /&gt;
&lt;br /&gt;
Once again, you can find more in-depth explanations of how some of these tools work by checking out these pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2175</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2175"/>
		<updated>2018-07-23T05:27:27Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* V5/Habanero */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. Here's the syntax for some of Java's base constructs and classes that you'll use throughout the semester.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out some of the following pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are a fundamental building block of task level parallelism. The execution of an async will spawn a new child task, and any code written within the braces of an async will be done in that new task parallel to the parent task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, both &amp;lt;code&amp;gt;doSomething()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse()&amp;lt;/code&amp;gt; are being done at the same time as one another.&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with V5, we can use asyncs ''without'' having a new task spawn. This can be really helpful when building and debugging your programs, as it will give you quick and simple means to switch back and forth between parallel and sequential. To do this, use the following version of the method: &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;. In the following example, switching the first line can switch whether or not the two things are run in parallel or not!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;boolean isParallelDesired = true;&lt;br /&gt;
async(isParallelDesired, () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&lt;br /&gt;
doMoreSomethingElses();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example, &amp;lt;code&amp;gt;doSomething();&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse();&amp;lt;/code&amp;gt; will run in parallel with each other, but &amp;lt;code&amp;gt;doMoreSomethingElses();&amp;lt;/code&amp;gt; will not begin until the first two things have fully completed. &lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
{{Warning| CSE 231s is all exclusive max, all the time.  forall, forasync, and forseq are all exclusive max.}}&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
Similar to general asyncs, by doing &amp;lt;code&amp;gt;forall(boolean isParallelDesired, int minInclusive, int maxExclusive, Consumer body)&amp;lt;/code&amp;gt;, we can control whether the code runs in parallel or sequentially. Use this to make debugging a lot simpler!&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also do &amp;lt;code&amp;gt;chunked(100)&amp;lt;/code&amp;gt; to specify the size each chunk should be.&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential. &lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential.&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), passing through &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; as the first parameter can cause the loop to run in parallel or sequential, and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
'''With the recent introduction of the &amp;lt;code&amp;gt;boolean isParallelDesired&amp;lt;/code&amp;gt; option, Forseq has become a less useful tool since its purpose can be achieved elsewhere.'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel task that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As shown, &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt; returns something of type [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html Future&amp;lt;R&amp;gt;], which is a Java X10 construct.&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Util Concurrent=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers.&lt;br /&gt;
&lt;br /&gt;
Once again, you can find more in-depth explanations of how some of these tools work by checking out these pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Others=&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2174</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2174"/>
		<updated>2018-07-23T04:54:40Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* V5/Habanero */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. Here's the syntax for some of Java's base constructs and classes that you'll use throughout the semester.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out some of the following pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are a fundamental building block of task level parallelism. The execution of an async will spawn a new child task, and any code written within the braces of an async will be done in that new task parallel to the parent task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, both &amp;lt;code&amp;gt;doSomething()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;doSomethingElse()&amp;lt;/code&amp;gt; are being done at the same time as one another.&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with V5, we can use asyncs ''without'' having a new task spawn. This can be really helpful when building and debugging your programs, as it will give you quick and simple means to switch back and forth between parallel and sequential. To do this, use the following version of the method: &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;. In the following example, switching the first line can switch whether or not the two things are run in parallel or not!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Boolean isParallelDesired = true;&lt;br /&gt;
async(isParallelDesired, () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&lt;br /&gt;
doSomethingElse();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel tool that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Java Util Concurrent=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers.&lt;br /&gt;
&lt;br /&gt;
Once again, you can find more in-depth explanations of how some of these tools work by checking out these pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Others=&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2173</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2173"/>
		<updated>2018-07-23T04:41:50Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. Here's the syntax for some of Java's base constructs and classes that you'll use throughout the semester.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out some of the following pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are our main tool in doing work in parallel. The execution of an async will spawn a new task, and any code written within the braces of an async will be done in that new task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with the V5 version of async, we can call it as &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;, where the boolean determines whether or not the body is run in a new thread or not. While you'll never need to use this for the assignments, it is a possibility.&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel tool that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Java Util Concurrent=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers.&lt;br /&gt;
&lt;br /&gt;
Once again, you can find more in-depth explanations of how some of these tools work by checking out these pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Others=&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2171</id>
		<title>Reference Page</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Reference_Page&amp;diff=2171"/>
		<updated>2018-07-23T04:38:01Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: Miles.p.cushing moved page Syntax of 231 to Reference Page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is a collection of all the the different tools we use in this course and their syntax.&lt;br /&gt;
&lt;br /&gt;
While this page is here to assist you whenever you forget how to create a lambda or register a phaser, try not to become too reliant on it. If you learn and understand the syntax for the tools we build in this class, it will make the assignments easier and faster to get through. Also, this page will not be available during exams, and while there is always leniency with written code, there must be some demonstration of understanding how to use our parallel constructs!&lt;br /&gt;
&lt;br /&gt;
=Java Basics=&lt;br /&gt;
&lt;br /&gt;
Sometimes the problem isn't with doing things in parallel, but just getting Java to cooperate with what you want it to do. Here's the syntax for some of Java's base constructs and classes that you'll use throughout the semester.&lt;br /&gt;
&lt;br /&gt;
This page mainly just covers syntax though. For a better understanding of how some of these tools actually function and why we use them, check out some of the following pages:&lt;br /&gt;
*[[Rundown on Everything Java]]&lt;br /&gt;
*[[Generics]]&lt;br /&gt;
*[[Interfaces]]&lt;br /&gt;
&lt;br /&gt;
===Object Constructors===&lt;br /&gt;
There will be a lot of classes for students to make/complete throughout the semester. Many times, you will be responsible for filling out the constructor. If given something like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;private int value;&lt;br /&gt;
&lt;br /&gt;
public Foo(int parameter){&lt;br /&gt;
	//TO DO&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While all sorts of code and commands may be used in the constructor, before it is over, all of the class's private variables should have been assigned.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public Foo(int parameter){&lt;br /&gt;
	this.value = parameter;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, outside of this class, you can create an object of type Foo by doing the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Foo userMadeObject = new Foo(1);&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lists===&lt;br /&gt;
Many times you will need to make some kind of list to keep information in. The two we recommend using are Linked Lists and Array Lists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; listA = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
List&amp;lt;T&amp;gt; listB = new ArrayList&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====List Iterator====&lt;br /&gt;
All lists (and many other objects) have iterators we can use to easily traverse through the list.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; list;&lt;br /&gt;
ListIterator&amp;lt;T&amp;gt; iterator = list.listIterator();&lt;br /&gt;
while(iterator.hasNext){&lt;br /&gt;
	T itemA = iterator.next();&lt;br /&gt;
	doSomething(itemA);&lt;br /&gt;
}&lt;br /&gt;
while(iterator.hasPrevious){&lt;br /&gt;
	T itemB = iterator.previous();&lt;br /&gt;
	doSomething(itemB);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Maps===&lt;br /&gt;
Many times you will need to make some kind of map to store information in. Depending on the race conditions of the assignment, you usually will use Hash Maps or Concurrent Hash Maps.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Map&amp;lt;K,V&amp;gt; map = new HashMap&amp;lt;&amp;gt;();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Compute====&lt;br /&gt;
A very important application of a map is its compute method. This allows us to ''change'' a value in a map rather than having to remove it and add it back. Here is the code for the default implementation of the compute method, taken from the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#compute-K-java.util.function.BiFunction- Map JavaDocs]. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;V oldValue = map.get(key);&lt;br /&gt;
V newValue = remappingFunction.apply(key, oldValue);&lt;br /&gt;
if (oldValue != null ) {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		map.remove(key);&lt;br /&gt;
} else {&lt;br /&gt;
	if (newValue != null)&lt;br /&gt;
		map.put(key, newValue);&lt;br /&gt;
	else&lt;br /&gt;
		return null;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Most students tend to get tripped up on the use of a BiFunction. This BiFunction is essential giving the map a formula to use in order to get the new value it needs to set in the map. If we wanted to call compute on a key and increase its value by one (assuming the value is an integer), it would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;map.compute(keyName, (key, value) -&amp;gt; {&lt;br /&gt;
	return value + 1;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that the BiFunction is simply given as a lambda with two parameters passed in. Also important is that this lambda has a return value. Whatever is returned is what the new value in the map will become. &lt;br /&gt;
&lt;br /&gt;
Other methods in Map that you may find helpful are &amp;lt;code&amp;gt;computeIfAbsent&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;merge&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;replace&amp;lt;/code&amp;gt;. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/Map.html Map JavaDocs] for more detailed information on how those methods work.&lt;br /&gt;
&lt;br /&gt;
===Ternary Operators===&lt;br /&gt;
A handy and quick way to do things based on a boolean operation. The two blocks of code are equivalent.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;if(testCondition){&lt;br /&gt;
	int finalResult = valueIfTrue;&lt;br /&gt;
} else{&lt;br /&gt;
	int finalResult = valueIfFalse;&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int finalResult = (testCondition) ? valueIfTrue : valueIfFalse&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===For-each Loop===&lt;br /&gt;
&lt;br /&gt;
For loops don't always need to go from one integer to the next. In fact, if we have any iterable object (array, list, set, etc.), we can just loop through all the entries available in that object. Use this to make your life much simpler!&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;List&amp;lt;T&amp;gt; filledList;&lt;br /&gt;
for(T singleEntry: filledList){&lt;br /&gt;
	doSomething(singleEntry);&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Runtime===&lt;br /&gt;
In order to get the number of processors your computer has:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;int numProcessors = Runtime.getRuntime().availableProcessors();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
Lambdas are very complex things, and they are also incredibly important when it comes to understanding how our code works in this course. If you are looking for more information on what lambdas actually are, '''go check out the [[Lambdas]] wiki page, or the lambdas section in the [[Rundown_on_Everything_Java#Lambdas| Rundown on Everything Java]] page!'''&lt;br /&gt;
&lt;br /&gt;
The syntax for a lambda can be seen as:&lt;br /&gt;
&amp;lt;source&amp;gt;(T parameter) -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Within the curly braces, you will have access to that parameter variable. Most times you use lambdas though, there are no parameters to pass through, so you can just do&lt;br /&gt;
&amp;lt;source&amp;gt;() -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It's strongly encouraged to check out the [[Eclipse_Tips#Content_Assist_lambda_.28.29-.3E.7B.7D| Eclipse tip on how to use content assist lambdas]].&lt;br /&gt;
&lt;br /&gt;
===Anonymous Classes===&lt;br /&gt;
We use anonymous classes throughout the course as a convenient way to instantiate objects of classes that have methods we need to define. There are two ways to do this, one manually labeling the method we're defining, and one with lambda. These are two similar creations of a Function object (which has the method &amp;quot;apply&amp;quot;) that adds one to whatever number is passed in:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = new Function&amp;lt;Integer, Integer&amp;gt;{&lt;br /&gt;
	public Integer apply(Integer oldValue){&lt;br /&gt;
		return oldValue + 1;&lt;br /&gt;
	}&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Function&amp;lt;Integer, Integer&amp;gt; increment = (oldValue) -&amp;gt; {&lt;br /&gt;
	return oldValue + 1;&lt;br /&gt;
};&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Since the class we are defining only has one method, if we use a lambda, it knows that the lambda refers to that one specific method. Check out the section on [Lambdas#Anonymous_Classes|Anonymous Classes] for more information!&lt;br /&gt;
&lt;br /&gt;
===Runnable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html Java Runnable] is an object with just a &amp;lt;code&amp;gt;.run()&amp;lt;/code&amp;gt; method. As discussed above, that means we can instantiate a Runnable using an anonymous class created by a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Runnable body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
body.run();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Callable===&lt;br /&gt;
A [https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html Java Callable] is very similar to a Runnable. It is an object with only a &amp;lt;code&amp;gt;.call()&amp;lt;/code&amp;gt; method. A key difference between this and a Runnable is that a Callable has a return value when called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Callable&amp;lt;V&amp;gt; body = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
V result = body.call();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=V5/Habanero=&lt;br /&gt;
&lt;br /&gt;
Habanero is [http://pasiphae.cs.rice.edu/ Rice's] collection of parallel tools. When you watch the RiceX videos, it is the Habanero version of things you will be seeing. For this course, we've designed [https://www.cse.wustl.edu/~cosgroved/courses/cse231/current/apidocs/edu/wustl/cse231s/v5/V5.html V5]. It is similar to Habanero in most ways, but has small changes to hopefully make your lives easier when it comes to using the tools in this class. Listed below is the syntax for V5's version, but the differences between the two versions are noted to help clarify.&lt;br /&gt;
&lt;br /&gt;
===Async===&lt;br /&gt;
&lt;br /&gt;
Asyncs are our main tool in doing work in parallel. The execution of an async will spawn a new task, and any code written within the braces of an async will be done in that new task. The actual [https://www.cse.wustl.edu/~cosgroved/courses/cse231/summer18/apidocs/edu/wustl/cse231s/v5/V5.html#async-edu.wustl.cse231s.v5.api.CheckedRunnable- async] method is called like this:&lt;br /&gt;
&amp;lt;code&amp;gt;async(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
But as discussed above in the [[#Runnable|Runnable]] section, a Runnable can be defined just using a [[#Lambda|lambda]]. For the runnables in asyncs, there are no parameters passed in, so an async with the lambda is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;async( () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is also worth noting that with the V5 version of async, we can call it as &amp;lt;code&amp;gt;async(Boolean isParallelDesired, Runnable body)&amp;lt;/code&amp;gt;, where the boolean determines whether or not the body is run in a new thread or not. While you'll never need to use this for the assignments, it is a possibility.&lt;br /&gt;
&lt;br /&gt;
===Finish===&lt;br /&gt;
&lt;br /&gt;
Finish blocks will wait until everything within the brackets (no matter the number of tasks) executes and completes before moving on to any of the code after it. This is essential in preventing data races and will be used frequently in the course.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;finish(Runnable body)&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;source&amp;gt;finish( () -&amp;gt; {&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	});&lt;br /&gt;
	asynch( () -&amp;gt; {&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Parallel Loops===&lt;br /&gt;
&lt;br /&gt;
====Forall====&lt;br /&gt;
&lt;br /&gt;
A forall loop is a simplified way to do the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;finish((), -&amp;gt; {&lt;br /&gt;
	for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
		final int i_ = i;&lt;br /&gt;
		async( () -&amp;gt; {&lt;br /&gt;
			doSomething(i_);&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To do that same code with a forall loop, we simply do&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note how this time in the lambda, we are passing a parameter through in the parentheses. This 'i' passed through is the variable that is being incremented. You can also do a forall loop iterating through an iterable object, such as an array or list. That would look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forall(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this case, &amp;lt;code&amp;gt;item&amp;lt;/code&amp;gt; is something of type T from the array. This loop will iterate through all the indicies in the array and spawn a new task for each one.&lt;br /&gt;
&lt;br /&gt;
====Forall Chunked====&lt;br /&gt;
&lt;br /&gt;
Sometimes, you don't want to make a task for each any everything in the iteratable object, as the overhead of spawning tasks outweighs the benefits from parallelism. Chunking allows the creation of the tasks to be manually decided (either by the user or the computer). To use chunking, just pass a ChunkedOption before the object/values to iterate over.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(chunked(), array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Forall 2d====&lt;br /&gt;
&lt;br /&gt;
Instead of doing two forall loops, we can achieve the same result using a single forall2d loop.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall(1stMinInclusive, 1stMaxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	forall(2ndMinInclusive, 2ndMaxExclusive, (j) -&amp;gt; {&lt;br /&gt;
		array[i][j] = doSomething();&lt;br /&gt;
	});&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Is the exact same thing as&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(1stMinInclusive, 1stMaxExclusive, 2ndMinInclusive, 2ndMaxExclusive, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Chunking can also be done on forall2d loops.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forall2d(chunked(), minA, maxExclusiveA, minB, maxExclusiveB, (i, j) -&amp;gt; {&lt;br /&gt;
	array[i][j] = doSomething();&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Forasync====&lt;br /&gt;
&lt;br /&gt;
Functions similarly to a forall loop, but does not have the finish block surrounding the for loop. So in order to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;for(int i = minInclusive; i &amp;lt; maxExclusive; i++){&lt;br /&gt;
	final int _i = i;&lt;br /&gt;
	async( () -&amp;gt; {&lt;br /&gt;
		doSomething(_i);&lt;br /&gt;
	});&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We use the forasync:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forasync(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forasync(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This style of loop does have a 2d option (&amp;lt;code&amp;gt;forasync2d&amp;lt;/code&amp;gt;), and it is possible to use chunking options with it.&lt;br /&gt;
&lt;br /&gt;
====Forseq====&lt;br /&gt;
&lt;br /&gt;
Forseq functions just like a regular for loop (nothing is done in parallel), but it looks similar in structure to a forall loop. Use this when you want to easily switch back and forth between the parallel and sequential versions for testing purposes.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;forseq(minInclusive, maxExclusive, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;T[] array = new T[n];&lt;br /&gt;
forseq(array, (item) -&amp;gt; {&lt;br /&gt;
	doSomething(item);&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There also is a &amp;lt;code&amp;gt;forseq2d&amp;lt;/code&amp;gt; loop that works just like its parallel counterpart. It is also possible to pass in a chunking option in a forseq, but it does not affect the performance of the code.&lt;br /&gt;
&lt;br /&gt;
===Future===&lt;br /&gt;
&lt;br /&gt;
A future is a parallel tool that has a return value. This means that once the work is completed (in another thread), we can call the future and get its returned value. The basic structure of a future is &amp;lt;code&amp;gt;future(Callable&amp;lt;R&amp;gt; body)&amp;lt;/code&amp;gt;. Note that this is similar to an async, but uses a [[#Callable|Callable]] rather than a Runnable. In practice, making a future and storing it so the value can be gotten later looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;R&amp;gt; futureWithTypeR = future(() -&amp;gt; {&lt;br /&gt;
	R item = doSomething();&lt;br /&gt;
	return item;&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then, get the value later on by calling &amp;lt;code&amp;gt;.get()&amp;lt;/code&amp;gt; on the future.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;R result = futureWithTypeR.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Finish Accumulators===&lt;br /&gt;
&lt;br /&gt;
A finish accumulator allows you to do operations (such as counting) within a finish block and make them thread-safe. Then the results can be accessed outside of the finish block. First you have to make the finish accumulator, and then you have to register it with your finish.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;FinishAccumulator&amp;lt;Integer&amp;gt; acc = newIntegerFinishAccumulator(NumberReductionOperator.SUM);&lt;br /&gt;
finish(register(acc), () -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	acc.put(value);&lt;br /&gt;
});&lt;br /&gt;
Integer result = acc.get();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some important notes:&lt;br /&gt;
*&amp;lt;code&amp;gt;register()&amp;lt;/code&amp;gt; is a V5 method that was created for this course to make setting up accumulators a bit easier.&lt;br /&gt;
*Some other NumberReductionOperators you can use are &amp;lt;code&amp;gt;PRODUCT&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;MIN&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;MAX&amp;lt;/code&amp;gt;.&lt;br /&gt;
*Some other types of accumulators are &amp;lt;code&amp;gt;newDoubleFinishAccumulator()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;newReducerFinishAccumulator&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Java X10=&lt;br /&gt;
X10 is Java's built in parallel tools. These are some things you will always be able to use outside of this course. If you have questions on how certain things work, searching for the javadocs for any object or class will normally provide the answers. Here is the syntax for some of the resources we will use in this class.&lt;br /&gt;
&lt;br /&gt;
===Threads===&lt;br /&gt;
&lt;br /&gt;
The most simple way to do something in parallel in Java is to create and run a new thread. The constructor needs to have a &amp;lt;code&amp;gt;run()&amp;lt;/code&amp;gt; method, so we can just use a lambda.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Thread threadToRun = () -&amp;gt; {&lt;br /&gt;
	doSomething();&lt;br /&gt;
}&lt;br /&gt;
threadToRun.start();&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
threadToRun.join();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Executors===&lt;br /&gt;
&lt;br /&gt;
The ExecutorService class has a &amp;lt;code&amp;gt;submit()&amp;lt;/code&amp;gt; function that returns a Future. From there, it isn't to different from our version of Future. In the following example, &amp;lt;code&amp;gt;ExecutorService executor&amp;lt;/code&amp;gt; is passed to us.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Future&amp;lt;Integer&amp;gt; future = executor.submit(() -&amp;gt; {&lt;br /&gt;
	int value = doSomething();&lt;br /&gt;
	return value;&lt;br /&gt;
};&lt;br /&gt;
doSomethingElse();&lt;br /&gt;
future.get()&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Phasers===&lt;br /&gt;
&lt;br /&gt;
There are a lot of things you can do with Phasers. Check out the [https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html official Javadocs] for a breakdown of all the options. Here is an example that uses some of the methods we'll call when utilizing phasers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaserA = new Phaser();&lt;br /&gt;
Phaser phaserB = new Phaser();&lt;br /&gt;
phaserA.register()&lt;br /&gt;
phaserB.register()&lt;br /&gt;
finish(() -&amp;gt; {&lt;br /&gt;
	async(() -&amp;gt; {&lt;br /&gt;
		for(int i = 0; i &amp;lt; 10; i++){&lt;br /&gt;
			doSomething();&lt;br /&gt;
			phaserA.arrive();&lt;br /&gt;
			PhaserUtils.awaitAdvancedForPhase(phaserB, i);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
	&lt;br /&gt;
	for(int j = 0; j &amp;lt; 10; j++){&lt;br /&gt;
		doSomethingElse();&lt;br /&gt;
		phaserB.arrive();&lt;br /&gt;
		PhaserUtils.awaitAdvancedForPhase(phaserA, j);&lt;br /&gt;
	}&lt;br /&gt;
});&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;PhaserUtils.awaitAdvancedForPhase(Phaser phaser, int phaseNumber)&amp;lt;/code&amp;gt; is a tool we have created to make it safer to wait for other phasers. You have have multiple things wait on one phaser by using a bulk register.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Phaser phaser = new Phaser();&lt;br /&gt;
phaser.bulkRegister(3);&lt;br /&gt;
forall(0, 3, (i) -&amp;gt; {&lt;br /&gt;
	doSomething(i);&lt;br /&gt;
	phaser.arriveAndAwaitAdvance();&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronized===&lt;br /&gt;
&lt;br /&gt;
Synchronizing on something prevents on any other thread using (and thus modifying) the synchronized object until it has finished executing the code in the block. You can synchronize on as big or small an object you want. The example below, both uses of synchronized will make the class thread safe, but they have different performance implications.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;public class Foo{&lt;br /&gt;
	public List&amp;lt;T&amp;gt; list;&lt;br /&gt;
&lt;br /&gt;
	public Foo(){&lt;br /&gt;
		this.list = new LinkedList&amp;lt;&amp;gt;();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void addToList(){&lt;br /&gt;
		synchronized(this){&lt;br /&gt;
			this.list.add(new T());&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public void removeFromList(){&lt;br /&gt;
		synchronized(this.list){&lt;br /&gt;
			this.list.poll();&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Locks===&lt;br /&gt;
&lt;br /&gt;
Locks are an alternative to synchronized. With proper use of locks, we can make our methods thread safe. Here's a couple examples that showcase the syntax for locks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Reentrant lock = ...&lt;br /&gt;
lock.lock();&lt;br /&gt;
doSomething();&lt;br /&gt;
lock.unlock();&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;source&amp;gt;Lock lock = ...&lt;br /&gt;
if (lock.tryLock()) {&lt;br /&gt;
	try {&lt;br /&gt;
		doSomething();&lt;br /&gt;
	} finally {&lt;br /&gt;
		lock.unlock();&lt;br /&gt;
	}&lt;br /&gt;
}&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Others=&lt;br /&gt;
&lt;br /&gt;
===Entries===&lt;br /&gt;
In a lot of assignments, you will need to make entries of different types. Almost always, the &amp;lt;code&amp;gt;KeyValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;KeyMutableValuePair&amp;lt;K,V&amp;gt;&amp;lt;/code&amp;gt; will be your best options.&lt;br /&gt;
&amp;lt;source&amp;gt;KeyValuePair&amp;lt;String, int&amp;gt; newEntry = new KeyValuePair&amp;lt;&amp;gt;(&amp;quot;A&amp;quot;, 1);&amp;lt;/source&amp;gt;&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=Syntax_of_231&amp;diff=2172</id>
		<title>Syntax of 231</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=Syntax_of_231&amp;diff=2172"/>
		<updated>2018-07-23T04:38:01Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: Miles.p.cushing moved page Syntax of 231 to Reference Page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;#REDIRECT [[Reference Page]]&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2159</id>
		<title>MatrixMultiply</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2159"/>
		<updated>2018-07-17T09:45:43Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Forall2dMatrixMultiplier */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
We gain experience using the parallel for loop constructs.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&lt;br /&gt;
Matrix multiplication is a simple mathematical operation which we will replicate in this studio. For our purposes, we will only deal with square matrices (same number of rows and columns). However, we will approach this problem with several different parallel constructs and approaches.&lt;br /&gt;
&lt;br /&gt;
For those unfamiliar on how to multiply two matrices, take a look at these overviews:&lt;br /&gt;
* [https://www.mathsisfun.com/algebra/matrix-multiplying.html Math Is Fun]&lt;br /&gt;
* [http://mathworld.wolfram.com/MatrixMultiplication.html Wolfram MathWorld]&lt;br /&gt;
* [https://en.wikipedia.org/wiki/Matrix_multiplication Wikipedia]&lt;br /&gt;
==Math Definition==&lt;br /&gt;
If &amp;lt;math&amp;gt;\mathbf{A}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;n \times m&amp;lt;/math&amp;gt; matrix and &amp;lt;math&amp;gt;\mathbf{B}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;m  \times p&amp;lt;/math&amp;gt; matrix&lt;br /&gt;
&lt;br /&gt;
for each i=[0..n) and for each j=[0..p)&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;(\mathbf{A}\mathbf{B})_{ij} = \sum_{k=1}^m A_{ik}B_{kj}&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/wiki/Matrix_multiplication#General_definition_of_the_matrix_product Matrix Multiplication on Wikipedia]&lt;br /&gt;
&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
The point of the required portion of this studio is not to struggle with matrix multiplication, but rather to get some experience with the parallel for loop constructs in Habanero.&lt;br /&gt;
&lt;br /&gt;
Feel free to use the provided sequential implementation in SequentialMatrixMultiplier as a reference:&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public double[][] multiply(double[][] a, double[][] b) {&lt;br /&gt;
		double[][] result = MatrixUtils.createMultiplyResultBufferInitializedToZeros(a, b);&lt;br /&gt;
		int n = a.length;&lt;br /&gt;
		int m = a[0].length;&lt;br /&gt;
		int p = b[0].length;&lt;br /&gt;
		for (int i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
			for (int j = 0; j &amp;lt; p; j++) {&lt;br /&gt;
				// NOTE: result is already initialized to 0.0&lt;br /&gt;
				// result[i][j] = 0.0;&lt;br /&gt;
				for (int k = 0; k &amp;lt; m; k++) {&lt;br /&gt;
					result[i][j] += a[i][k] * b[k][j];&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
		return result;&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[[Syntax_of_231#Parallel_Loops|Wiki's syntax page]]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(start, endExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(chunked(), start, endExclusive, body)]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(aMin, aMaxExclusive, bMin, bMaxExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(chunked(), aMin, aMaxExclusive, bMin, bMaxExclusive, body)]&lt;br /&gt;
&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-- chunked()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-int- chunked(size)]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Habanero Documentation==&lt;br /&gt;
WARNING: Habanero from Rice is '''inclusive'''.  So, its loops are specified from 0 to n-1.  CSE 231's wrapper is '''exclusive on max''' so it is specified 0 to n.&lt;br /&gt;
&lt;br /&gt;
[http://pasiphae.cs.rice.edu/#hjlib-for Habanero for loops]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Common Mistakes To Avoid=&lt;br /&gt;
{{Warning|CSE 231 is exclusive on max.  While we implemented our own X10/Habanero we changed forall(0, n-1, body) to forall(0, n, body) for everything.}}&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
&lt;br /&gt;
There are three methods you will need to implement, all of which are different ways to use parallel for loops to solve the problem. To assist you, the sequential implementation has already been completed for you. We recommend starting from the top and working your way down. There is also an optional recursive implementation and a manual grouping implementation which has been done for you (this is just to demonstrate how chunking works behind the scenes).&lt;br /&gt;
&lt;br /&gt;
==ForallForallMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|ForallForallMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, you will simply convert the sequential solution into a parallel one using two forall loops.&lt;br /&gt;
&lt;br /&gt;
==Forall2dMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will cut down the syntax of the two forall implementation with the use of HJ’s &amp;lt;code&amp;gt;forall2d&amp;lt;/code&amp;gt; method. Functionally, this method serves the purpose of using two forall loops. [[Syntax_of_231#Forall_2d|Take a look at the syntax page]] if you have questions on how to utilize this loop.&lt;br /&gt;
&lt;br /&gt;
==Forall2dChunkedMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dChunkedMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will add a minor performance boost to the process by using the forall-chunked construct. Although similar to the traditional forall loop, it increases performance using iteration grouping/chunking. This topic is discussed in detail in this [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/6349730bb2a149a0b33fa23db7afddee/?activate_block_id=i4x%3A%2F%2FRiceX%2FCOMP322%2Fsequential%2F6349730bb2a149a0b33fa23db7afddee Rice video] and explained in the [http://pasiphae.cs.rice.edu/#hjlib-for-parallelchunkediterationwithimplicitfinish HJ documentation]. There is no need to specify anything, allow the runtime to determine the chunking.&lt;br /&gt;
&lt;br /&gt;
NOTE: we contemplated also assigning building a 1D forall chunked version.  We deemed this more work that it was worth given that you are already building the 2d version.  Just know that forall(chunked(), ...) exists for 1d loops as well.  &lt;br /&gt;
&lt;br /&gt;
Use chunking.  It is a nice feature.&lt;br /&gt;
&lt;br /&gt;
=Optional Divide and Conquer Challenges=&lt;br /&gt;
In this implementation, you will solve the matrix multiply problem sequentially and in parallel using recursion. Although this class should be able to take in a matrix of any size, try to imagine this as a 2x2 matrix in order to make it easier to solve. Once you solve the sequential method, the parallel method should look very similar with exception of an async/finish block.&lt;br /&gt;
&lt;br /&gt;
In order to obtain the desired result matrix, you will need to recursively call the correct submatrices for each of the four result submatrices. Imagining this as a 2x2 matrix, remember that the dot products of the rows of the first matrix and the columns of the second matrix create the result matrix.&lt;br /&gt;
&lt;br /&gt;
Hint: Each result submatrix should have two recursive calls, for a total of eight recursive calls.&lt;br /&gt;
&lt;br /&gt;
==SequentialDivideAndConquerMatrixMultiplier==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SubMatrix|sequentialDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
In &amp;lt;code&amp;gt;class SubMatrix&amp;lt;/code&amp;gt;, method &amp;lt;code&amp;gt;sequentialDivideAndConquerMultiplyKernel&amp;lt;/code&amp;gt; you will find your base case and the sub matrices prepared for you.  &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
	private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result) {&lt;br /&gt;
		if( result.size == 1 ) {&lt;br /&gt;
			result.values[result.row][result.col] += a.values[a.row][a.col] * b.values[b.row][b.col];&lt;br /&gt;
		} else {&lt;br /&gt;
			SubMatrix a11 = a.newSub11();&lt;br /&gt;
			SubMatrix a12 = a.newSub12();&lt;br /&gt;
			SubMatrix a21 = a.newSub21();&lt;br /&gt;
			SubMatrix a22 = a.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix b11 = b.newSub11();&lt;br /&gt;
			SubMatrix b12 = b.newSub12();&lt;br /&gt;
			SubMatrix b21 = b.newSub21();&lt;br /&gt;
			SubMatrix b22 = b.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix result11 = result.newSub11();&lt;br /&gt;
			SubMatrix result12 = result.newSub12();&lt;br /&gt;
			SubMatrix result21 = result.newSub21();&lt;br /&gt;
			SubMatrix result22 = result.newSub22();&lt;br /&gt;
&lt;br /&gt;
			throw new NotYetImplementedException();&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You simply need to make the appropriate recursive calls to compute the result on the right:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} &amp;amp; \mathbf{A}_{12} \\&lt;br /&gt;
\mathbf{A}_{21} &amp;amp; \mathbf{A}_{22} \\&lt;br /&gt;
\end{pmatrix} \begin{pmatrix}&lt;br /&gt;
\mathbf{B}_{11} &amp;amp; \mathbf{B}_{12} \\&lt;br /&gt;
\mathbf{B}_{21} &amp;amp; \mathbf{B}_{22} \\&lt;br /&gt;
\end{pmatrix} = \begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
==ParallelDivideAndConquerMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|SubMatrix|parallelDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void parallelDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
Again, given the following:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
What computation can be done in parallel?  What computation must be performed sequentially?&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=Provided Example Implementations=&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
==ForallGroupedMatrixMultiplier==&lt;br /&gt;
For 231 we are encouraging you to prefer the use of chunked().  However, if you want greater control over how your loops are broken up, please look to this as an example of how to use forall grouped.&lt;br /&gt;
&lt;br /&gt;
==Forall2dGroupedMatrixMultiplier==&lt;br /&gt;
Same as above but with forall2d.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.studio}}&lt;br /&gt;
==Optional Fun Divide And Conquer Matrix Multiply Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.fun}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|MatrixMultiplicationTiming|matrixmultiply.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
	<entry>
		<id>http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2158</id>
		<title>MatrixMultiply</title>
		<link rel="alternate" type="text/html" href="http://classes.engineering.wustl.edu/cse231/core/index.php?title=MatrixMultiply&amp;diff=2158"/>
		<updated>2018-07-17T09:45:18Z</updated>

		<summary type="html">&lt;p&gt;Miles.p.cushing: /* Forall2dMatrixMultiplier */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Motivation=&lt;br /&gt;
We gain experience using the parallel for loop constructs.&lt;br /&gt;
&lt;br /&gt;
=Background=&lt;br /&gt;
&lt;br /&gt;
Matrix multiplication is a simple mathematical operation which we will replicate in this studio. For our purposes, we will only deal with square matrices (same number of rows and columns). However, we will approach this problem with several different parallel constructs and approaches.&lt;br /&gt;
&lt;br /&gt;
For those unfamiliar on how to multiply two matrices, take a look at these overviews:&lt;br /&gt;
* [https://www.mathsisfun.com/algebra/matrix-multiplying.html Math Is Fun]&lt;br /&gt;
* [http://mathworld.wolfram.com/MatrixMultiplication.html Wolfram MathWorld]&lt;br /&gt;
* [https://en.wikipedia.org/wiki/Matrix_multiplication Wikipedia]&lt;br /&gt;
==Math Definition==&lt;br /&gt;
If &amp;lt;math&amp;gt;\mathbf{A}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;n \times m&amp;lt;/math&amp;gt; matrix and &amp;lt;math&amp;gt;\mathbf{B}&amp;lt;/math&amp;gt; is an &amp;lt;math&amp;gt;m  \times p&amp;lt;/math&amp;gt; matrix&lt;br /&gt;
&lt;br /&gt;
for each i=[0..n) and for each j=[0..p)&lt;br /&gt;
&lt;br /&gt;
: &amp;lt;math&amp;gt;(\mathbf{A}\mathbf{B})_{ij} = \sum_{k=1}^m A_{ik}B_{kj}&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/wiki/Matrix_multiplication#General_definition_of_the_matrix_product Matrix Multiplication on Wikipedia]&lt;br /&gt;
&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
The point of the required portion of this studio is not to struggle with matrix multiplication, but rather to get some experience with the parallel for loop constructs in Habanero.&lt;br /&gt;
&lt;br /&gt;
Feel free to use the provided sequential implementation in SequentialMatrixMultiplier as a reference:&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;	@Override&lt;br /&gt;
	public double[][] multiply(double[][] a, double[][] b) {&lt;br /&gt;
		double[][] result = MatrixUtils.createMultiplyResultBufferInitializedToZeros(a, b);&lt;br /&gt;
		int n = a.length;&lt;br /&gt;
		int m = a[0].length;&lt;br /&gt;
		int p = b[0].length;&lt;br /&gt;
		for (int i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
			for (int j = 0; j &amp;lt; p; j++) {&lt;br /&gt;
				// NOTE: result is already initialized to 0.0&lt;br /&gt;
				// result[i][j] = 0.0;&lt;br /&gt;
				for (int k = 0; k &amp;lt; m; k++) {&lt;br /&gt;
					result[i][j] += a[i][k] * b[k][j];&lt;br /&gt;
				}&lt;br /&gt;
			}&lt;br /&gt;
		}&lt;br /&gt;
		return result;&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Code To Use=&lt;br /&gt;
[[Syntax_of_231#Parallel_Loops|Wiki's syntax page]]&lt;br /&gt;
&lt;br /&gt;
[https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html V5]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(start, endExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-edu.wustl.cse231s.v5.api.CheckedIntConsumer- forall(chunked(), start, endExclusive, body)]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(aMin, aMaxExclusive, bMin, bMaxExclusive, body)] &lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#forall2d-edu.wustl.cse231s.v5.options.ChunkedOption-int-int-int-int-edu.wustl.cse231s.v5.api.CheckedIntIntConsumer- forall2d(chunked(), aMin, aMaxExclusive, bMin, bMaxExclusive, body)]&lt;br /&gt;
&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-- chunked()]&lt;br /&gt;
: [https://www.cse.wustl.edu/~cosgroved/courses/cse231/s18/apidocs/edu/wustl/cse231s/v5/V5.html#chunked-int- chunked(size)]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
==Habanero Documentation==&lt;br /&gt;
WARNING: Habanero from Rice is '''inclusive'''.  So, its loops are specified from 0 to n-1.  CSE 231's wrapper is '''exclusive on max''' so it is specified 0 to n.&lt;br /&gt;
&lt;br /&gt;
[http://pasiphae.cs.rice.edu/#hjlib-for Habanero for loops]&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Common Mistakes To Avoid=&lt;br /&gt;
{{Warning|CSE 231 is exclusive on max.  While we implemented our own X10/Habanero we changed forall(0, n-1, body) to forall(0, n, body) for everything.}}&lt;br /&gt;
&lt;br /&gt;
=Code To Implement=&lt;br /&gt;
&lt;br /&gt;
There are three methods you will need to implement, all of which are different ways to use parallel for loops to solve the problem. To assist you, the sequential implementation has already been completed for you. We recommend starting from the top and working your way down. There is also an optional recursive implementation and a manual grouping implementation which has been done for you (this is just to demonstrate how chunking works behind the scenes).&lt;br /&gt;
&lt;br /&gt;
==ForallForallMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|ForallForallMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, you will simply convert the sequential solution into a parallel one using two forall loops.&lt;br /&gt;
&lt;br /&gt;
==Forall2dMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will cut down the syntax of the two forall implementation with the use of HJ’s &amp;lt;code&amp;gt;forall2d&amp;lt;/code&amp;gt; method. Functionally, this method serves the purpose of using two forall loops. Take a look at the [[Syntax_of_231#Forall_2d|syntax page]] if you have questions on how to utilize this loop.&lt;br /&gt;
&lt;br /&gt;
==Forall2dChunkedMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|Forall2dChunkedMatrixMultiplier|multiply|matrixmultiply.studio}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|public double[][] multiply(double[][] a, double[][] b)}}&lt;br /&gt;
&lt;br /&gt;
In this implementation, we will add a minor performance boost to the process by using the forall-chunked construct. Although similar to the traditional forall loop, it increases performance using iteration grouping/chunking. This topic is discussed in detail in this [https://edge.edx.org/courses/RiceX/COMP322/1T2014R/courseware/a900dd0655384de3b5ef01e508ea09d7/6349730bb2a149a0b33fa23db7afddee/?activate_block_id=i4x%3A%2F%2FRiceX%2FCOMP322%2Fsequential%2F6349730bb2a149a0b33fa23db7afddee Rice video] and explained in the [http://pasiphae.cs.rice.edu/#hjlib-for-parallelchunkediterationwithimplicitfinish HJ documentation]. There is no need to specify anything, allow the runtime to determine the chunking.&lt;br /&gt;
&lt;br /&gt;
NOTE: we contemplated also assigning building a 1D forall chunked version.  We deemed this more work that it was worth given that you are already building the 2d version.  Just know that forall(chunked(), ...) exists for 1d loops as well.  &lt;br /&gt;
&lt;br /&gt;
Use chunking.  It is a nice feature.&lt;br /&gt;
&lt;br /&gt;
=Optional Divide and Conquer Challenges=&lt;br /&gt;
In this implementation, you will solve the matrix multiply problem sequentially and in parallel using recursion. Although this class should be able to take in a matrix of any size, try to imagine this as a 2x2 matrix in order to make it easier to solve. Once you solve the sequential method, the parallel method should look very similar with exception of an async/finish block.&lt;br /&gt;
&lt;br /&gt;
In order to obtain the desired result matrix, you will need to recursively call the correct submatrices for each of the four result submatrices. Imagining this as a 2x2 matrix, remember that the dot products of the rows of the first matrix and the columns of the second matrix create the result matrix.&lt;br /&gt;
&lt;br /&gt;
Hint: Each result submatrix should have two recursive calls, for a total of eight recursive calls.&lt;br /&gt;
&lt;br /&gt;
==SequentialDivideAndConquerMatrixMultiplier==&lt;br /&gt;
&lt;br /&gt;
{{CodeToImplement|SubMatrix|sequentialDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Sequential|private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
In &amp;lt;code&amp;gt;class SubMatrix&amp;lt;/code&amp;gt;, method &amp;lt;code&amp;gt;sequentialDivideAndConquerMultiplyKernel&amp;lt;/code&amp;gt; you will find your base case and the sub matrices prepared for you.  &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
	private static void sequentialDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result) {&lt;br /&gt;
		if( result.size == 1 ) {&lt;br /&gt;
			result.values[result.row][result.col] += a.values[a.row][a.col] * b.values[b.row][b.col];&lt;br /&gt;
		} else {&lt;br /&gt;
			SubMatrix a11 = a.newSub11();&lt;br /&gt;
			SubMatrix a12 = a.newSub12();&lt;br /&gt;
			SubMatrix a21 = a.newSub21();&lt;br /&gt;
			SubMatrix a22 = a.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix b11 = b.newSub11();&lt;br /&gt;
			SubMatrix b12 = b.newSub12();&lt;br /&gt;
			SubMatrix b21 = b.newSub21();&lt;br /&gt;
			SubMatrix b22 = b.newSub22();&lt;br /&gt;
			&lt;br /&gt;
			SubMatrix result11 = result.newSub11();&lt;br /&gt;
			SubMatrix result12 = result.newSub12();&lt;br /&gt;
			SubMatrix result21 = result.newSub21();&lt;br /&gt;
			SubMatrix result22 = result.newSub22();&lt;br /&gt;
&lt;br /&gt;
			throw new NotYetImplementedException();&lt;br /&gt;
		}&lt;br /&gt;
	}&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You simply need to make the appropriate recursive calls to compute the result on the right:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} &amp;amp; \mathbf{A}_{12} \\&lt;br /&gt;
\mathbf{A}_{21} &amp;amp; \mathbf{A}_{22} \\&lt;br /&gt;
\end{pmatrix} \begin{pmatrix}&lt;br /&gt;
\mathbf{B}_{11} &amp;amp; \mathbf{B}_{12} \\&lt;br /&gt;
\mathbf{B}_{21} &amp;amp; \mathbf{B}_{22} \\&lt;br /&gt;
\end{pmatrix} = \begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
==ParallelDivideAndConquerMatrixMultiplier==&lt;br /&gt;
{{CodeToImplement|SubMatrix|parallelDivideAndConquerMultiplyKernel|matrixmultiply.fun}}&lt;br /&gt;
&lt;br /&gt;
{{Parallel|private static void parallelDivideAndConquerMultiplyKernel(SubMatrix a, SubMatrix b, SubMatrix result)}}&lt;br /&gt;
&lt;br /&gt;
Again, given the following:&lt;br /&gt;
&lt;br /&gt;
:&amp;lt;math&amp;gt;\begin{pmatrix}&lt;br /&gt;
\mathbf{A}_{11} \mathbf{B}_{11} + \mathbf{A}_{12} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{11} \mathbf{B}_{12} + \mathbf{A}_{12} \mathbf{B}_{22}\\&lt;br /&gt;
\mathbf{A}_{21} \mathbf{B}_{11} + \mathbf{A}_{22} \mathbf{B}_{21} &amp;amp; \mathbf{A}_{21} \mathbf{B}_{12} + \mathbf{A}_{22} \mathbf{B}_{22}\\&lt;br /&gt;
\end{pmatrix}&lt;br /&gt;
&amp;lt;/math&amp;gt;&lt;br /&gt;
source: [https://en.wikipedia.org/w/index.php?title=Matrix_multiplication#Parallel_matrix_multiplication Wikipedia Parallel Matrix Multiplication]&lt;br /&gt;
&lt;br /&gt;
What computation can be done in parallel?  What computation must be performed sequentially?&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
=Provided Example Implementations=&lt;br /&gt;
==SequentialMatrixMultiplier==&lt;br /&gt;
We provide the sequential iterative implementation so you can focus just on becoming familiar with using Habanero's forall loops.&lt;br /&gt;
&lt;br /&gt;
==ForallGroupedMatrixMultiplier==&lt;br /&gt;
For 231 we are encouraging you to prefer the use of chunked().  However, if you want greater control over how your loops are broken up, please look to this as an example of how to use forall grouped.&lt;br /&gt;
&lt;br /&gt;
==Forall2dGroupedMatrixMultiplier==&lt;br /&gt;
Same as above but with forall2d.&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Testing Your Solution=&lt;br /&gt;
==Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.studio}}&lt;br /&gt;
==Optional Fun Divide And Conquer Matrix Multiply Correctness==&lt;br /&gt;
{{TestSuite|MatrixMultiplyTestSuite|matrixmultiply.fun}}&lt;br /&gt;
==Performance==&lt;br /&gt;
{{Performance|MatrixMultiplicationTiming|matrixmultiply.studio}}&lt;/div&gt;</summary>
		<author><name>Miles.p.cushing</name></author>
		
	</entry>
</feed>