CS61B Lecture #36. DSIJ, Chapter 10, HFJ, pp Today: A Brief Side Trip: Enumeration types.

Similar documents
Side Trip into Java: Enumeration Types. CS61B Lecture #36. Making Enumerals Available Elsewhere. Enum Types in Java. import static checkers.piece.

CS61B Lecture #35. [The Lecture #32 notes covered lectures #33 and #34.] Today: Enumerated types, backtracking searches, game trees.

Java Threads. COMP 585 Noteset #2 1

Multiple Inheritance. Computer object can be viewed as

RACE CONDITIONS AND SYNCHRONIZATION

Threads and Parallelism in Java

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Concurrent Programming using Threads

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CmpSci 187: Programming with Data Structures Spring 2015

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Java Threads. Written by John Bell for CS 342, Spring 2018

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Principles of Software Construction: Concurrency, Part 2

THREADS & CONCURRENCY

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

CS 160: Interactive Programming

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

The New Java Technology Memory Model

Java Programming Lecture 23

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

Info 408 Distributed Applications Programming Exercise sheet nb. 4

CMSC 132: Object-Oriented Programming II. Threads in Java

THREADS AND CONCURRENCY

Threads, Concurrency, and Parallelism

1 Multiple Threads of Control

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Advances in Programming Languages

Java Threads and intrinsic locks

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Synchronization in Java

Speculative Parallelism. Java & Object-Oriented Programming. Reading Assignment

Today: Synchronization. Recap: Synchronization

About this exam review

Programming Language Concepts: Lecture 11

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

CMSC 330: Organization of Programming Languages

Advanced Concepts of Programming

CS11 Java. Fall Lecture 7

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

CS 351 Design of Large Programs Threads and Concurrency

What is a thread anyway?

Pace University. Fundamental Concepts of CS121 1

This is a talk given by me to the Northwest C++ Users Group on May 19, 2010.

Review sheet for Final Exam (List of objectives for this course)

Only one thread can own a specific monitor

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Introduction to Programming Using Java (98-388)

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Introduction to Java Threads

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

CS61B Lecture #13: Packages, Access, Etc.

Program Graph. Lecture 25: Parallelism & Concurrency. Performance. What does it mean?

Java Threads. Introduction to Java Threads

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

6.001 Notes: Section 17.5

Exercise Session Week 8

7. MULTITHREDED PROGRAMMING

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Java Overview An introduction to the Java Programming Language

Multithreading and Interactive Programs

Problems with Concurrency. February 19, 2014

Modern Programming Languages. Lecture Java Programming Language. An Introduction

CS180 Review. Recitation Week 15

Exercise Session Week 8

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Programmazione di sistemi multicore

Designing Robust Classes

JAVA BASICS II. Example: FIFO

Java s Implementation of Concurrency, and how to use it in our applications.

CS61B Lecture #13: Packages, Access, Etc.

Animation Part 2: MoveableShape interface & Multithreading

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

APCS Semester #1 Final Exam Practice Problems

CS 556 Distributed Systems

Multithreaded Programming

CMSC 330: Organization of Programming Languages

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430

Prelim 2. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer

Chapter 6 Introduction to Defining Classes

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Page 1. Goals for Today" Atomic Read-Modify-Write instructions" Examples of Read-Modify-Write "

THREADS & CONCURRENCY

CST242 Concurrency Page 1

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Transcription:

CS61B Lecture #36 Today: A Brief Side Trip: Enumeration types. DSIJ, Chapter 10, HFJ, pp. 489 516. Threads Communication between threads Synchronization Mailboxes Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 1

