Insert Lesson Name

Download Report

Transcript Insert Lesson Name

Lecture K – Advanced Java API
Unit K1 – Communication
Lecture K – Advanced Java API
Slide 1 of 36.
Computer Communication
• The most important function of most computers today is to
communicate with other computers
• In “reality” various electronic signals move across various
electrical wires, optical cables, and electromagnetic waves
• In a Java program we get a neat high level encapsulation
of communication.
• E.g.: Web access:
InputStream page = new
URL(“http://www.cnn.com”).openStream();
Lecture K – Advanced Java API
Slide 2 of 36.
Abstractions in Computer Communication
• As always in Computer Science, we need to get the
•
•
•
•
correct abstractions.
As usual in computer science, there are many levels of
abstraction until you get to the URL().openStream()
level
The trick in communication is to have the same level of
abstraction on both sides of the communication line
There are several standards for levels of abstractions to
be used in computer communication
E.g. the ISO standard has 7 well defined layers
Lecture K – Advanced Java API
Slide 3 of 36.
Basic layers of abstraction in communication
• Physical

Hardware: Wires, voltage levels, frequencies, etc.
• Network


Specific to each kind of local network: e.g. Ethernet
Allows sending/receiving bits to/from the local network
• Internet



Internet Protocol – IP – common abstraction layer for all
computers connected to the Internet
Provides a world-wide address space (e.g. humus=132.65.128.9)
Allows sending a packet to any Internet address (unreliably)
• Transport

TCP – provides a reliable bi-directional stream
• Application

E.g. http, ftp, smtp, …, and user defined
Lecture K – Advanced Java API
Slide 4 of 36.
Communication in Java
• You can easily communicate with other computers using
an existing application-level protocol (ftp, http) using the
java.net.URL class.
• You can communicate at the transport layer of abstraction
using the java.net.Socket and
java.net.ServerSocket classes.
• In this case you must define and use your own
application-level protocol.
Lecture K – Advanced Java API
Slide 5 of 36.
Sockets
• Sockets come in two flavors: server socket and client
socket
• Client-Server methodology




Server creates ServerSocket and “binds” it to a “well known”
port
Server listens on this socket
A client that wants to talk to the server must create a Socket and
connect it to the server socket, given by a <host, port> pair
When a client connects, the server and client have a bi-directional
stream between them
Lecture K – Advanced Java API
Slide 6 of 36.
Server Socket
import java.net.*;
import java.io.*;
public class UpperServer {
public static void main(String[] args){
try {
ServerSocket server = new ServerSocket(1234);
Socket client = server.accept(); // wait for client
PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String line;
while ((line = in.readLine()) != null)
out.println(line.toUpper());
out.close();
in.close();
client.close();
server.close();
} catch (Exception e) { System.err.println(e); }
}
}
Lecture K – Advanced Java API
Slide 7 of 36.
Client Socket
import java.net.*;
import java.io.*;
public class UpperClient {
public static void main(String[] args){
try {
Socket server = new Socket(“pita.huji.ac.il”, 1234);
PrintWriter serverOut = new PrintWriter(
server.getOutputStream(), true);
BufferedReader serverIn = new BufferedReader(
new InputStreamReader(server.getInputStream()));
String line;
while (!”bye”.equals(line = System.in.readLine())){
serverOut.println(line);
System.out.println(serverIn.readline());
}
serverOut.close(); serverIn.close(); server.close();
} catch (Exception e) { System.err.println(e); }
}
}
Lecture K – Advanced Java API
Slide 8 of 36.
Browsers, HTTP daemons, and applets
user requests a page
browser requests the page
from the HTTPD
the HTTPD returns
the page
request the code
code of the applet
returns the code
HTTPD
application
Browser
Disk
Lecture K – Advanced Java API
Slide 9 of 36.
Lecture K – Advanced Java API
Unit K1 - Communication
Lecture K – Advanced Java API
Slide 10 of 36.
Lecture K – Advanced Java API
Unit K2 – Threads
Lecture K – Advanced Java API
Slide 11 of 36.
Multi-threaded programming
• Often we want to write our program as a set of several
tasks that are executed concurrently
• Advantages:




Corresponds better to program logic
Parallelism if multiple processors are available
Parallelism with I/O
Timing
Lecture K – Advanced Java API
Slide 12 of 36.
Threads in Java
• Java uses threads to execute tasks
• A Thread is an object that is capable of executing a
single task
• The Java system automatically creates a thread for
the main program (method main() of your class)
• It also creates other threads


Garbage collection thread
When GUI is used, a GUI thread
• You can create and run more threads
• To write a thread you need to implement the interface
Runnable – implement the run() method.
• One way to do this is to subclass Thread
Lecture K – Advanced Java API
Slide 13 of 36.
A simple Thread
public class MyThread extends Thread {
public void run() {
for(int i=0; i<100000; i++)
System.out.println("A:"+i);
}
}
public class MyProg {
static public void main(String[] args) {
Thread t = new MyThread();
t.start();
for(int j=0; j<100000; j++)
System.out.println("B:"+j);
}
}
Lecture K – Advanced Java API
Slide 14 of 36.
Clocks
public class Clock extends Thread {
private int delay;
// in mSec
private String message;
public Clock(int d, String m){
delay = d*1000;
message = m;
}
public void run() {
while(true) {
System.out.println(message);
try {
sleep(delay)
} catch(InterruptedException e) {}
}
}
}
public class MyProg {
public static void main (String args[]) {
Thread c1=new Clock(7,"A"); Thread c2=new Clock(9,"B");
c1.start();
c2.start();
}
}
Lecture K – Advanced Java API
Slide 15 of 36.
Thread Life Cycle
Ready queue
start()
Newly created
threads
Currently executed
thread
Thread blocks
Thread becomes ready
Blocked threads
Lecture K – Advanced Java API
Slide 16 of 36.
Ready vs. Blocked threads
• A Threads can become blocked if it:





Waits for I/O
Its suspend() method is called
Sleeps using Thread.sleep() method
Calls a wait() method on some object
Tries to enter a critical section whose lock is already acquired
• It becomes ready again when, respectively,





I/O completes
Its resume() method is called
Sleeping time has elapsed
A notify() method was called on the object for which it was waiting
The lock is released by the holder
Lecture K – Advanced Java API
Slide 17 of 36.
Scheduling
Thread A
ready
waiting
context
switch
Thread B
ready
context
switch
context
switch
waiting
I/O request
Local disk
Lecture K – Advanced Java API
Slide 18 of 36.
Animation
public class AnimationApplet extends Applet {
private Image[] images;
private int index;
private static long DELAY = 100;
boolean isActive;
public void init() {
images = getImages(); index = 0;
}
public void paint(Graphics g) {
g.drawImage(images[index], 0, 0,
getSize().width, getSize().height, this);
}
public void start() {
isActive = true;
new AnimationTask.start();
}
public void stop() { isActive = false; }
// inner class AnimationTask on next slide
}
Lecture K – Advanced Java API
Slide 19 of 36.
AnimationTask
class AnimationTask extends Thread {
public void run() {
while(isActive) {
try {
sleep(DELAY);
} catch(InterruptedException ie) {}
index = (index+1)%images.length;
repaint();
}
}
Lecture K – Advanced Java API
Slide 20 of 36.
Critical sections
• Each thread has its private run-time stack.
• If two threads execute the same method, each will have
its own copy of the local variables that the methods uses
• However, all threads see the same heap – i.e. they share
all objects.
• Two different threads can act on the same object (or
same static fields) concurrently
• This can lead to some problems...
Lecture K – Advanced Java API
Slide 21 of 36.
Critical Section in BankAccount
import java.io.*;
public class FirstLine {
public static void main(String[] args){
String name = args[0];
try {
BufferedReader file =
new BufferedReader(new FileReader(name));
String line = file.readLine();
System.out.println(line);
} catch (FileNotFoundException e) {
System.out.println(“File not found: “ + name);
} catch (IOException e) {
System.out.println(“Problem: ” + e);
}
}
}
Lecture K – Advanced Java API
Slide 22 of 36.
The problem with Concurrent Access
balance
10
SomeThread
AnotherThread
read balance (10)
compute 110=10+100
read balance (10)
compute 210=10+200
write balance (210)
210
write balance (110)
110
Lecture K – Advanced Java API
Slide 23 of 36.
Synchronized keyword
• In order to prevent concurrent execution of a critical
section by more than one thread, we use the
synchronized keyword.
• A thread can not enter a synchronized method of an
object if any other thread is inside a synchronized method
of the same object.
• A thread entering a synchronized methods acquires a
lock on the object, and releases it when it exits.
public class BankAccount {
private float balance;
public synchronized void deposit(float amount) {
balance = balance + amount;
}
// …
}
Lecture K – Advanced Java API
Slide 24 of 36.
Critical sections
t3
t2
t1
deposit()
Lecture K – Advanced Java API
Slide 25 of 36.
More Synchronization
• Synchronization between threads or processes is a
complicated issue.
• Some concerns:


Deadlock: two threads are waiting for each other to exit from a
method and so both block
Livelock: some thread that wants to work always gets blocked by
others
• Java also has a synchronized statement that allows
synchronization of a block of code
• Objects in Java have wait() and notify() methods for
explicit synchronization by the programmer
Lecture K – Advanced Java API
Slide 26 of 36.
Lecture K – Advanced Java API
Unit K1 - Threads
Lecture K – Advanced Java API
Slide 27 of 36.
Lecture K – Advanced Java API
Unit K2 – Collections Library Basic Interfaces
Lecture K – Advanced Java API
Slide 28 of 36.
Collections Library Basic Interfaces
Lecture K – Advanced Java API
Slide 29 of 36.
Collection API
public interface Collection {
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element);
// Optional
boolean remove(Object element); // Optional
Iterator iterator();
boolean addAll(Collection c);
Object[] toArray();
……
// Optional
}
Lecture K – Advanced Java API
Slide 30 of 36.
Using a Set
import java.util.*;
public class FindDups {
public static void main(String args[]) {
Set s = new HashSet();
for (int i=0; i<args.length; i++)
if (!s.add(args[i]))
System.out.println("Duplicate: " + args[i]);
System.out.println(s.size() +
" distinct words detected:" + s);
}
}
}
Lecture K – Advanced Java API
Slide 31 of 36.
List API
public interface List extends Collection {
Object get(int index);
Object set(int index, Object element); // Optional
void add(int index, Object element);
// Optional
Object remove(int index);
// Optional
int indexOf(Object o);
List subList(int from, int to);
// …
}
Lecture K – Advanced Java API
Slide 32 of 36.
Map API
public interface Map {
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
public Set keySet();
public Collection values();
// ……
}
Lecture K – Advanced Java API
Slide 33 of 36.
Using a Map
Map m = new HashMap();
m.put(“One”,”Ehad”);
m.put(“Two”,”Shnaim”)
//…
String s = (String) m.get(“Seven”);
Lecture K – Advanced Java API
Slide 34 of 36.
Sorting a Collection
import java.util.*;
public class Sort {
public static void main(String args[]) {
List l = new ArrayList(args);
Collections.sort(l);
System.out.println(l);
}
}
Lecture K – Advanced Java API
Slide 35 of 36.
Lecture K – Advanced Java API
Unit K1 – Collections Library Basic Interfaces
Lecture K – Advanced Java API
Slide 36 of 36.