Networking Java threads and synchronization PRIS lecture 4



















































- Slides: 51

Networking, Java threads and synchronization PRIS lecture 4 Fredrik Kilander

OSI TCP/IP Application Presentation Session Transport Network Internet Data link Physical Host-to-network A. S. Tanenbaum, Computer Networks, 3 rd Ed.

OSI TCP/IP Application Presentation Session Middleware Transport Network Internet Data link Physical Host-to-network A. S. Tanenbaum, Computer Networks, 3 rd Ed.

HTTP Protocols Bit. Torrent SMTP TCP SSH DNS UDP Transport IP Networks WAN MAN LAN Application Network Wi. Fi 3 G PPP Data link + physical Adapted from A. S. Tanenbaum, Computer Networks, 3 rd Ed.

Application Remote Procedure Call Application SOAP Message SOAP XML Message XML HTTP Connection HTTP Transport Connection Transport Network Packet Network Data link Frame Data link Physical Waves Physical

Communication Layers, interfaces, and protocols in the OSI (Open Systems Interconnection) reference model. • Divided into 7 layers each deals with one specific aspects of the communication

Transport unreliable Network reliable Data link unreliable Physical reliable

Reliable data transmission • • • Divide data into packets Add error-detection/correction to payload Add sequence numbers Add a timer for each packet sent Keep resending packets until they are ack’d. Acknowledge received packets

Point-to-point connection Transport Network Data link Physical Wire or EM beam

Common media, no longer point-to-point Transport Network Data link Physical Coaxial cable or radio channel (wave propagation medium)

Medium ACcess Layer OSI Application Presentation Session Transport Network Data link Physical MAC

MAC layer negotiates access to shared medium Transport Network Data link MAC MAC Physical

Ethernet history – thick cable

Ethernet history – thinwire

Ethernet history – CAT 6/Wi. Fi

Stations share the broadcast medium Only one station may send - all listen Ada Bea Cia Didi Eve MAC MAC MAC Transmissions are addressed • to an interface (unicast) • or to a group (multicast) • or to all (broadcast)

Stations share the broadcast medium The MAC-address depends on the medium 00: 1 F: 3 B: BF: CA: 35 Ada Bea Cia Didi Eve MAC MAC MAC Ethernet Blue. Tooth 48 bits vv: vv: ss: ss 48 bits NAP(16)UAP(8)LAP(24) NAP: Non-significant address portion LAP: Lower address portion UAP: Upper address portion

Stations share the broadcast medium Simultaneous broadcasts leads to collisions Ada Bea Cia Didi Eve MAC MAC MAC

Stations share the broadcast medium Simultaneous broadcasts leads to collisions Ada Bea Cia Didi Eve MAC MAC MAC Interference where frames overlap

OSI TCP/IP Application Presentation Session Transport Network Internet Data link Physical Host-to-network A. S. Tanenbaum, Computer Networks, 3 rd Ed.

Data network: routers and links

Network/Internet layer – routing of packets Each router selects the best output line for the packet Packets may be • Lost (router memory is full) • Reordered (go separate paths) • Delayed (queued)

OSI TCP/IP Application Presentation Session Transport Network Internet Data link Physical Host-to-network A. S. Tanenbaum, Computer Networks, 3 rd Ed.

Transport layer – virtual connection Endpoints simulate a continuous stream of bytes TCP: packet sizes depend on delay Fixes lost and reordered packets

Multithreading Concurrent computing

Threads allow parallel execution in one pgm Threading is a programming language construct

Threads allow parallel execution in one pgm The main thread is issued by the operating system. It enters the main routine of the program. When it exits the program ends.

Threads allow parallel execution in one pgm Other threads are issued from the main thread. They enter other routines of the same program. Several threads can enter the same routine. When the entry point is exited, the thread ends.

Threads allow parallel execution in one pgm The main thread always enters the main program. int foo() { a = b; c = d; . . . } void bar (int x) { x = u * b; . . . } void main (String argv[]) { boolean o; double p; . . . } Other threads execute with other routines as their main programs.

Threads allow parallel execution in one pgm All threads share global variables. Threads do not share local variables because each thread has its own stack. int a = 0; boolean b; void foo() { int a; . . . } void bar (int x) { float y; . . . } Threads can be implemented in several ways: Virtual threads by interpreter Parallel processes from OS Threads supported by OS void main (String argv[]) { a = 42; . . . }

Mental models • Single-threaded – whole program • Multi-threaded – several small programs • Where and how can and should threads interact in my program?

Surreptious multi-threading: • Callback APIs – GUI events – Messaging systems – Discovery systems • Timers • RPC server

Race condition Insert presentation here

