Class 21 — Monday, November 9
Quiz 9 first. Then the three sections Wednesday did not reach: a thread for each client, four robots that share one count, and names. Last, a way to test what a server answers without running it.
- Refused, or let in and waiting — keyboards down
- A thread for each client
- Four robots — predict first
- One lock for the count
- One name for everybody — predict first
- Names and a lobby
- Answers without a network — keyboards down
NameSession
Today’s work goes in your copy of cmsc-230-threads, beside Wednesday’s EchoServer and EchoClient; if you have neither, they are in Wednesday’s section 1, and so is the note on running two programs at once in IntelliJ.
1. Refused, or let in and waiting
Keyboards down.
On Wednesday, client 2 connected to a server that was busy with client 1. It was let in, and only its answer waited. This server is different: it accepts one client and ends.
import java.io.*;
import java.net.*;
import java.util.*;
// accepts one client, answers its lines, and ends
public class OnceServer {
public static void main(String[] args) throws IOException {
try (ServerSocket server = new ServerSocket(6230);
Socket client = server.accept();
Scanner in = new Scanner(client.getInputStream());
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
while (in.hasNextLine()) {
out.println("echo: " + in.nextLine());
}
}
}
}A client connects to it, talks, and leaves. Then a second client starts.
The second client is refused. On Wednesday, a client was let in by a server that was busy. What is the difference between the two?
Whether a ServerSocket is open on the port. While one is, the system lets every client in and holds it in a queue, and accept() takes the next one out. OnceServer closes its ServerSocket when the first client leaves and the program ends, so nothing is listening and the system refuses.
Wednesday’s client 2 waited for its answer for another reason: the server had one thread, and that thread was inside serve for client 1. Section 2 gives each client a thread of its own.
2. A thread for each client
Pairs. 2.1, then 2.2 if you are done.
2.1 ThreadedEchoServer
A new file: Wednesday’s EchoServer with one change. Instead of calling serve(client) itself, main starts a thread that does, and goes straight back to accept():
A Runnable cannot throw an IOException, so serve now catches it: its try gets a catch (IOException e) that prints e.getMessage(), and throws IOException comes off its first line.
In a comment above main: it never calls join on the threads it starts. Why not?
Done when two clients connected at once each get their echo at once.
2.2 One bad client (if you are done)
If you wrote Wednesday’s CalcServer, make it start a thread for each client the same way. Take Wednesday’s 2.3 catch out of answer for a moment, and from one of two connected clients send ADD two 3. What happens to that client, to the other one, and to the server? Answer in a comment, then put the catch back.
When the section ends: commit and push.
3. Four robots
Keyboards down. Write in the Journal first, then run it.
A server with a thread for each client, counting every line any client sends, and four robot clients that each send it 100,000 lines at once. Two new files in src:
import java.io.*;
import java.net.*;
import java.util.*;
// counts every line from every client; COUNT answers with the count so far
public class CountServer {
static int count;
public static void main(String[] args) throws IOException {
try (ServerSocket server = new ServerSocket(6230)) {
System.out.println("waiting on port 6230");
while (true) {
Socket client = server.accept();
new Thread(() -> serve(client)).start();
}
}
}
// counts one client's lines until it leaves
static void serve(Socket client) {
try (Scanner in = new Scanner(client.getInputStream());
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("COUNT")) {
out.println(count);
} else {
count++;
}
}
} catch (IOException e) {
System.out.println("a client failed: " + e.getMessage());
}
}
}import java.io.*;
import java.net.*;
import java.util.*;
// four robot clients at once, each sending 100,000 lines to CountServer; then
// one more connection asks for the count
public class Robots {
public static void main(String[] args) throws Exception {
Thread[] robots = new Thread[4];
for (int r = 0; r < robots.length; r++) {
robots[r] = new Thread(() -> {
try (Socket s = new Socket("localhost", 6230);
Scanner in = new Scanner(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream(), true)) {
for (int i = 0; i < 100_000; i++) {
out.println("hello");
}
out.println("COUNT");
in.nextLine(); // the server has read all of this robot's lines
} catch (IOException e) {
System.out.println("a robot failed: " + e.getMessage());
}
});
robots[r].start();
}
for (Thread robot : robots) {
robot.join();
}
try (Socket s = new Socket("localhost", 6230);
Scanner in = new Scanner(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream(), true)) {
out.println("COUNT");
System.out.println("the server counted " + in.nextLine() + " lines of 400000");
}
}
}Start
CountServer, thenRobots. How many of the 400,000 lines will the server count? Why?
Fewer. Six runs here counted 396963, 392769, 394152, 383562, 397389 and 394534.
Each client’s thread runs count++ on the one count, and two threads lose each other’s updates, as two threads did in Class 16. The robots are separate connections, but on the server they are threads of one program sharing one field. A server with a thread for each client is a program with many threads, and what its clients share needs a lock.
4. One lock for the count
Pairs. 4.1, then 4.2 if you are done.
4.1 add
Move count++ into a method of its own, static synchronized void add(), so that a test can call it and every client’s thread takes the same lock in it. Which object’s lock is that? COUNT reads count under the same lock.
A synchronized block inside add would work too, but it would cover the whole method anyway: the same lock, held just as long, in more lines.
Your test, in test/CountServerTest.java: set CountServer.count to 0, then four threads each call add() 100,000 times; the count is 400,000.
Done when Robots prints 400000 three runs in a row, and your test is green.
4.2 What the lock costs (if you are done)
Time Robots, System.nanoTime() before the robots start and after the last join, three runs with your lock and three with synchronized taken off add. Can you see the lock in the times? Write the six times and your answer in a comment, then put synchronized back.
When the section ends: commit and push.
5. One name for everybody
Keyboards down. Write in the Journal first, then run it.
A server that gives each client a name: NAME alice answers OK, and HELLO answers hello, alice. Each client has a thread of its own.
import java.io.*;
import java.net.*;
import java.util.*;
// NAME gives this client a name, and HELLO greets it, each client on a thread
// of its own; but the name is one field for every client
public class SharedName {
static String name;
public static void main(String[] args) throws IOException {
try (ServerSocket server = new ServerSocket(6230)) {
System.out.println("waiting on port 6230");
while (true) {
Socket client = server.accept();
new Thread(() -> serve(client)).start();
}
}
}
// answers one client's lines until it leaves
static void serve(Socket client) {
try (Scanner in = new Scanner(client.getInputStream());
PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
while (in.hasNextLine()) {
String[] words = in.nextLine().split(" ");
if (words.length == 2 && words[0].equals("NAME")) {
name = words[1];
out.println("OK");
} else if (words.length == 1 && words[0].equals("HELLO")) {
out.println(name == null ? "ERROR no name yet" : "hello, " + name);
} else {
out.println("ERROR no such command");
}
}
} catch (IOException e) {
System.out.println("a client failed: " + e.getMessage());
}
}
}Client 1 sends NAME alice. Client 2 sends NAME bob. Then client 1 sends HELLO.
What does client 1 get back, and why?
hello, bob, three runs of three here.
name is static: one variable for the whole program, and every client’s thread reads and writes the same one. The last client to say NAME wins, for everybody. A lock would not help, since nothing is lost: the name is wrong because it is shared at all.
A client’s own name belongs to that client’s thread: a local variable in serve, of which each thread has its own. What every client should see, the names of everyone connected, is shared on purpose, and that is the part that needs a lock.
6. Names and a lobby
Pairs. 6.1, then 6.2 if you are done.
6.1 Names
NameServer, with a thread for each client and three commands:
NAME alicegives this client a name, and answersOK.HELLOanswershello, alice, orERROR no name yet.WHOanswers the names of every client connected now, on one line.
A client’s own name belongs to that client alone: a local variable in serve. The names of everyone connected belong to all of them: a class Lobby, with join(name), leave(name) and who(), and one Lobby object that every client’s thread uses. When a client leaves, serve takes its name out.
Your test, in test/LobbyTest.java: two names join, who() lists both, one leaves, and who() lists the other.
6.2 Taken (if you are done)
NAME bob, while a connected client is already bob, answers ERROR bob is taken. join returns false and changes nothing when the name is taken, and true when it adds it.
Your test: two threads each join name0 to name999 into one Lobby; the joins that return true add up to 1,000. Without a lock, ten runs here came to between 1,026 and 1,179.
When the section ends: commit and push.
7. Answers without a network
Keyboards down.
To try NameServer, you start it and connect clients by hand. Its answer to a line depends on two things: the line, and what this client said before, its name. So the answers can move into a class of their own, one object for each client:
// one client's conversation: its own name, and the lobby every client shares
public class NameSession {
private final Lobby lobby;
private String name;
public NameSession(Lobby lobby) { ... }
// the answer to one line from this client
public String answer(String line) { ... }
// takes this client's name out of the lobby, when it leaves
public void leave() { ... }
}The server makes a NameSession for each client, passes it every line, and sends back what it answers. A test does the same, with no server at all.
Which of
NameServer’s variables move intoNameSession, and which stay in the server?
The name moves: it is one client’s, and each NameSession is one client. The Lobby is passed in, the same one to every session, since it is shared. A session knows its own name; only the Lobby knows everyone’s: WHO reads it, and NAME asks it whether a name is taken. The socket, the Scanner and the PrintWriter stay in the server: they are how lines travel, and a test has no use for them.
8. NameSession
Pairs. 8.1, then 8.2 if you are done.
8.1 Moving the answers
Write NameSession, with 6’s three commands in answer. Then NameServer’s serve makes new NameSession(lobby), sends back session.answer(in.nextLine()) for each line, and calls session.leave() after the loop.
Your test, in test/NameSessionTest.java, with no server running: a session that sends NAME alice and then HELLO gets OK and then hello, alice; and HELLO before any NAME answers a line starting with ERROR.
Done when your test is green, and two clients of NameServer still get the answers they got in 6.
8.2 Two sessions, one lobby (if you are done)
Your test: two NameSessions on one Lobby. The second NAME alice is refused; after NAME bob, WHO lists both; after the first session’s leave(), WHO lists only bob.
When the section ends: commit and push.