Upload
others
View
17
Download
0
Embed Size (px)
Citation preview
Networking, Java threads and synchronization
PRIS lecture 4Fredrik Kilander
Application
Presentation
Session
Transport
Network
Data link
Physical
OSIApplication
Transport
Internet
TCP/IP
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd Ed.
Application
Presentation
Session
Transport
Network
Data link
Physical
OSIApplication
Transport
Internet
TCP/IP
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd Ed.
Middleware
SSHBitTorrent SMTP DNSHTTP
TCP UDP
IP
LAN WiFi PPP
Application
Transport
Network
Data link +physical
Protocols
Networks
Adapted from A. S. Tanenbaum, Computer Networks, 3rd Ed.
MANWAN 3G
Application
Transport
Network
SOAP
XML
HTTP
Application
Transport
Network
SOAP
XML
HTTP
Network
Waves
Remote Procedure Call
Packet
Connection
Connection
Message
Message
Data link
Physical
Data link
Physical
Data link
Physical
Frame
CommunicationLayers, 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
Network
Data link
Physical
unreliable
unreliable
reliable
reliable
Transport
Network
Data link
Physical
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
Transport
Physical
Transport
Physical
Network
Data link
Network
Data link
Point-to-point connection
Wire or EM beam
Transport
Physical
Transport
Physical
Network
Data link
Network
Data link
Common media, no longer point-to-point
Transport
Physical
Network
Data link
Coaxial cable or radio channel(wave propagation medium)
MAC
Application
Presentation
Session
Transport
Network
Data link
Physical
OSI
Medium ACcess Layer
Transport
Physical
Transport
Physical
Network
Data link
Network
Data link
MAC layer negotiates access to shared medium
Transport
Physical
Network
Data link
MAC MAC MAC
Ethernet history – thick cable
Ethernet history – thinwire
Ethernet history – CAT6/WiFi
Ada Bea Cia Didi Eve
MAC MAC MAC MAC MAC
Stations share the broadcast medium
Only one station may send - all listen
Transmissions are addressed • to an interface (unicast)• or to a group (multicast)• or to all (broadcast)
Ada Bea Cia Didi Eve
MAC MAC MAC MAC MAC
Stations share the broadcast medium
The MAC-address depends on the medium
Ethernet 48 bits vv:vv:vv:ss:ss:ssBlueTooth 48 bits NAP(16)UAP(8)LAP(24)
NAP:Non-significant address portionLAP:Lower address portionUAP:Upper address portion
00:1F:3B:BF:CA:35
Ada Bea Cia Didi Eve
MAC MAC MAC MAC MAC
Stations share the broadcast medium
Simultaneous broadcasts leads tocollisions
Ada Bea Cia Didi Eve
MAC MAC MAC MAC MAC
Stations share the broadcast medium
Simultaneous broadcasts leads tocollisions
Interference where frames overlap
Application
Presentation
Session
Transport
Network
Data link
Physical
OSIApplication
Transport
Internet
TCP/IP
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd Ed.
Data network: routers and links
Network/Internet layer – routing of packets
Packets may be• Lost (router memory is full)• Reordered (go separate paths)• Delayed (queued)
Each router selects the best output line for the packet
Application
Presentation
Session
Transport
Network
Data link
Physical
OSIApplication
Transport
Internet
TCP/IP
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd Ed.
Transport layer – virtual connection
Endpoints simulate a continuous stream of bytes
TCP: packet sizes depend on delayFixes lost and reordered packets
Multithreading
Concurrent computing
Threads allow parallel execution in one pgm
Threading is a programming language construct
Threads
Threads allow parallel execution in one pgm
Threads
The main thread is issued by the operatingsystem.
It enters the main routine of the program.
When it exits the program ends.
Threads allow parallel execution in one pgm
Threads
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
Threads
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 routinesas their main programs.
Threads allow parallel execution in one pgm
Threads
All threads shareglobal variables.
int a = 0;boolean b;
void foo() {int a;...
}
void bar (int x) {float y;...
}
void main (String argv[]) {
a = 42;...
}
Threads can be implementedin several ways:
Virtual threads by interpreter
Parallel processes from OS
Threads supported by OS
Threads can be implementedin several ways:
Virtual threads by interpreter
Parallel processes from OS
Threads supported by OS
Threads do notshare local vari-ables becauseeach thread has its own stack.
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 implementsinterface Runnable.
import java.lang.Runnable;import java.lang.Thread;
class MyServer implements Runnable {
// In interface Runnable:public void run () {...
}
public void main (String argv[]) {...new Thread (this).start ();...
}}
Interface Runnable hasone method: run(). Thisis a thread’s entry point.
A new thread is createdjust like any other object.It is given the objectwhere to execute andtold to start running.
Threads in Java
A class that supports threading implementsinterface Runnable.
Interface Runnable hasone method: run(). Thisis a thread’s entry point.
A new thread is createdjust like any other object.It is given the objectwhere to execute andtold to start running.
class MyServer implements Runnable...Thread t = new Thread (this);...public void run() {...}
class MyServer implements Runnable...Thread t = new Thread (this);...public void run() {...}
Thread t
public void start()
Thread t
public void start()
Threads in Java
class MyServer...Thread t = new Thread (new Worker());...t.start ();
class MyServer...Thread t = new Thread (new Worker());...t.start ();
Thread t
public void start()
Thread t
public void start()
class Worker implements Runnable
public void run() {...}
class Worker implements Runnable
public void run() {...}
Threads in JavaIn Java you must use method Runnable.run(). Where is the diversity?
import java.lang.Runnable;import java.lang.Thread;
class MyServer implements Runnable {int h;
// In interface Runnable:public void run () {switch (h) {case 1: foo(); break;case 2: bar(); break;}
}
public void main (String argv[]) {...h = 1;new Thread (this).start ();h = 2;
}}
Programmaticor computedchoice.
Race conditionon variable h!
Race conditionon variable h!
Threads in JavaIn Java you must use method Runnable.run(). Where is the diversity?
import java.lang.Runnable;import java.lang.Thread;
class MyServer {
public void main (String argv[]) {new Thread (new Foo ()).start ();new Thread (new Bar ()).start ();
}}
Separate outmethods intotheir own classes.
import java.lang.Runnable;class Foo implements Runnable {
public void run () {...
}}
import java.lang.Runnable;class Bar implements Runnable {
public void run () {...
}}
Threads in Java
import java.lang.Runnable;import java.lang.Thread;
class MyServer {
protected void doWork () {...
}
public void main (String argv[]) {...new Thread (new Runnable () {public void run () {doWork ();
}});
}}
In Java you must use method Runnable.run(). Where is the diversity?
Anonymoussubclassing
Threads in JavaWait for a thread to die: Thread.join()
import java.lang.Runnable;import java.lang.Thread;
class MyServer {
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 JavaThread 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 JavaThreads 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 JavaWhen 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 (myQueue) { ... }
Synchronization in JavaA thread that attempts to enter a synchronized method or blockmust wait in a queue for the monitor.
When the monitor is released the thread continues to execute.
While the thread is inside the synchronized section it canrelease the monitor and wait().
synchronized (myQueue) { ...wait (); // Nothing to do...}
When some other thread has the monitor it can notify the waitingthread, giving back the monitor and allowing it to continue:
synchronized (myQueue) { ...notify (); // Work is ready for you...}
Synchronization in Java
Producer threadAdds items to
the queue myQueue
Producer threadAdds items to
the queue myQueuemyQueuemyQueue Consumer thread
Removes items from the queue myQueue
Consumer threadRemoves items from the queue myQueue
head tailmyQueue
Synchronization in Java
Producer threadAdds items to
the queue myQueue
Producer threadAdds items to
the queue myQueuemyQueuemyQueue Consumer thread
Removes items from the queue myQueue
Consumer threadRemoves items from the queue myQueue
Producer receives myQueue’s monitor
Producer asks for myQueue’s monitor
Producer enqueues items
Producer returns myQueue’s monitor
Consumer dequeues items
Qmobj
Consumer asks for myQueue’s monitor
Consumer receives myQueue’s monitor
Consumer returns myQueue’s monitor
Synchronizedcode
Synchronizedcode
Producer iswaiting for
the monitor
Consumer iswaiting forthe monitor
Synchronization in Java
Producer threadAdds items to
the queue myQueue
Producer threadAdds items to
the queue myQueuemyQueuemyQueue Consumer thread
Removes items from the queue myQueue
Consumer threadRemoves items from the queue myQueue
Producer receives myQueue’s monitor
Producer asks for myQueue’s monitor
Producer enqueues items
Producer returns myQueue’s monitor
Consumer dequeues items
Qmobj
Consumer asks for myQueue’s monitor
Consumer receives myQueue’s monitor
Consumer returns myQueue’s monitor
Synchronizedcode
Synchronizedcode
Producer iswaiting for
the monitor
Consumer iswaiting forthe monitor
Both threads are waiting forthe monitor:The winner selection is undefined
Both threads are waiting forthe monitor:The winner selection is undefined
Synchronization in JavaA typical application of the wait()/notify() mechanism is a consumerproducer pair with a queue between them.
Access to the queue must be synchronized.
While the queue is empty the consumer does not execute.
M
myQueue
synchronized (myQueue) {myQueue.enqueue (x);
}synchronized (qmObj) {notify ();
}
// In qmObj:
for (;;) {while (!myQueue.isEmpty()) {
synchronized (myQueue) {e = myQueue.dequeue ();
}}synchronized (this) {
wait ();}
}
// In qmObj:
for (;;) {while (!myQueue.isEmpty()) {synchronized (myQueue) {e = myQueue.dequeue ();
}}synchronized (this) {wait ();
}}
M
myQueue
synchronized (myQueue) {myQueue.enqueue (x);
}synchronized (qmObj) {
notify ();}
Stuff we did not mention ...Avoid Thread. stop() suspend() resume() (deprecated)
Class Threadgroup : handle threads as a unit
Class ThreadLocal : thread-specific data
Thread intercommunication with pipes.
Thread priorities.
The End