Lec 10 agenda >git fetch origin lab10g; > git checkout -b lab10g origin/lab10g; Format/rules for Week 11 Advanced Topics (all beyond the scope of this.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
Object-Oriented Software Engineering Concurrent Programming.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
ThreadThread Thread Basics Thread Synchronization Animations.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Chapter 21 – Multithreading Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Internet Software Development Controlling Threads Paul J Krause.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java Thread and Memory Model
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Serialization Allows you to turn Java Objects into serial data that can be either save to a file or sent over a network. Usefull for persisting data.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreading Chapter 9.
Lecture 21 Concurrency Introduction
Threads Chate Patanothai.
ITEC324 Principle of CS III
Multithreading.
Multithreaded Programming
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Lec 10 agenda >git fetch origin lab10g; > git checkout -b lab10g origin/lab10g; Format/rules for Week 11 Advanced Topics (all beyond the scope of this course) – Serialization Sockets – Concurrency (Threads) Lab

Serialization Allows you to turn Java Objects into serial data that can be either saved to a file, stored in a db, or sent over a network. Useful for persisting data.

Serialization analogy to physics Objects in Memory space are in a gas state and they're alive. Serialized objects are liquid and they're suspended (they can flow across networks, and be persisted to a hard- drives and databases)

Serialization Syntax FileOutputStream filOut = new FileOutputStream("gamestate.ser"); ObjectOutputStream out = new ObjectOutputStream(filOut); out.writeObject(gst); out.close(); filOut.close();

Deserialization Syntax FileInputStream filIn = new FileInputStream("gamestate.ser"); ObjectInputStream ois = new ObjectInputStream(filIn); gst= (GameState) ois.readObject(); ois.close(); filIn.close();

Sockets See example package called socket from lab10

Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed serially, from start to finish. In a threaded program, you can have multiple threads working concurrently.

Process vs. Threads Process: A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time. Threads: threads are so-called lightweight processes which have their own call-stack but can access shared data on the heap. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache.

Threads are short-lived Threads are like processes, only they're short-lived. How short-lived? – When run() method terminates or returns – The thread is interrupted – An exception is thrown inside run()

Concurrency (Threads) Concurrency is achieved through time- slicing. This is where the processor cycles through each active thread for an indeterminate period of time (the slice). This gives the illusion that there are multiple processes. With multi-core processors, this may mean, true multi-threading is possible, but NOT guaranteed Invoke jvisualvm

Amdahl's Law Concurrency promises to perform certain task faster as these tasks can be divided into subtasks and these subtasks can be executed in parallel. Of course the runtime is limited by parts of the task which can be performed in parallel. The theoretical possible performance gain can be calculated by Amdahl's Law. If F (fixed) is the percentage of the program which can not run in parallel and n is the number of processes then the maximum performance gain is: 1/ (F+ ((1-F)/n)).

Concurrency Issues Liveliness: The program reacts slowly due to concurrent access of data. Safety: The program creates incorrect data.

Concurrency Imperatives Liveliness: The program must react quickly despite concurrent access of data. Safety: The program must produce correct data. These two imperatives are at odds and there is a trade-off between them. The best multi-threaded programs balance these two imperatives.

Syncrhonized keyword that only a single thread can execute a block of code at the same time ensures that each thread entering a synchronized block of code sees the effects of all previous modifications that were guarded by the same lock

Volatile keyword If a variable is declared as volatile then it is guaranteed that any thread which reads the field will see the most recently written value. This is to guard against caching. If you use synchronized properly, you don't need to worry about volatile at all.

Car + Engine + Turn-key Thread Runnable.start()

Car + Engine + Turn-key Thread Runnable.start() Thread thr = new Thread(new MyRunner()); thr.start(); //start will spawn a new thread

private class MyRunner implements Runnable public void run() { //do some work } Thread thr = new Thread(new MyRunner()); thr.start(); Define your own Runnable class

Thread thr = new Thread(new Runnable() public void run() { } }); thr.start(); anonymous-inner class

new Thread(new Runnable() public void run() { } }).start(); Reference anonymous thread and anonymous-inner class

private class MyRunningThread extends Thread public void run { //do some work } new MyRunningThread().start(); Thread which can run itself

Thread Pools Thread Pools manage (and limit) the number of active threads. This tends to be more orderly and more efficient for scaled applications.

Synchronizing methods When multiple threads have access to the same object, it makes sense to synchronize those methods which are prone to concurrency errors. The bank account example.

Thread-safe collections // pi/java/util/concurrent/package- summary.html

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Running a Thread Implement a class that implements the Runnable interface: public interface Runnable { void run(); } Place the code for your task into the run method of your class: public class MyRunnable implements Runnable { public void run() { Task statements... } }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Running a Thread Create an object of your subclass: Runnable r = new MyRunnable(); Construct a Thread object from the runnable object: Thread t = new Thread(r); Call the start method to start the thread: t.start();

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Running Threads sleep puts current thread to sleep for given number of milliseconds: Thread.sleep(milliseconds) When a thread is interrupted, most common response is to terminate run

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Generic run method public void run() { try { Task statements } catch (InterruptedException exception) { } Clean up, if necessary }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch20/greeting/GreetingRunnable.java 1 import java.util.Date; 2 3 /** 4 A runnable that repeatedly prints a greeting. 5 */ 6 public class GreetingRunner implements Runnable 7 { 8 private static final int REPETITIONS = 10; 9 private static final int DELAY = 1000; private String strGreeting; /** 14 Constructs the runnable object. aGreeting the greeting to display 16 */ 17 public GreetingRunner(String strGreeting) 18 { 19 this.strGreeting = strGreeting; 20 } 21 Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. To Start the Thread Construct an object of your runnable class: Runnable t = new GreetingRunnable("Hello World"); Then construct a thread and call the start method: Thread t = new Thread(r); t.start();

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Thread Scheduler Thread scheduler: runs each thread for a short amount of time (a time slice) Then the scheduler activates another thread There will always be slight variations in running times - especially when calling operating system services (e.g. input and output) There is no guarantee about the order in which threads are executed

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Terminating Threads A thread terminates when its run method terminates Do not terminate a thread using the deprecated stop method Instead, notify a thread that it should terminate: t.interrupt(); interrupt does not cause the thread to terminate – it sets a boolean variable in the thread data structure

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Terminating Threads The run method should check occasionally whether it has been interrupted Use the interrupted method An interrupted thread should release resources, clean up, and exit: public void run() { for (int i = 1; i <= REPETITIONS && !Thread.interrupted() ; i++) { Do work } Clean up }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Terminating Threads Java does not force a thread to terminate when it is interrupted It is entirely up to the thread what it does when it is interrupted Interrupting is a general mechanism for getting the thread’s attention

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Synchronizing Object Access When a thread calls lock, it owns the lock until it calls unlock A thread that calls lock while another thread owns the lock is temporarily deactivated Thread scheduler periodically reactivates thread so it can try to acquire the lock Eventually, waiting thread can acquire the lock

SwingWorker SwingWorker takes two Object parameters. +The first is the return value and is passed to done() +The second parameter is the progress value and is passed to publish/process. Example: SwingWorker There are three important methods of SwingWorker. +doInBackGround() --background thread +process() -main UI thread +done() -main UI thread