Threads in Java A class that supports threading implements interface Runnable. import java. lang. Runnable; import java. lang. Thread; class My. Server implements Runnable { Interface Runnable has one method: run(). This is a thread’s entry point. // In interface Runnable: public void run () {. . . } A new thread is created just like any other object. It is given the object where to execute and told to start running. public void main (String argv[]) {. . . new Thread (this). start (); . . . } }

Threads in Java A class that supports threading implements interface Runnable. class My. Server implements Runnable. . . Thread t = new Thread (this); . . . public void run() {. . . } Interface Runnable has one method: run(). This is a thread’s entry point. A new thread is created just like any other object. It is given the object where to execute and told to start running. Thread t public void start()

Threads in Java class My. Server. . . Thread t = new Thread (new Worker()); . . . t. start (); class Worker implements Runnable public void run() {. . . } Thread t public void start()

Threads in Java In Java you must use method Runnable. run(). Where is the diversity? import java. lang. Runnable; import java. lang. Thread; class My. Server implements Runnable { int h; // In interface Runnable: public void run () { switch (h) { case 1: foo(); break; case 2: bar(); break; } } Programmatic or computed choice. public void main (String argv[]) {. . . h = 1; new Thread (this). start (); h = 2; } Race condition on variable h! }

Threads in Java In Java you must use method Runnable. run(). Where is the diversity? import java. lang. Runnable; class Foo implements Runnable { public void run () {. . . } } Separate out methods into their own classes. import java. lang. Runnable; class Bar implements Runnable { public void run () {. . . } } import java. lang. Runnable; import java. lang. Thread; class My. Server { public void main (String argv[]) { new Thread (new Foo ()). start (); new Thread (new Bar ()). start (); } }

Threads in Java In Java you must use method Runnable. run(). Where is the diversity? import java. lang. Runnable; import java. lang. Thread; class My. Server { protected void do. Work () {. . . } public void main (String argv[]) {. . . new Thread (new Runnable () { public void run () { do. Work (); } } Anonymous subclassing

Threads in Java Wait for a thread to die: Thread. join() import java. lang. Runnable; import java. lang. Thread; class My. Server { public void main (String argv[]) {. . . // Create thread t. Thread t = new Thread (new Foo ()). start (); . . . // Main thread waits for t to die. t. join (); . . . } }

Threads in Java Thread control • sleep (long ms) – suspend caller for at least ms milliseconds • join (Thread t) – suspend caller until other thread t has exited • wait() – suspend until notified (in a synchronized block) • notify() – release a wait()ing thread (in a synchronized block)

Synchronization in Java Threads that access common variables together can seriously mess up the state of the program. Synchronization is achieved by monitors. A monitor is a non-sharable entity associated with a Java object (choosen by the programmer). Synchronized code is locked by the object. A thread must have the monitor to be able to execute the synchronized code.

Synchronization in Java When a method is declared as synchronized the monitor is retrieved from the method’s object. Potential inefficiency. public synchronized void enqueue() {. . . } When a block of code is synchronized, any object’s monitor can be used: synchronized (my. Queue) {. . . }

Synchronization in Java A thread that attempts to enter a synchronized method or block must wait in a queue for the monitor. When the monitor is released the thread continues to execute. While thread is inside the synchronized section it can release the monitor and wait(). synchronized (my. Queue) {. . . wait (); // Nothing to do. . . } When some other thread has the monitor it can notify the waiting thread, giving back the monitor and allowing it to continue: synchronized (my. Queue) {. . . notify (); // Work is ready for you. . . }

Synchronization in Java Producer thread Adds items to the queue my. Queue Consumer thread Removes items from the queue my. Queue head tail

Synchronization in Java Qmobj Producer thread Adds items to the queue my. Queue Consumer thread Removes items from the queue my. Queue Producer asks for my. Queue’s monitor Producer is waiting for the monitor Synchronized code Consumer asks for my. Queue’s monitor Producer receives my. Queue’s monitor Consumer is waiting for the monitor Producer enqueues items Producer returns my. Queue’s monitor Consumer receives my. Queue’s monitor Consumer dequeues items Consumer returns my. Queue’s monitor Synchronized code

Synchronization in Java Qmobj Producer thread Adds items to the queue my. Queue Consumer thread Removes items from the queue my. Queue Producer asks for my. Queue’s monitor Producer is waiting for the monitor Synchronized code Consumer asks for my. Queue’s monitor Producer receives my. Queue’s monitor Consumer is waiting for the monitor Producer enqueues items Both threads aremonitor waiting Producer returns my. Queue’s for Consumer receives my. Queue’s monitor the monitor: The winner selection is undefined Consumer dequeues items Consumer returns my. Queue’s monitor Synchronized code

Synchronization in Java A typical application of the wait()/notify() mechanism is a consumer producer pair with a queue between them. Access to the queue must be synchronized. While the queue is empty the consumer does not execute. synchronized (my. Queue) { my. Queue. enqueue (x); } synchronized (qm. Obj) { notify (); } // In qm. Obj: my. Queue M for (; ; ) { while (!my. Queue. is. Empty()) { synchronized (my. Queue) { e = my. Queue. dequeue (); } } synchronized (this) { wait (); } }

synchronized (my. Queue) { my. Queue. enqueue (x); } synchronized (qm. Obj) { notify (); // In qm. Obj: } my. Queue M for (; ; ) { while (!my. Queue. is. Empty()) { synchronized (my. Queue) { e = my. Queue. dequeue (); } } synchronized (this) { wait (); } }

Stuff we did not mention. . . Avoid Thread. stop() suspend() resume() (deprecated) Class Threadgroup : handle threads as a unit Class Thread. Local : thread-specific data Thread intercommunication with pipes. Thread priorities.

The End