Download the thread ends

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Networking, Java threads and
synchronization
PRIS lecture 4
Fredrik Kilander
OSI
TCP/IP
Application
Application
Presentation
Session
Transport
Transport
Network
Internet
Data link
Physical
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd Ed.
OSI
TCP/IP
Application
Application
Presentation
Session
Middleware
Transport
Transport
Network
Internet
Data link
Physical
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd Ed.
HTTP
Protocols
BitTorrent
SMTP
TCP
SSH
DNS
UDP
Transport
IP
Networks
WAN
MAN
LAN
Application
Network
WiFi
3G
PPP
Data link +
physical
Adapted from A. S. Tanenbaum, Computer Networks, 3rd Ed.
Remote Procedure Call
Application
Message
SOAP
Message
XML
Connection
HTTP
Connection
Transport
Network
Packet
Application
SOAP
XML
HTTP
Transport
Network
Network
Data link
Frame
Data link
Data link
Physical
Waves
Physical
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
reliable
Transport
Transport
unreliable
Network
Network
reliable
Data link
Data link
unreliable
Physical
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
Point-to-point connection
Transport
Transport
Network
Network
Data link
Data link
Physical
Physical
Wire or EM beam
Common media, no longer point-to-point
Transport
Transport
Transport
Network
Network
Network
Data link
Data link
Data link
Physical
Physical
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
Transport
Transport
Network
Network
Network
Data link
Data link
Data link
MAC
MAC
MAC
Physical
Physical
Physical
Ethernet history – thick cable
Ethernet history – thinwire
Ethernet history – CAT6/WiFi
Stations share the broadcast medium
Only one station may send - all listen
Ada
Bea
Cia
Didi
Eve
MAC
MAC
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:1F:3B:BF:CA:35
Ada
Bea
Cia
Didi
Eve
MAC
MAC
MAC
MAC
MAC
Ethernet
BlueTooth
48 bits vv:vv:vv:ss: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
MAC
MAC
Stations share the broadcast medium
Simultaneous broadcasts leads to
collisions
Ada
Bea
Cia
Didi
Eve
MAC
MAC
MAC
MAC
MAC
Interference where frames overlap
OSI
TCP/IP
Application
Application
Presentation
Session
Transport
Transport
Network
Internet
Data link
Physical
Host-to-network
A. S. Tanenbaum, Computer Networks, 3rd 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
Application
Presentation
Session
Transport
Transport
Network
Internet
Data link
Physical
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 delay
Fixes lost and reordered packets
Multithreading
Concurrent computing
Threads
Threads allow parallel execution in one pgm
Threading is a programming language construct
Threads
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
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
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
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 MyServer 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 MyServer 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 MyServer
...
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 MyServer 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 MyServer {
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 MyServer {
protected void doWork () {
...
}
public void main (String argv[]) {
...
new Thread (new Runnable () {
public void run () {
doWork ();
}
});
}
}
Anonymous
subclassing
Threads in Java
Wait 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 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 (myQueue) { ... }
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 the thread is inside the synchronized section it can
release the monitor and wait().
synchronized (myQueue) { ...
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 (myQueue) { ...
notify (); // Work is ready for you
...}
Synchronization in Java
Producer thread
Adds items to
the queue myQueue
myQueue
Consumer thread
Removes items from
the queue myQueue
myQueue
head
tail
Synchronization in Java
Qmobj
Producer thread
Adds items to
the queue myQueue
myQueue
Consumer thread
Removes items from
the queue myQueue
Producer asks for myQueue’s monitor
Producer is
waiting for
the monitor
Synchronized
code
Consumer asks for myQueue’s monitor
Producer receives myQueue’s monitor
Consumer is
waiting for
the monitor
Producer enqueues items
Producer returns myQueue’s monitor
Consumer receives myQueue’s monitor
Consumer dequeues items
Consumer returns myQueue’s monitor
Synchronized
code
Synchronization in Java
Qmobj
Producer thread
Adds items to
the queue myQueue
myQueue
Consumer thread
Removes items from
the queue myQueue
Producer asks for myQueue’s monitor
Producer is
waiting for
the monitor
Synchronized
code
Consumer asks for myQueue’s monitor
Producer receives myQueue’s monitor
Consumer is
waiting for
the monitor
Producer enqueues items
Both threads
aremonitor
waiting
Producer returns
myQueue’s
for
Consumer receives myQueue’s monitor
the monitor:
The winner selection is undefined
Consumer dequeues items
Consumer returns myQueue’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 (myQueue) {
myQueue.enqueue (x);
}
synchronized (qmObj) {
notify ();
}
// In qmObj:
myQueue
M
for (;;) {
while (!myQueue.isEmpty()) {
synchronized (myQueue) {
e = myQueue.dequeue ();
}
}
synchronized (this) {
wait ();
}
}
synchronized (myQueue) {
myQueue.enqueue (x);
}
synchronized (qmObj) {
notify ();
// In qmObj:
}
myQueue
M
for (;;) {
while (!myQueue.isEmpty()) {
synchronized (myQueue) {
e = myQueue.dequeue ();
}
}
synchronized (this) {
wait ();
}
}
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