<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@Reading_5_Objectives" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Reading 5 Objectives</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_6f7f450863c1">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_6f7f450863c1" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<h4>Software in 6.005</h4>
<table class="table table-striped no-markdown">
<tbody>
<tr>
<th width="33%">Safe from bugs</th>
<th>Easy to understand</th>
<th>Ready for change</th>
</tr>
<tr>
<td>
Correct today and correct in the unknown future.
</td>
<td>
Communicating clearly with future programmers, including future you.
</td>
<td>
Designed to accommodate change without rewriting.
</td>
</tr>
</tbody>
</table>
<h4>Objectives</h4>
<ul>
<li>The message passing and shared memory models of concurrency</li>
<li>Concurrent processes and threads, and time slicing</li>
<li>The danger of race conditions</li>
</ul>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical-two-models" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Two Models for Concurrent Programming</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_d4af89dfb27c">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_d4af89dfb27c" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<h2 id="concurrency">Concurrency</h2>
<div data-outline="concurrency">
<p><em>Concurrency</em> means multiple computations are happening at the same time. Concurrency is everywhere in modern programming, whether we like it or not:</p>
<ul>
<li>Multiple computers in a network</li>
<li>Multiple applications running on one computer</li>
<li>Multiple processors in a computer (today, often multiple processor cores on a single chip) </li>
</ul>
<p>In fact, concurrency is essential in modern programming:</p>
<ul>
<li>Web sites must handle multiple simultaneous users.</li>
<li>Mobile apps need to do some of their processing on servers (“in the cloud”).</li>
<li>Graphical user interfaces almost always require background work that does not interrupt the user. For example, Eclipse compiles your Java code while you're still editing it.</li>
</ul>
<p>Being able to program with concurrency will still be important in the future. Processor clock speeds are no longer increasing. Instead, we're getting more cores with each new generation of chips. So in the future, in order to get a computation to run faster, we'll have to split up a computation into concurrent pieces.</p>
</div>
<h2 id="two_models_for_concurrent_programming">Two Models for Concurrent Programming</h2>
<div data-outline="two_models_for_concurrent_programming">
<p>There are two common models for concurrent programming: <em>shared memory</em> and <em>message passing</em>.</p>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/f813c55964fe062ce196d502a26419f9/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/05-shared-memory.png" alt="shared memory" width="300"></div>
<p><strong>Shared memory.</strong> In the shared memory model of concurrency, concurrent modules interact by reading and writing shared objects in memory. </p>
<p>Examples of the shared-memory model: </p>
<ul>
<li>
<p>A and B might be two processors (or processor cores) in the same computer, sharing the same physical memory.</p>
</li>
<li>
<p>A and B might be two programs running on the same computer, sharing a common filesystem with files they can read and write.</p>
</li>
<li>
<p>A and B might be two threads in the same Java program (we'll explain what a thread is below), sharing the same Java objects.</p>
</li>
</ul>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/fb0b4ab0f90e1926a7667ab98aa741d8/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/05-message-passing.png" alt="message passing" width="200"></div>
<p><strong>Message passing.</strong> In the message-passing model, concurrent modules interact by sending messages to each other through a communication channel. Modules send off messages, and incoming messages to each module are queued up for handling. Examples include:</p>
<ul>
<li>
<p>A and B might be two computers in a network, communicating by network connections.</p>
</li>
<li>
<p>A and B might be a web browser and a web server — A opens a connection to B and asks for a web page, and B sends the web page data back to A.</p>
</li>
<li>
<p>A and B might be an instant messaging client and server.</p>
</li>
<li>
<p>A and B might be two programs running on the same computer whose input and output have been connected by a pipe, like <code>ls | grep</code> typed into a command prompt.</p>
</li>
</ul>
</div>
<h2 id="processes_threads_time-slicing">Processes, Threads, Time-slicing</h2>
<div data-outline="processes_threads_time-slicing">
<p>The message-passing and shared-memory models are about how concurrent modules communicate. The concurrent modules themselves come in two different kinds: processes and threads.</p>
<p><strong>Process</strong>. A process is an instance of a running program that is <em>isolated</em> from other processes on the same machine. In particular, it has its own private section of the machine's memory.</p>
<p>The process abstraction is a <em>virtual computer</em>. It makes the program feel like it has the entire machine to itself — like a fresh computer has been created, with fresh memory, just to run that program.</p>
<p>Just like computers connected across a network, processes normally share no memory between them. A process can't access another process's memory or objects at all. Sharing memory between processes is <em>possible</em> on most operating systems, but it needs special effort. By contrast, a new process is automatically ready for message passing, because it is created with standard input & output streams, which are the <code>System.out</code> and <code>System.in</code> streams you've used in Java.</p>
<p><strong>Thread</strong>. A thread is a locus of control inside a running program. Think of it as a place in the program that is being run, plus the stack of method calls that led to that place (so the thread can go back up the stack when it reaches <code>return</code> statements).</p>
<p>Just as a process represents a virtual computer, the thread abstraction represents a <em>virtual processor</em>. Making a new thread simulates making a fresh processor inside the virtual computer represented by the process. This new virtual processor runs the same program and shares the same memory as other threads in the process.</p>
<p>Threads are automatically ready for shared memory, because threads share all the memory in the process. It takes special effort to get “thread-local” memory that's private to a single thread. It's also necessary to set up message-passing explicitly, by creating and using queue data structures. We'll talk about how to do that in a future reading.</p>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/c0d27c5a74cfe449d004f16cf7662cf6/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/05-time-slicing.png" alt="time-slicing" width="300"></div>
<p>How can I have many concurrent threads with only one or two processors in my computer? When there are more threads than processors, concurrency is simulated by <strong>time slicing</strong>, which means that the processor switches between threads. The figure on the right shows how three threads T1, T2, and T3 might be time-sliced on a machine that has only two actual processors. In the figure, time proceeds downward, so at first one processor is running thread T1 and the other is running thread T2, and then the second processor switches to run thread T3. Thread T2 simply pauses, until its next time slice on the same processor or another processor.</p>
<p>On most systems, time slicing happens unpredictably and nondeterministically, meaning that a thread may be paused or resumed at any time.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical_Questions_159a3841f092" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Processes_Threads">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Processes_Threads" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/c9cee8830885f59e75b8782f44026226/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-57">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-57" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-processes-threads-57" class="problems-wrapper" role="group"
aria-labelledby="05-processes-threads-57-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-57" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-57/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-processes-threads-57-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-57-problem-progress" tabindex="-1">
Processes and threads 1
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-57-problem-progress"></div>
<div class="problem">
<div>
<p>When you run a Java program (for example, using the Run button in Eclipse), how many processes and threads are created at first?</p>
<p>Processes:</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="inputtype option-input ">
<select name="input_05-processes-threads-57_2_1" id="input_05-processes-threads-57_2_1" aria-describedby="status_05-processes-threads-57_2_1">
<option value="option_05-processes-threads-57_2_1_dummy_default">Select an option</option>
<option value="no processes"> no processes</option>
<option value="one process"> one process</option>
<option value="one process for each class in the program"> one process for each class in the program</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_05-processes-threads-57_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_05-processes-threads-57_2_1"/>
</div></div>
<p>Threads:</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="inputtype option-input ">
<select name="input_05-processes-threads-57_3_1" id="input_05-processes-threads-57_3_1" aria-describedby="status_05-processes-threads-57_3_1">
<option value="option_05-processes-threads-57_3_1_dummy_default">Select an option</option>
<option value="no threads"> no threads</option>
<option value="one thread"> one thread</option>
<option value="one thread for each class in the program"> one thread for each class in the program</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_05-processes-threads-57_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_05-processes-threads-57_3_1"/>
</div></div>
<div class="solution-span">
<span id="solution_05-processes-threads-57_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Processes and threads 1" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-processes-threads-57" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-processes-threads-57">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-57-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-57-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-57-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical-anonymous-class" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Starting a thread with an anonymous class</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_5b33b7d1fad4">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_5b33b7d1fad4" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<h2 id="anonymous_classes">Starting a thread with an anonymous class</h2>
<div data-outline="anonymous_classes">
<p>Before talking about how to start a new thread in Java, it's useful to take a detour and talk about <em>anonymous classes</em>, because that language feature is the usual way that threads are started in Java. An anonymous class is an implementation of an interface that has no class name of its own.</p>
<p>Usually when we implement an interface, we do so by declaring a class. For example, given the interface <a href="http://docs.oracle.com/javase/8/docs/api/?java/util/Comparator.html"><code>Comparator</code></a> in the Java API:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** A comparison function that imposes a total ordering on some objects.
* ... */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Comparator</span><<span class="hljs-title">T</span>> </span>{
<span class="hljs-comment handout-javadoc-comment">/** Compares its two arguments for order.
* ...
* <span class="hljs-doctag">@return</span> a negative integer, zero, or a positive integer if the first
* argument is less than, equal to, or greater than the second */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">compare</span><span class="hljs-params">(T o1, T o2)</span></span>;
}</code></pre>
<p>We might declare:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** Orders Strings by length (shorter first) and then lexicographically. */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StringLengthComparator</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Comparator</span><<span class="hljs-title">String</span>> </span>{
<span class="hljs-annotation">@Override</span> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">compare</span><span class="hljs-params">(String s1, String s2)</span> </span>{
<span class="hljs-keyword">if</span> (s1.length() == s2.length()) {
<span class="hljs-keyword">return</span> s1.compareTo(s2);
}
<span class="hljs-keyword">return</span> s1.length() - s2.length();
}
}</code></pre>
<p>One purpose of <code>Comparator</code> is for sorting. A <a href="http://docs.oracle.com/javase/8/docs/api/?java/util/SortedSet.html"><code>SortedSet</code></a> keeps its items in a total order.</p>
<p>Without a <code>Comparator</code>, the <code>SortedSet</code> implementation uses the <code>compareTo</code> method provided by the objects in the set:</p><pre><code class="language-java hljs">SortedSet<String> strings = <span class="hljs-keyword">new</span> TreeSet<>();
strings.addAll(Arrays.asList(<span class="hljs-string">"yolanda"</span>, <span class="hljs-string">"zach"</span>, <span class="hljs-string">"alice"</span>, <span class="hljs-string">"bob"</span>));
<span class="hljs-comment">// strings is { "alice", "bob", "yolanda", "zach" }</span></code></pre>
<p>With a <code>Comparator</code>:</p><pre><code class="language-java hljs"><span class="hljs-comment">// uses StringLengthComparator declared above</span>
Comparator<String> compareByLength = <span class="hljs-keyword">new</span> StringLengthComparator();
SortedSet<String> strings = <span class="hljs-keyword">new</span> TreeSet<>(compareByLength);
strings.addAll(Arrays.asList(<span class="hljs-string">"yolanda"</span>, <span class="hljs-string">"zach"</span>, <span class="hljs-string">"alice"</span>, <span class="hljs-string">"bob"</span>));
<span class="hljs-comment">// strings is { "bob", "zach", "alice", "yolanda" }</span></code></pre>
<p>If we only intend to use this comparator in this one place, we already know how to eliminate the variable:</p><pre><code class="language-java hljs"><span class="hljs-comment">// uses StringLengthComparator declared above</span>
SortedSet<String> strings = <span class="hljs-keyword">new</span> TreeSet<>(<span class="hljs-keyword">new</span> StringLengthComparator());
strings.addAll(Arrays.asList(<span class="hljs-string">"yolanda"</span>, <span class="hljs-string">"zach"</span>, <span class="hljs-string">"alice"</span>, <span class="hljs-string">"bob"</span>));
<span class="hljs-comment">// strings is { "bob", "zach", "alice", "yolanda" }</span></code></pre>
<p>An <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html"><strong>anonymous class</strong></a> declares an unnamed class that implements an interface and immediately creates the one and only instance of that class. Compare to the code above:</p><pre><code class="language-java hljs"><span class="hljs-comment">// no StringLengthComparator class!</span>
SortedSet<String> strings = <span class="hljs-keyword">new</span> TreeSet<>(<span class="hljs-keyword">new</span> Comparator<String>() {
<span class="hljs-annotation">@Override</span> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">compare</span><span class="hljs-params">(String s1, String s2)</span> </span>{
<span class="hljs-keyword">if</span> (s1.length() == s2.length()) {
<span class="hljs-keyword">return</span> s1.compareTo(s2);
}
<span class="hljs-keyword">return</span> s1.length() - s2.length();
}});
strings.addAll(Arrays.asList(<span class="hljs-string">"yolanda"</span>, <span class="hljs-string">"zach"</span>, <span class="hljs-string">"alice"</span>, <span class="hljs-string">"bob"</span>));
<span class="hljs-comment">// strings is { "bob", "zach", "alice", "yolanda" }</span></code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li>
<p>If we're only using the comparator in this one piece of code, we've reduced its scope. Previously, any other code could start using and depending on <code>StringLengthComparator</code>.</p>
</li>
<li>
<p>A reader no longer has to search elsewhere for the details of the comparator, everything is right here.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>
<p>If we need the same comparator more than once, we might be tempted to copy-and-paste. The old way is DRY.</p>
</li>
<li>
<p>If the implementation of the comparator is long, it interrupts the surrounding code, making it harder to understand. The old way is broken into modular pieces.</p>
</li>
</ul>
<p>So anonymous classes are good for short one-off implementations of a method.</p>
</div>
<h2 id="using_an_anonymous_runnable_to_start_a_thread">Using an anonymous <code>Runnable</code> to start a thread</h2>
<div data-outline="using_an_anonymous_runnable_to_start_a_thread">
<p>To start a new thread, we create an anonymous implementation of <code>Runnable</code> which represents the code we want the new thread to start running:</p><pre><code class="language-java hljs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
System.out.println("Hello from a thread!");
}
}).start();
computeFact(<span class="hljs-number">100</span>);
}</code></pre>
<p>If you're feeling clever, you can go one step further with Java's lambda expressions:</p><pre><code class="language-java hljs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-keyword">new</span> Thread(() -> System.out.println("Hello from a thread!")).start();
computeFact(<span class="hljs-number">100</span>);
}</code></pre>
<p>Whether that's more or less <em>easy to understand</em> is up for debate.
<code>Runnable</code> and <code>run</code> never appear at all, so you certainly have to do more research to understand this construction the first time you come across it.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical_Questions_459e04214b5d" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Processes_Threads">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Processes_Threads" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/c9cee8830885f59e75b8782f44026226/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-58">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-58" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-processes-threads-58" class="problems-wrapper" role="group"
aria-labelledby="05-processes-threads-58-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-58" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-58/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="3"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-processes-threads-58-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-58-problem-progress" tabindex="-1">
Processes and threads 2
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-58-problem-progress"></div>
<div class="problem">
<div>
<p>Suppose we run main in this program, which contains bugs:</p>
<pre>
public class Moirai {
public static void main(String[] args) {
Thread clotho = new Thread(new Runnable() {
public void run() { System.out.println("spinning"); };
});
clotho.start();
new Thread(new Runnable() {
public void run() { System.out.println("measuring"); };
}).start();
new Thread(new Runnable() {
public void run() { System.out.println("cutting"); };
});
}
}
</pre>
<p>How many new Thread objects are created?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div id="formulaequationinput_05-processes-threads-58_2_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_05-processes-threads-58_2_1" id="input_05-processes-threads-58_2_1" data-input-id="05-processes-threads-58_2_1" value="" aria-describedby="status_05-processes-threads-58_2_1" size="20"/>
<span class="trailing_text" id="trailing_text_05-processes-threads-58_2_1"/>
<span class="status unanswered" id="status_05-processes-threads-58_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_05-processes-threads-58_2_1" class="answer"/>
<div id="input_05-processes-threads-58_2_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_05-processes-threads-58_solution_1"/>
</div><p>How many new threads are run?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div id="formulaequationinput_05-processes-threads-58_3_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_05-processes-threads-58_3_1" id="input_05-processes-threads-58_3_1" data-input-id="05-processes-threads-58_3_1" value="" aria-describedby="status_05-processes-threads-58_3_1" size="20"/>
<span class="trailing_text" id="trailing_text_05-processes-threads-58_3_1"/>
<span class="status unanswered" id="status_05-processes-threads-58_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_05-processes-threads-58_3_1" class="answer"/>
<div id="input_05-processes-threads-58_3_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_05-processes-threads-58_solution_2"/>
</div><p>What is the maximum number of threads that might be running at the same time?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 3" role="group"><div id="formulaequationinput_05-processes-threads-58_4_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_05-processes-threads-58_4_1" id="input_05-processes-threads-58_4_1" data-input-id="05-processes-threads-58_4_1" value="" aria-describedby="status_05-processes-threads-58_4_1" size="20"/>
<span class="trailing_text" id="trailing_text_05-processes-threads-58_4_1"/>
<span class="status unanswered" id="status_05-processes-threads-58_4_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_05-processes-threads-58_4_1" class="answer"/>
<div id="input_05-processes-threads-58_4_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_05-processes-threads-58_solution_3"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Processes and threads 2" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-processes-threads-58" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-processes-threads-58">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-58-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-58-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-58-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-59">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-59" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-processes-threads-59" class="problems-wrapper" role="group"
aria-labelledby="05-processes-threads-59-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-59" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-59/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-processes-threads-59-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-59-problem-progress" tabindex="-1">
Processes and threads 3
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-processes-threads-59-problem-progress"></div>
<div class="problem">
<div>
<p>Suppose we run main in this program, which demonstrates two common bugs:</p>
<pre>
public class Parcae {
public static void main(String[] args) {
Thread nona = new Thread(new Runnable() {
public void run() { System.out.println("spinning"); };
});
nona.run();
Runnable decima = new Runnable() {
public void run() { System.out.println("measuring"); };
};
decima.run();
// ...
}
}
</pre>
<p>How many new Thread objects are created?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div id="formulaequationinput_05-processes-threads-59_2_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_05-processes-threads-59_2_1" id="input_05-processes-threads-59_2_1" data-input-id="05-processes-threads-59_2_1" value="" aria-describedby="status_05-processes-threads-59_2_1" size="20"/>
<span class="trailing_text" id="trailing_text_05-processes-threads-59_2_1"/>
<span class="status unanswered" id="status_05-processes-threads-59_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_05-processes-threads-59_2_1" class="answer"/>
<div id="input_05-processes-threads-59_2_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_05-processes-threads-59_solution_1"/>
</div><p>How many new threads are run?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div id="formulaequationinput_05-processes-threads-59_3_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_05-processes-threads-59_3_1" id="input_05-processes-threads-59_3_1" data-input-id="05-processes-threads-59_3_1" value="" aria-describedby="status_05-processes-threads-59_3_1" size="20"/>
<span class="trailing_text" id="trailing_text_05-processes-threads-59_3_1"/>
<span class="status unanswered" id="status_05-processes-threads-59_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_05-processes-threads-59_3_1" class="answer"/>
<div id="input_05-processes-threads-59_3_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_05-processes-threads-59_solution_2"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Processes and threads 3" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-processes-threads-59" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-processes-threads-59">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-59-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-59-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-processes-threads-59-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical-shared-memory" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Shared Memory</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_54061550e068">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_54061550e068" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<h2 id="shared_memory_example">Shared Memory Example</h2>
<div data-outline="shared_memory_example">
<p>Let's look at an example of a shared memory system. The point of this example is to show that concurrent programming is hard, because it can have subtle bugs.</p>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/29480f47a80fd8fe08acc25c16f78030/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/05-shared-memory-bank-account.png" alt="shared memory model for bank accounts" width="500"></div>
<p>Imagine that a bank has cash machines that use a shared memory model, so all the cash machines can read and write the same account objects in memory.</p>
<div class="clearfix"></div>
<p>To illustrate what can go wrong, let's simplify the bank down to a single account, with a dollar balance stored in the <code>balance</code> variable, and two operations <code>deposit</code> and <code>withdraw</code> that simply add or remove a dollar:</p><pre><code class="language-java hljs"><span class="hljs-comment">// suppose all the cash machines share a single bank account</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> balance = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deposit</span><span class="hljs-params">()</span> </span>{
balance = balance + <span class="hljs-number">1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">()</span> </span>{
balance = balance - <span class="hljs-number">1</span>;
}</code></pre>
<p>Customers use the cash machines to do transactions like this:</p><pre><code class="language-java hljs">deposit(); <span class="hljs-comment">// put a dollar in</span>
withdraw(); <span class="hljs-comment">// take it back out</span></code></pre>
<p>In this simple example, every transaction is just a one dollar deposit followed by a one-dollar withdrawal, so it should leave the balance in the account unchanged. Throughout the day, each cash machine in our network is processing a sequence of deposit/withdraw transactions.</p><pre><code class="language-java hljs"><span class="hljs-comment">// each ATM does a bunch of transactions that</span>
<span class="hljs-comment">// modify balance, but leave it unchanged afterward</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cashMachine</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < TRANSACTIONS_PER_MACHINE; ++i) {
deposit(); <span class="hljs-comment">// put a dollar in</span>
withdraw(); <span class="hljs-comment">// take it back out</span>
}
}</code></pre>
<p>So at the end of the day, regardless of how many cash machines were running, or how many transactions we processed, we should expect the account balance to still be 0.</p>
<p>But if we run this code, we discover frequently that the balance at the end of the day is <em>not</em> 0. If more than one <code>cashMachine()</code> call is running at the same time — say, on separate processors in the same computer — then <code>balance</code> may not be zero at the end of the day. Why not?</p>
</div>
<script>
/* style timeline tables */
window.onHandoutDidRender = function() {
$('.timeline table').addClass('table-condensed');
$('.timeline table').css('width', 'inherit');
$('.timeline table thead:not(:has(th:not(:empty)))').remove();
}
</script>
<h2 id="interleaving">Interleaving</h2>
<div data-outline="interleaving">
<p>Here's one thing that can happen. Suppose two cash machines, A and B, are both working on a deposit at the same time. Here's how the <code>deposit()</code> step typically breaks down into low-level processor instructions:</p>
<div class="timeline">
<table class="table table-condensed" style="width: inherit;">
<tbody>
<tr>
<td>get balance (balance=0)</td>
</tr>
<tr>
<td>add 1</td>
</tr>
<tr>
<td>write back the result (balance=1)</td>
</tr>
</tbody>
</table>
</div>
<p>When A and B are running concurrently, these low-level instructions interleave with each other (some might even be simultaneous in some sense, but let's just worry about interleaving for now):</p>
<div class="timeline">
<table class="table table-condensed" style="width: inherit;">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>A get balance (balance=0)</td>
<td></td>
</tr>
<tr>
<td>A add 1</td>
<td></td>
</tr>
<tr>
<td>A write back the result (balance=1)</td>
<td></td>
</tr>
<tr>
<td></td>
<td>B get balance (balance=1)</td>
</tr>
<tr>
<td></td>
<td>B add 1</td>
</tr>
<tr>
<td></td>
<td>B write back the result (balance=2)</td>
</tr>
</tbody>
</table>
</div>
<p>This interleaving is fine — we end up with balance 2, so both A and B successfully put in a dollar. But what if the interleaving looked like this:</p>
<div class="timeline">
<table class="table table-condensed" style="width: inherit;">
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>A get balance (balance=0)</td>
<td></td>
</tr>
<tr>
<td></td>
<td>B get balance (balance=0)</td>
</tr>
<tr>
<td>A add 1</td>
<td></td>
</tr>
<tr>
<td></td>
<td>B add 1</td>
</tr>
<tr>
<td>A write back the result (balance=1)</td>
<td></td>
</tr>
<tr>
<td></td>
<td>B write back the result (balance=1)</td>
</tr>
</tbody>
</table>
</div>
<p>The balance is now 1 — A's dollar was lost! A and B both read the balance at the same time, computed separate final balances, and then raced to store back the new balance — which failed to take the other's deposit into account.</p>
</div>
<h2 id="race_condition">Race Condition</h2>
<div data-outline="race_condition">
<p>This is an example of a <strong>race condition</strong>. A race condition means that the correctness of the program (the satisfaction of postconditions and invariants) depends on the relative timing of events in concurrent computations A and B. When this happens, we say “A is in a race with B.”</p>
<p>Some interleavings of events may be OK, in the sense that they are consistent with what a single, nonconcurrent process would produce, but other interleavings produce wrong answers — violating postconditions or invariants.</p>
</div>
<h2 id="tweaking_the_code_wont_help">Tweaking the Code Won't Help</h2>
<div data-outline="tweaking_the_code_wont_help">
<p>All these versions of the bank-account code exhibit the same race condition:</p><pre><code class="language-java hljs"><span class="hljs-comment">// version 1</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deposit</span><span class="hljs-params">()</span> </span>{
balance = balance + <span class="hljs-number">1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">()</span> </span>{
balance = balance - <span class="hljs-number">1</span>;
}</code></pre><pre><code class="language-java hljs"><span class="hljs-comment">// version 2</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deposit</span><span class="hljs-params">()</span> </span>{
balance += <span class="hljs-number">1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">()</span> </span>{
balance -= <span class="hljs-number">1</span>;
}</code></pre><pre><code class="language-java hljs"><span class="hljs-comment">// version 3</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deposit</span><span class="hljs-params">()</span> </span>{
++balance;
}
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">()</span> </span>{
--balance;
}</code></pre>
<p>You can't tell just from looking at Java code how the processor is going to execute it. You can't tell what the indivisible operations — the atomic operations — will be. It isn't atomic just because it's one line of Java. It doesn't touch balance only once just because the balance identifier occurs only once in the line. The Java compiler, and in fact the processor itself, makes no commitments about what low-level operations it will generate from your code. In fact, a typical modern Java compiler produces exactly the same code for all three of these versions!</p>
<p>The key lesson is that you can't tell by looking at an expression whether it will be safe from race conditions.</p>
<div class="handout-solo alert alert-warning">
<p>Read: <strong><a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html" class="alert-link">Thread Interference</a></strong> (just 1 page)</p>
</div>
</div>
<h2 id="reordering">Reordering</h2>
<div data-outline="reordering">
<p>It's even worse than that, in fact. The race condition on the bank account balance can be explained in terms of different interleavings of sequential operations on different processors. But in fact, when you're using multiple variables and multiple processors, you can't even count on changes to those variables appearing in the same order.</p>
<p>Here's an example. Note that it uses a loop that continuously checks for a concurrent condition; this is called <a href="https://en.wikipedia.org/wiki/Busy_waiting">busy waiting</a> and it is not a good pattern. In this case, the code is also broken:</p><pre><code class="language-java hljs"><span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> ready = <span class="hljs-keyword">false</span>;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> answer = <span class="hljs-number">0</span>;
<span class="hljs-comment">// computeAnswer runs in one thread</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">computeAnswer</span><span class="hljs-params">()</span> </span>{
answer = <span class="hljs-number">42</span>;
ready = <span class="hljs-keyword">true</span>;
}
<span class="hljs-comment">// useAnswer runs in a different thread</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">useAnswer</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">while</span> (!ready) {
Thread.yield();
}
<span class="hljs-keyword">if</span> (answer == <span class="hljs-number">0</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"answer wasn't ready!"</span>);
}</code></pre>
<p>We have two methods that are being run in different threads. <code>computeAnswer</code> does a long calculation, finally coming up with the answer 42, which it puts in the answer variable. Then it sets the <code>ready</code> variable to true, in order to signal to the method running in the other thread, <code>useAnswer</code>, that the answer is ready for it to use. Looking at the code, <code>answer</code> is set before <code>ready</code> is set, so once <code>useAnswer</code> sees <code>ready</code> as true, then it seems reasonable that it can assume that the <code>answer</code> will be 42, right? Not so.</p>
<p>The problem is that modern compilers and processors do a lot of things to make the code fast. One of those things is making temporary copies of variables like answer and ready in faster storage (registers or caches on a processor), and working with them temporarily before eventually storing them back to their official location in memory. The storeback may occur in a different order than the variables were manipulated in your code. Here's what might be going on under the covers (but expressed in Java syntax to make it clear). The processor is effectively creating two temporary variables, <code>tmpr</code> and <code>tmpa</code>, to manipulate the fields <code>ready</code> and <code>answer</code>:</p><pre><code class="language-java hljs"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">computeAnswer</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">boolean</span> tmpr = ready;
<span class="hljs-keyword">int</span> tmpa = answer;
tmpa = <span class="hljs-number">42</span>;
tmpr = <span class="hljs-keyword">true</span>;
ready = tmpr;
<span class="hljs-comment">// <-- what happens if useAnswer() interleaves here?</span>
<span class="hljs-comment">// ready is set, but answer isn't.</span>
answer = tmpa;
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical_Questions_fb2f29f0978b" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Race_Conditions">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Race_Conditions" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/c9cee8830885f59e75b8782f44026226/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-1">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-1" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-interleaving-1" class="problems-wrapper" role="group"
aria-labelledby="05-interleaving-1-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-1" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-1/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-interleaving-1-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-1-problem-progress" tabindex="-1">
Interleaving 1
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-1-problem-progress"></div>
<div class="problem">
<div>
<p>Here&#8217;s the buggy code from our earlier exercise where two new threads are started:</p>
<pre>
public class Moirai {
public static void main(String[] args) {
Thread clotho = new Thread(new Runnable() {
public void run() { System.out.println("spinning"); };
});
clotho.start();
new Thread(new Runnable() {
public void run() { System.out.println("measuring"); };
}).start();
new Thread(new Runnable() {
public void run() { System.out.println("cutting"); };
});
// bug! never started
}
}
</pre>
<p>Which of the following are possible outputs from this program:</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_05-interleaving-1_2_1">
<fieldset aria-describedby="status_05-interleaving-1_2_1">
<div class="field">
<input type="checkbox" name="input_05-interleaving-1_2_1[]" id="input_05-interleaving-1_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="05-interleaving-1_2_1-choice_0-label" for="input_05-interleaving-1_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-1_2_1"> spinning<br/>measuring<br/>cutting
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-1_2_1[]" id="input_05-interleaving-1_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="05-interleaving-1_2_1-choice_1-label" for="input_05-interleaving-1_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-1_2_1"> spinning<br/>measuring
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-1_2_1[]" id="input_05-interleaving-1_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="05-interleaving-1_2_1-choice_2-label" for="input_05-interleaving-1_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-1_2_1"> measuring<br/>spinning<br/>cutting
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-1_2_1[]" id="input_05-interleaving-1_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="05-interleaving-1_2_1-choice_3-label" for="input_05-interleaving-1_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-1_2_1"> measuring<br/>spinning
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-1_2_1[]" id="input_05-interleaving-1_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="05-interleaving-1_2_1-choice_4-label" for="input_05-interleaving-1_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-1_2_1"> spinning
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-1_2_1[]" id="input_05-interleaving-1_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="05-interleaving-1_2_1-choice_5-label" for="input_05-interleaving-1_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-1_2_1"> measuring
</label>
</div>
<span id="answer_05-interleaving-1_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_05-interleaving-1_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_05-interleaving-1_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Interleaving 1" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-interleaving-1" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-interleaving-1">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-interleaving-1-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-interleaving-1-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-interleaving-1-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-2">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-2" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-interleaving-2" class="problems-wrapper" role="group"
aria-labelledby="05-interleaving-2-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-2" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-2/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-interleaving-2-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-2-problem-progress" tabindex="-1">
Interleaving 2
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-interleaving-2-problem-progress"></div>
<div class="problem">
<div>
<p>Here&#8217;s the buggy code from our earlier exercise where no new threads are started:</p>
<pre>
public class Parcae {
public static void main(String[] args) {
Thread nona = new Thread(new Runnable() {
public void run() { System.out.println("spinning"); };
});
nona.run(); // bug! called run instead of start
Runnable decima = new Runnable() {
public void run() { System.out.println("measuring"); };
};
decima.run(); // bug? maybe meant to create a Thread?
// ...
}
}
</pre>
<p>Which of the following are possible outputs from this program:</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_05-interleaving-2_2_1">
<fieldset aria-describedby="status_05-interleaving-2_2_1">
<div class="field">
<input type="checkbox" name="input_05-interleaving-2_2_1[]" id="input_05-interleaving-2_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="05-interleaving-2_2_1-choice_0-label" for="input_05-interleaving-2_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-2_2_1"> spinning<br/>measuring
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-2_2_1[]" id="input_05-interleaving-2_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="05-interleaving-2_2_1-choice_1-label" for="input_05-interleaving-2_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-2_2_1"> measuring<br/>spinning
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-2_2_1[]" id="input_05-interleaving-2_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="05-interleaving-2_2_1-choice_2-label" for="input_05-interleaving-2_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-2_2_1"> spinning
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-interleaving-2_2_1[]" id="input_05-interleaving-2_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="05-interleaving-2_2_1-choice_3-label" for="input_05-interleaving-2_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_05-interleaving-2_2_1"> measuring
</label>
</div>
<span id="answer_05-interleaving-2_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_05-interleaving-2_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_05-interleaving-2_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Interleaving 2" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-interleaving-2" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-interleaving-2">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-interleaving-2-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-interleaving-2-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-interleaving-2-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-3" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-58">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-58" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-race-conditions-58" class="problems-wrapper" role="group"
aria-labelledby="05-race-conditions-58-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-58" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-58/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-race-conditions-58-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-58-problem-progress" tabindex="-1">
Race conditions 1
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-58-problem-progress"></div>
<div class="problem">
<div>
<p>Consider the following code:</p>
<pre>
private static int x = 1;
public static void methodA() {
x *= 2;
x *= 3;
}
public static void methodB() {
x *= 5;
}
</pre>
<p>Suppose methodA and methodB run <b>sequentially</b>, i.e. first one and then the other. What is the final value of x?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div id="formulaequationinput_05-race-conditions-58_2_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_05-race-conditions-58_2_1" id="input_05-race-conditions-58_2_1" data-input-id="05-race-conditions-58_2_1" value="" aria-describedby="status_05-race-conditions-58_2_1" size="20"/>
<span class="trailing_text" id="trailing_text_05-race-conditions-58_2_1"/>
<span class="status unanswered" id="status_05-race-conditions-58_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_05-race-conditions-58_2_1" class="answer"/>
<div id="input_05-race-conditions-58_2_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_05-race-conditions-58_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Race conditions 1" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-race-conditions-58" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-race-conditions-58">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-race-conditions-58-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-race-conditions-58-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-race-conditions-58-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-4" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-59">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-59" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-race-conditions-59" class="problems-wrapper" role="group"
aria-labelledby="05-race-conditions-59-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-59" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-59/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-race-conditions-59-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-59-problem-progress" tabindex="-1">
Race conditions 2
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-race-conditions-59-problem-progress"></div>
<div class="problem">
<div>
<p>Now suppose methodA and methodB run concurrently, so that their instructions might interleave arbitrarily. Which of the following are possible final values of x?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_05-race-conditions-59_2_1">
<fieldset aria-describedby="status_05-race-conditions-59_2_1">
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="05-race-conditions-59_2_1-choice_0-label" for="input_05-race-conditions-59_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="05-race-conditions-59_2_1-choice_1-label" for="input_05-race-conditions-59_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 2
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="05-race-conditions-59_2_1-choice_2-label" for="input_05-race-conditions-59_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 5
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="05-race-conditions-59_2_1-choice_3-label" for="input_05-race-conditions-59_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 6
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="05-race-conditions-59_2_1-choice_4-label" for="input_05-race-conditions-59_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 10
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="05-race-conditions-59_2_1-choice_5-label" for="input_05-race-conditions-59_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 30
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-race-conditions-59_2_1[]" id="input_05-race-conditions-59_2_1_choice_6" class="field-input input-checkbox" value="choice_6"/><label id="05-race-conditions-59_2_1-choice_6-label" for="input_05-race-conditions-59_2_1_choice_6" class="response-label field-label label-inline" aria-describedby="status_05-race-conditions-59_2_1"> 150
</label>
</div>
<span id="answer_05-race-conditions-59_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_05-race-conditions-59_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_05-race-conditions-59_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Race conditions 2" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-race-conditions-59" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-race-conditions-59">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-race-conditions-59-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-race-conditions-59-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-race-conditions-59-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical-message-passing" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Message Passing</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_1f9920bdd71e">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_1f9920bdd71e" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<h2 id="message_passing_example">Message Passing Example</h2>
<div data-outline="message_passing_example">
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/7fcc578cc783d010176f77517cffe612/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/05-message-passing-bank-account.png" alt="message passing bank account example" width="500"></div>
<p>Now let's look at the message-passing approach to our bank account example.</p>
<p>Now not only are the cash machine modules, but the accounts are modules, too. Modules interact by sending messages to each other. Incoming requests are placed in a queue to be handled one at a time. The sender doesn't stop working while waiting for an answer to its request. It handles more requests from its own queue. The reply to its request eventually comes back as another message.</p>
<p>Unfortunately, message passing doesn't eliminate the possibility of race conditions. Suppose each account supports <code>get-balance</code> and <code>withdraw</code> operations, with corresponding messages. Two users, at cash machines A and B, are both trying to withdraw a dollar from the same account. They check the balance first to make sure they never withdraw more than the account holds, because overdrafts trigger big bank penalties:</p><pre><code class="hljs cpp">get-balance
<span class="hljs-keyword">if</span> balance >= <span class="hljs-number">1</span> then withdraw <span class="hljs-number">1</span></code></pre>
<p>The problem is again interleaving, but this time interleaving of the <em>messages</em> sent to the bank account, rather than the <em>instructions</em> executed by A and B. If the account starts with a dollar in it, then what interleaving of messages will fool A and B into thinking they can both withdraw a dollar, thereby overdrawing the account?</p>
<p>One lesson here is that you need to carefully choose the operations of a message-passing model. <code>withdraw-if-sufficient-funds</code> would be a better operation than just <code>withdraw</code>.</p>
</div>
<h2 id="concurrency_is_hard_to_test_and_debug">Concurrency is Hard to Test and Debug</h2>
<div data-outline="concurrency_is_hard_to_test_and_debug">
<p>If we haven't persuaded you that concurrency is tricky, here's the worst of it. It's very hard to discover race conditions using testing. And even once a test has found a bug, it may be very hard to localize it to the part of the program causing it.</p>
<p>Concurrency bugs exhibit very poor reproducibility. It's hard to make them happen the same way twice. Interleaving of instructions or messages depends on the relative timing of events that are strongly influenced by the environment. Delays can be caused by other running programs, other network traffic, operating system scheduling decisions, variations in processor clock speed, etc. Each time you run a program containing a race condition, you may get different behavior. </p>
<p>These kinds of bugs are <em>heisenbugs</em>, which are nondeterministic and hard to reproduce, as opposed to a <em>bohrbug</em>, which shows up repeatedly whenever you look at it. Almost all bugs in sequential programming are bohrbugs.</p>
<p>A heisenbug may even disappear when you try to look at it with <code>println</code> or <code>debugger</code>! The reason is that printing and debugging are so much slower than other operations, often 100-1000x slower, that they dramatically change the timing of operations, and the interleaving. So inserting a simple print statement into the cashMachine():</p><pre><code class="language-java hljs"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cashMachine</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < TRANSACTIONS_PER_MACHINE; ++i) {
deposit(); <span class="hljs-comment">// put a dollar in</span>
withdraw(); <span class="hljs-comment">// take it back out</span>
System.out.println(balance); <span class="hljs-comment">// makes the bug disappear!</span>
}
}</code></pre>
<p>…and suddenly the balance is always 0, as desired, and the bug appears to disappear. But it's only masked, not truly fixed. A change in timing somewhere else in the program may suddenly make the bug come back.</p>
<p>Concurrency is hard to get right. Part of the point of this reading is to scare you a bit. Over the next several readings, we'll see principled ways to design concurrent programs so that they are safer from these kinds of bugs.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@vertical_Questions_7701ac88ed5f" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Testing_Concurrency">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@Testing_Concurrency" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/c9cee8830885f59e75b8782f44026226/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-testing-concurrency-59">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-testing-concurrency-59" data-graded="True" data-has-score="True" data-runtime-version="1" data-block-type="problem" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_05-testing-concurrency-59" class="problems-wrapper" role="group"
aria-labelledby="05-testing-concurrency-59-problem-title"
data-problem-id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-testing-concurrency-59" data-url="/courses/course-v1:MITx+6.005.2x+1T2017/xblock/block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-testing-concurrency-59/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="05-testing-concurrency-59-problem-title" aria-describedby="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-testing-concurrency-59-problem-progress" tabindex="-1">
Testing concurrency
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.2x+1T2017+type@problem+block@05-testing-concurrency-59-problem-progress"></div>
<div class="problem">
<div>
<p>You're running a JUnit test suite (for code written by somebody else), and some of the tests are failing. You add System.out.println statements to the one method called by all the failing test cases, in order to display some of its local variables, and the test cases suddenly start passing. Which of the following are likely reasons for this?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_05-testing-concurrency-59_2_1">
<fieldset aria-describedby="status_05-testing-concurrency-59_2_1">
<div class="field">
<input type="checkbox" name="input_05-testing-concurrency-59_2_1[]" id="input_05-testing-concurrency-59_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="05-testing-concurrency-59_2_1-choice_0-label" for="input_05-testing-concurrency-59_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_05-testing-concurrency-59_2_1"> The method is calling a random number generator (i.e., Math.random()), so sometimes its tests will pass by random chance.
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-testing-concurrency-59_2_1[]" id="input_05-testing-concurrency-59_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="05-testing-concurrency-59_2_1-choice_1-label" for="input_05-testing-concurrency-59_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_05-testing-concurrency-59_2_1"> The method has code running concurrently.
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-testing-concurrency-59_2_1[]" id="input_05-testing-concurrency-59_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="05-testing-concurrency-59_2_1-choice_2-label" for="input_05-testing-concurrency-59_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_05-testing-concurrency-59_2_1"> The method has a race condition.
</label>
</div>
<div class="field">
<input type="checkbox" name="input_05-testing-concurrency-59_2_1[]" id="input_05-testing-concurrency-59_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="05-testing-concurrency-59_2_1-choice_3-label" for="input_05-testing-concurrency-59_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_05-testing-concurrency-59_2_1"> The method's preconditions are not being met by the test cases.
</label>
</div>
<span id="answer_05-testing-concurrency-59_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_05-testing-concurrency-59_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_05-testing-concurrency-59_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="Testing concurrency" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_05-testing-concurrency-59" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_05-testing-concurrency-59">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-testing-concurrency-59-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-testing-concurrency-59-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="05-testing-concurrency-59-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@vertical+block@Reading_5_Summary" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="vertical" data-init="VerticalStudentView" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<h2 class="hd hd-2 unit-title">Reading 5 Summary</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_4d7f368259ed">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-request-token="07f1d82ae99c11efb7c60e0e3c45b88f" data-usage-id="block-v1:MITx+6.005.2x+1T2017+type@html+block@html_4d7f368259ed" data-graded="True" data-has-score="False" data-runtime-version="1" data-block-type="html" data-init="XBlockToXModuleShim" data-course-id="course-v1:MITx+6.005.2x+1T2017" data-runtime-class="LmsRuntime">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/b2188f0a95a7a9062748278f7d5a584f/asset-v1:MITx+6.005.2x+1T2017+type@asset+block/syntax-highlighting.css" rel="stylesheet" type="text/css" />
<h2 id="summary">Summary</h2>
<div data-outline="summary">
<ul>
<li>Concurrency: multiple computations running simultaneously</li>
<li>Shared-memory & message-passing paradigms</li>
<li>Processes & threads
<ul>
<li>Process is like a virtual computer; thread is like a virtual processor</li>
</ul>
</li>
<li>Race conditions
<ul>
<li>When correctness of result (postconditions and invariants) depends on the relative timing of events</li>
</ul>
</li>
</ul>
<p>These ideas connect to our three key properties of good software mostly in bad ways. Concurrency is necessary but it causes serious problems for correctness. We'll work on fixing those problems in the next few readings.</p>
<ul>
<li>
<p><strong>Safe from bugs.</strong> Concurrency bugs are some of the hardest bugs to find and fix, and require careful design to avoid.</p>
</li>
<li>
<p><strong>Easy to understand.</strong> Predicting how concurrent code might interleave with other concurrent code is very hard for programmers to do. It's best to design your code in such a way that programmers don't have to think about interleaving at all. </p>
</li>
<li>
<p><strong>Ready for change.</strong> Not particularly relevant here.</p>
</li>
</ul>
</div>
<div class="license">This reading was collaboratively authored with contributions from: Saman Amarasinghe, Adam Chlipala, Srini Devadas, Michael Ernst, Max Goldman, John Guttag, Daniel Jackson, Rob Miller, Martin Rinard, and Armando Solar-Lezama. This work is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>.</div>
</div>
</div>
</div>
</div>