Side Trip into Java: Enumeration Types Problem: Needatypetorepresentsomethingthathasafew,named, discrete values. In the purest form, the only necessary operations are == and!=; the only property of a value of the type is that it differs from all others. In older versions of Java, used named integer constants: interface Pieces { int BLACK PIECE = 0, BLACK KING = 1, WHITE PIECE = 2, WHITE KING = 3, EMPTY = 4; // Fields in interfaces are static final. CandC++provideenumerationtypesasashorthand,withsyntaxlike this: enum Piece { BLACK PIECE, BLACK KING, WHITE PIECE, WHITE KING, EMPTY ; But since all these values are basically ints, accidents can happen. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 2

Enum Types in Java New version of Java allows syntax like that of C or C++, but with more guarantees: public enum Piece { BLACK PIECE, BLACK KING, WHITE PIECE, WHITE KING, EMPTY Defines Piece as a new reference type, a special kind of class type. The names BLACK PIECE, etc., are static, final enumeration constants (or enumerals) of type PIECE. They are automatically initialized, and are the only values of the enumeration type that exist (illegal to use new to create an enum value.) Can safely use ==, and also switch statements: boolean isking(piece p) { switch (p) { case BLACK KING: case WHITE KING: return true; default: return false; Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 3

Making Enumerals Available Elsewhere EnumeralslikeBLACK PIECEarestaticmembersofaclass,notclasses. Therefore, unlike C or C++, their declarations are not automatically visible outside the enumeration class definition. So, in other classes, must write Piece.BLACK_PIECE, which can get annoying. However, with version 1.5, Java has static imports: to import all static definitions of class checkers.piece(including enumerals), you write import static checkers.piece.*; among the import clauses. Alas, cannot use this for enum classes in the anonymous package. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 4

Operations on Enum Types Order of declaration of enumeration constants significant:.ordinal() gives the position(numbering from 0) of an enumeration value. Thus, Piece.BLACK KING.ordinal() is 1. The array Piece.values() gives all the possible values of the type. Thus, you can write: for (Piece p : Piece.values()) System.out.printf("Piece value #%d is %s%n", p.ordinal(), p); The static function Piece.valueOf converts a String into a value of type Piece. So Piece.valueOf("EMPTY") == EMPTY. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 5

Fancy Enum Types Enums are classes. You can define all the extra fields, methods, and constructors you want. Constructors are used only in creating enumeration constants. The constructor arguments follow the constant name: enum Piece { BLACK PIECE(BLACK, false, "b"), BLACK KING(BLACK, true, "B"), WHITE PIECE(WHITE, false, "w"), WHITE KING(WHITE, true, "W"), EMPTY(null, false, " "); private final Side color; private final boolean isking; private final String textname; Piece(Side color, boolean isking, String textname) { this.color = color; this.isking = isking; this.textname = textname; Side color() { return color; boolean isking() { return isking; String textname() { return textname; Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 6

Threads So far, all our programs consist of single sequence of instructions. Each such sequence is called a thread (for thread of control ) in Java. Java supports programs containing multiple threads, which (conceptually) run concurrently. Actually, on a uniprocessor, only one thread at a time actually runs, while others wait, but this is largely invisible. To allow program access to threads, Java provides the type Thread in java.lang. Each Thread contains information about, and controls, one thread. Simultaneous access to data from two threads can cause chaos, so are also constructs for controlled communication, allowing threads to lock objects, to wait to be notified of events, and to interrupt other threads. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 7

But Why? Typical Java programs always have > 1 thread: besides the main program, others clean up garbage objects, receive signals, update the display, other stuff. When programs deal with asynchronous events, is sometimes convenient to organize into subprograms, one for each independent, related sequence of events. Threads allow us to insulate one such subprogram from another. GUIs often organized like this: application is doing some computation or I/O, another thread waits for mouse clicks (like Stop ), another pays attention to updating the screen as needed. Large servers like search engines may be organized this way, with one thread per request. And, of course, sometimes we do have a real multiprocessor. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 8

Java Mechanics To specify the actions walking and chewing gum : class Chewer1 implements Runnable { public void run() { while (true) ChewGum(); class Walker1 implements Runnable { public void run() { while (true) Walk(); // Walk and chew gum Thread chomp = new Thread(new Chewer1()); Thread clomp = new Thread(new Walker1()); chomp.start(); clomp.start(); Concise Alternative (uses fact that Thread implements Runnable): class Chewer2 extends Thread { public void run() { while (true) ChewGum(); class Walker2 extends Thread { public void run() { while (true) Walk(); Thread chomp = new Chewer2(), clomp = new Walker2(); chomp.start(); clomp.start(); Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 9

Avoiding Interference When one thread has data for another, one must wait for the other to be ready. Likewise, if two threads use the same data structure, generally only one should modify it at a time; other must wait. E.g., what would happen if two threads simultaneously inserted an item into a linked list at the same point in the list? A: Both could conceivably execute p.next = new ListCell(x, p.next); with the same values of p and p.next; one insertion is lost. Can arrange for only one thread at a time to execute a method on a particular object with either of the following equivalent definitions: void f(...) { synchronized (this) { body of f synchronized void f(...) { body of f Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 10

Communicating the Hard Way Communicating data is tricky: the faster party must wait for the slower. Obvious approaches for sending data from thread to thread don t work: class DataExchanger { Object value = null; Object receive() { Object r; r = null; while (r == null) { r = value; value = null; return r; void deposit(object data) { while (value!= null) { value = data; DataExchanger exchanger = new DataExchanger(); -------------------------------- // thread1 sends to thread2 with exchanger.deposit("hello!"); -------------------------------- // thread2 receives from thread1 with msg = (String) exchanger.receive(); BAD: One thread can monopolize machine while waiting; two threads executing deposit or receive simultaneously cause chaos. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 11

Primitive Java Facilities wait method on Object makes thread wait (not using processor) until notified by notifyall, unlocking the Object while it waits. Example, ucb.util.mailbox has something like this (simplified): interface Mailbox { void deposit(object msg) throws InterruptedException; Object receive() throws InterruptedException; class QueuedMailbox implements Mailbox { private List<Object> queue = new LinkedList<Object>(); public synchronized void deposit(object msg) { queue.add(msg); this.notifyall(); // Wake any waiting receivers public synchronized Object receive() throws InterruptedException { while (queue.isempty()) wait(); return queue.remove(0); Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 12

Message-Passing Style Use of Java primitives very error-prone. Wait until CS162. Mailboxes are higher-level, and allow the following program structure: information flow through Mailbox #1 Player #1 deposit receive Mailbox #1 Mailbox #2 receive deposit Player #2 information flow through Mailbox #2 Where each Player is a thread that looks like this: while (! gameover()) { if (mymove()) outbox.deposit(computemymove(lastmove)); else lastmove = inbox.receive(); Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 13

More Concurrency Previous example can be done other ways, but mechanism is very flexible. E.g., suppose you want to think during opponent s move: while (!gameover()) { if (mymove()) outbox.deposit(computemymove(lastmove)); else { do { thinkaheadalittle(); lastmove = inbox.receiveifpossible(); while (lastmove == null); receiveifpossible(written receive(0) in our actual package) doesn t wait; returns null if no message yet, perhaps like this: public synchronized Object receiveifpossible() throws InterruptedException { if (queue.isempty()) return null; return queue.remove(0); Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 14

Coroutines A coroutine is a kind of synchronous thread that explicitly hands off control to other coroutines so that only one executes at a time, like Python generators. Can get similar effect with threads and mailboxes. Example: recursive inorder tree iterator: class TreeIterator extends Thread { Tree root; Mailbox r; TreeIterator(Tree T, Mailbox r) { this.root = T; this.dest = r; public void run() { traverse(root); r.deposit(end marker); void traverse(tree t) { if (t == null) return; traverse(t.left); r.deposit(t.label); traverse(t.right); void treeprocessor(tree T) { Mailbox m = new QueuedMailbox(); new TreeIterator(T, m).start(); while (true) { Object x = m.receive(); if (x is end marker) break; do something with x; Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 15

Use In GUIs Jave runtime library uses a special thread that does nothing but wait for events like mouse clicks, pressed keys, mouse movement, etc. You can designate an object of your choice as a listener; which means that Java s event thread calls a method of that object whenever an event occurs. As a result, your program can do work while the GUI continues to respond to buttons, menus, etc. Another special thread does all the drawing. You don t have to be awarewhen this takes place; just ask that the threadwake up whenever you change something. Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 16

Highlights of a GUI Component /** A widget that draws multi-colored lines indicated by mouse. */ class Lines extends JComponent implements MouseListener { private List<Point> lines = new ArrayList<Point>(); Lines() { // Main thread calls this to create one setpreferredsize(new Dimension(400, 400)); addmouselistener(this); public synchronized void paintcomponent(graphics g) { // Paint thread g.setcolor(color.white); g.fillrect(0, 0, 400, 400); int x, y; x = y = 200; Color c = Color.black; for (Point p : lines) g.setcolor(c); c = choosenextcolor(c); g.drawline(x, y, p.x, p.y); x = p.x; y = p.y; public synchronized void mouseclicked(mouseevent e) // Event thread { lines.add(new Point(e.getX(), e.gety())); repaint();... Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 17

Interrupts An interrupt is an event that disrupts the normal flow of control of a program. In many systems, interrupts can be totally asynchronous, occurring at arbitrary points in a program, the Java developers considered this unwise; arranged that interrupts would occur only at controlled points. In Java programs, one thread can interrupt another to inform it that something unusual needs attention: otherthread.interrupt(); But otherthread does not receive the interrupt until it waits: methods wait,sleep (wait for a period of time), join (wait for thread to terminate), and mailbox deposit and receive. Interrupt causes these methods to throw InterruptedException, so typical use is like this: try { msg = inbox.receive(); catch (InterruptedException e) { HandleEmergency(); Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 18

Remote Mailboxes (A Side Excursion) RMI: Remote Method Interface allows one program to refer to objects in another program. We use it to allow mailboxes in one program be received from or deposited into in another. To use this, you define an interface to the remote object: import java.rmi.*; interface Mailbox extends Remote { void deposit(object msg) throws InterruptedException, RemoteException; Object receive() throws InterruptedException, RemoteException;... On machine that actually will contain the object, you define class QueuedMailbox... implements Mailbox { Same implementation as before, roughly Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 19

Remote Objects Under the Hood // On machine #1: // On Machine #2: Mailbox outbox Mailbox inbox = new QueuedMailbox(); = get outbox from machine #1 outbox: a QueuedMailbox queue: [ Hi,...] receive() request (I/O) response Hi (I/O) inbox: a Mailbox stub receive() Because Mailbox is an interface, hides fact that on Machine #2 doesn t actually have direct access to it. Requests for method calls are relayed by I/O to machine that has real object. Any argument or return type OK if it also implements Remote or can be serialized turned into stream of bytes and back, as can primitive types and String. Because I/O involved, expect failures, hence every method can throw RemoteException (subtype of IOException). Last modified: Fri Nov 17 01:28:46 2017 CS61B: Lecture #36 20