CSCD 330 Network Programming

Similar documents
CSCD 330 Network Programming

Synchronization in Concurrent Programming. Amit Gupta

Java Threads. What Are Threads? General-purpose solution for managing concurrency. Multiple independent execution streams. Shared state.

CERTIFICATION OBJECTIVES

COMP346 Winter Tutorial 4 Synchronization Semaphores

Animation Part 2: MoveableShape interface & Multithreading

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Threads Chate Patanothai

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

Java Threads. COMP 585 Noteset #2 1

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

CSCD 330 Network Programming

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

CSCD 330 Network Programming

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

CSCD 330 Network Programming

Introduction to Java Threads

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

Multithreaded Programming

7. MULTITHREDED PROGRAMMING

CMSC 132: Object-Oriented Programming II

CS 351 Design of Large Programs Threads and Concurrency

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


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

COE518 Lecture Notes Week 7 (Oct 17, 2011)

Component-Based Software Engineering

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

CS360 Lecture 12 Multithreading

Contents. 6-1 Copyright (c) N. Afshartous

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall()

Synchronization

Synchronization synchronization.

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

04-Java Multithreading

Excep&ons and Threads

Reintroduction to Concurrency

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

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

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

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

COMP 322: Fundamentals of Parallel Programming

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430

Administrivia. Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS

Robotics and Autonomous Systems

Module - 4 Multi-Threaded Programming

Java Programming Lecture 23

Threads and Parallelism in Java

Threads and Concurrency in Java

THREADS AND MULTITASKING ROBOTS

ROBOTICS AND AUTONOMOUS SYSTEMS

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

CMSC 330: Organization of Programming Languages

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

CS11 Java. Fall Lecture 7

Programming Language Concepts: Lecture 11

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

COMP 346 WINTER Tutorial 5 MONITORS

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CS180 Review. Recitation Week 15

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Threads and Java Memory Model

Programming Language Concepts: Lecture 13

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

Software Practice 1 - Multithreading

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

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

Before we can talk about concurrency, we need to first understand what happens under the hood when the interpreter executes a Python statement.

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Multithreading in Java Part 2 Thread - States JAVA9S.com

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

CSE332: Data Abstractions Lecture 19: Mutual Exclusion and Locking

CS18000: Programming I

Synchronization Lecture 24 Fall 2018

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

Part IV Other Systems: I Java Threads

Problems with Concurrency. February 19, 2014

Monitors; Software Transactional Memory

Multiple Inheritance. Computer object can be viewed as

Chapter 32 Multithreading and Parallel Programming

Advanced Concepts of Programming

Concurrent Computing CSCI 201 Principles of Software Development

Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

CSE 332 Winter 2018 Final Exam (closed book, closed notes, no calculators)

Chapter 19 Multithreading

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Synchronization in Java

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues

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

Multi-threading in Java. Jeff HUANG

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

Unit 5 - Exception Handling & Multithreaded

THREADS AND CONCURRENCY

Transcription:

CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2016 Reading: References at end of Lecture 1

Introduction So far, Looked at client-server programs with Java Sockets TCP and UDP based Reading and writing to a socket Sockets with threads Multiple clients at a time Today Look at more complexity with threads Synchronizing threads Come in handy with future program 2

Threads Recall A thread is Separate thread of execution Called from an existing program A java class, Thread represents a thread in Java Has a separate stack Allows you to run separate processes from main thread Can do concurrency 3

Threads States Thread t = new Thread (r); t.start(); Running! Thread created but not started Thread ready to run, runnable state Waiting to be selected for execution Thread selected to run and is the currently running thread Once thread is runnable, can go back and forth between running, runnable and blocked 4

Threads The JVM thread scheduler is responsible for deciding who gets to run next You, have little control over the decision Don t base your program s correctness on the scheduler working in a particular way Example: Two threads executing 5

6 Example of Two Threads public class RunThreads implements Runnable { RunThreads runner = new RunThreads (); Thread alpha = new Thread (runner); Thread beta = new Thread (runner); alpha.setname ( Alpha thread ); beta.setname ( Beta thread ); alpha.start (); beta.start(); }

Example of Two Threads public void run() { for (int i = 0; i < 25; i++) { } } } String threadname = Thread.currentThread().getName (); System.out.println (threadname + is running ); Lets execute this and see what happens. Will run two examples of this. 7

8 How can we Control Scheduler What can we do to influence the thread execution?

Example of Two Threads We can do something about the Scheduler Can t control it, but we can force it to execute things in order There is Thread.sleep(arg) Will put one thread to sleep Call the sleep method and pass it the sleep duration in milliseconds Will knock the thread out of the running state and keep it out for the duration Example: Thread.sleep (2000); thread sleeps 2 secs 9

Sleep method throws in InterruptedException, so all calls must be wrapped in a try/catch ------------------------------------------------------------------------------------------------- public void run() { String threadname = Thread.currentThread().getName (); if (threadname.equals("alpha thread")) { } try { Thread.sleep(500); } catch (InterruptedException ex) { ex.printstacktrace (); } for (int i = 0; i < 25; i++) { System.out.println (threadname + "is running"); } } Put one thread to sleep Other thread can execute first Execute again, RunThreads4 or RunThreads3 10

Thread States After putting thread to sleep... When it wakes up, its runnable Can be selected to run No guarantee that it will be run!! 11

