CSCD 330 Network Programming

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.
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?
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.
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.
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.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
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.
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.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
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.
Lecture 3 Concurrency and Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
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.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Java Thread Programming
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Threaded Programming in Python
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreading Chapter 9.
Object-Orientated Analysis, Design and Programming
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Race Conditions & Synchronization
Liveness And Performance
Java Based Techhnology
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
Software Engineering and Architecture
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CSCD 330 Network Programming Lecture 12 More Client-Server Programming Spring 2017 Reading: References at end of Lecture

Introduction So far, Looked at client-server programs with Java Today 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

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

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

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

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

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

Example of Two Threads There is 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

Other thread can execute first 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

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

Concurrency and Threads So, threads can have 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 ...

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

Ryan and Monica Two Thread Story Run method, Ryan and Monica each running in a separate thread Normally, we would write an algorithm that: - Checks the balance, - if enough money, withdraw amount Else - Do not withdraw to protect against overdraft Should protect against overdrawing the account … but They fall asleep after checking the balance but before they finish withdrawal

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

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 times Flag overdrawn

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

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

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

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

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

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

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 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 See the Problem?

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

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

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 – Just wait () Demo RyanAndMonica6 – wait() and notify()

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

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

Next: Network Layer – Routers and Routing