1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Ken Birman 1. Refresher: Dekers Algorithm Assumes two threads, numbered 0 and 1 CSEnter(int i) { int J = i^1; inside[i] = true; turn = J; while(inside[J]
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
May 23, 2002Serguei A. Mokhov, 1 Synchronization COMP346/ Operating Systems Tutorial 3 Revision 1.2 October 7, 2003.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Multithreading. RHS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this?
CS 11 java track: lecture 7 This week: Web tutorial:
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
CS Introduction to Operating Systems
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
Internet Software Development More stuff on Threads Paul Krause.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
CSE 219 Computer Science III Multithreaded Issues.
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)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Games Development 2 Concurrent Programming CO3301 Week 9.
Threading Eriq Muhammad Adams J
Threads.
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
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
1 CSCD 330 Network Programming Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 9 Client-Server Programming.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Implementing Lock. From the Previous Lecture  The “too much milk” example shows that writing concurrent programs directly with load and store instructions.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Implementing Mutual Exclusion Andy Wang Operating Systems COP 4610 / CGS 5765.
Java Thread Programming
CSCD 330 Network Programming
Multithreading / Concurrency
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreading Chapter 9.
Threads Chate Patanothai.
Multithreading.
Implementing Mutual Exclusion
Implementing Mutual Exclusion
Computer Science 2 06A-Java Multithreading
NETWORK PROGRAMMING CNET 441
CSE 153 Design of Operating Systems Winter 19
Threads and Multithreading
CSCD 330 Network Programming
Lecture 19 Threads CSE /6/2019.
CSE 332: Concurrency and Locks
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture

2 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

3 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

4 Threads States Thread t = new Thread (r); 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 t.start(); Running! Once thread is runnable, can go back and forth between running, runnable and blocked

5 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

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(); }

7 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.

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

9 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

10 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

11 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!!

12 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...

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

15 class BankAccount { private int balance = 100; public int getBalance() { return balance; } public void withdraw(int amount) { balance = balance - amount; } public class RyanAndMonica implements Runnable { private BankAccount account = new BankAccount(); 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(); withdraw amount Job Start two threads

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

17 private 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(); } 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()); } Ryan and Monica …. run it and see …. RyanAndMonica class check account force sleep make withdrawal

18 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

19 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

20 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

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

22 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

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?

24 Other Thread Methods Another way besides sleep() to influence threads to move between runnable and ready- to-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

25 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

26 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

27 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

28 References More Intro Type of Information Goes into Semaphores and Locking Goes into Semaphores and Locking Insider view of Java Virtual Machine more detailed...

29 Program is now due on Monday, June 2 !!