Concurrency and Threads So, with threads there can be concurrency issues When you need to coordinate access to same object between two or more threads Left hand side doesn t know what right hand side is doing Operating from two different stacks When thread is not running, it is completely unaware that anything else is happening Like being unconscious Lets look at an example... 12

13 Ryan and Monica Two Thread Story Two threads one object Ryan and Monica, a couple One bank account, limited amount of money!! Trouble for sure RyanandMonica are a Job Its runnable Two threads, both operate on the same job Artificially create a race condition in the code They each need to withdraw an amount without overdrawing the account

14 Ryan and Monica Two Thread Story Run method, Ryan and Monica each running in a separate thread Check the balance, if enough money, withdraw amount Should protect against overdrawing the account but They fall asleep after checking the balance but before they finish withdrawal

class BankAccount { private int balance = 100; public class RyanAndMonica implements Runnable { public int getbalance() { return balance; } private BankAccount account = new BankAccount(); } public void withdraw(int amount) { balance = balance - amount; } withdraw amount public static void main (String [] args) { RyanAndMonica thejob = new RyanAndMonica(); Thread one = new Thread (thejob); Thread two = new Thread (thejob); one.setname ("Ryan"); two.setname ("Monica"); one.start(); two.start(); Start two threads Job 15

Ryan and Monica Two Thread Story public void run() { for (int x = 0; x < 10; x++) { makewithdrawal(10); Try to withdraw 10 times if (account.getbalance() < 0) { System.out.println("Overdrawn!"); Flag overdrawn } } } Within makewithdrawal, put checks to prevent overdrawn condition 16

private void makewithdrawal(int amount) { if (account.getbalance() >= amount) { account System.out.println(Thread.currentThread().getName() + " is about to withdraw"); } } try { System.out.println(Thread.currentThread().getName() + " is going to sleep"); force sleep Thread.sleep(1000); } catch(interruptedexception ex) {ex.printstacktrace(); } System.out.println(Thread.currentThread().getName() + " woke up."); account.withdraw(amount); System.out.println(Thread.currentThread().getName() + " completes the withdrawl"); } else { System.out.println("Sorry, not enough money for " + Thread.currentThread().getName()); } check make withdrawal Ryan and Monica. run it and see. RyanAndMonica class 17

Ryan and Monica Continued What happened? Ryan was in the middle of his transaction when Monica thread checked balance and withdrew amount Invalid transaction Solution? Make the transaction one single action Atomic transaction Will see this when you take Database Must check and withdraw money all in one action 18

Monica and Ryan Need a lock associated with the bank account transaction One key and it stays with the lock One person at a time gets the lock and key until transaction finished Key is not released until transaction over Use the synchronized key word in Java Prevents multiple threads from using a method at a time 19

Ryan and Monica private synchronized void makewithdrawal(int amount) { if (account.getbalance() >= amount) { System.out.println(Thread.currentThread().getName() + " is about to withdraw"); try { System.out.println(Thread.currentThread().getName() + " is going to sleep"); Thread.sleep(1000); } catch(interruptedexception ex) {ex.printstacktrace(); } Re-run example. RyanAndMonica3 20

Threads and Concurrency Goal of synchronization Protect critical data Don t lock the data Synchronize methods that access the data Problem with Synchronization? 21

Problems with Concurrency Problem is Deadlock Java has no real way to deal with deadlock You must design your applications to handle this case Pay attention to the order in which you start your threads 22

23 Deadlock Scenario Simple Deadlock scenario Thread A enters synchronized method object foo Get key Thread A goes to sleep holding foo key Thread B enters synchronized method object bar Get key Thread B tries to enter synchronized method of object foo but can t get that key Goes to waiting room, keeps bar key Thread A wakes up, tries to enter synchronized method of object bar, can t, key not available Goes to waiting room Problem?

Other Thread Methods Another way besides sleep() to influence threads to move between runnable and readyto-run is Thread.yield(); All it does is move one thread to ready-to-run for a while May not result in threads taking turns Demo with RyanAndMonica4.java 24

Other Thread Methods Turns out that once a thread gets a lock, does not want to give it up Thus, unless we can break Monica's hold on the bank book Resulting from the Synchronized method Ryan is out of luck for getting any money! Wait (); - Turns out, you can make Monica wait for a while and allow Ryan to get in and get some money Wait - makes the lock holding thread pause Notify - used to tell waiting thread lock is free 25

Final Solution to Ryan and Monica So, the wait() method will help regulate Monica's behavior Set up the synchronized method to create a critical section Then, make her release the lock through the wait method so Ryan has a chance!!! Demo RyanAndMonica5 26

Summary Covered Threads and Synchronization Demonstrated that the JVM scheduler can t be trusted to execute threads in a given order Concurrency issues can lead to deadlock Ways around this... but need to be aware of issues 27

References More Intro Type of Information http://www.javabeginner.com/learn-java/java-threads-tutorial Goes into Semaphores and Locking http://www.ibm.com/developerworks/library/j-thread.html Goes into Synchronization of Java Threads http://java.sun.com/docs/books/tutorial/essential/concurrency/sync.html Insider view of Java Virtual Machine more detailed... http://www.artima.com/insidejvm/ed2/threadsynch.html 28

Next: Network Layer Routers and Routing 29

1