Title: Java Thread and Network Programming
1Java Thread and Network Programming
2Concurrency/Threading
- Pretending to do more than 1 thing at a time.
- Process vs. Thread
- Process Own instance of JVM (Heavyweight)
- Separate address space
- Separate resources
- Threads Run in same JVM (Lightweight)
- Use same address space
- Share same resources
3Threads
- Executes its own code sequentially
- Keeps its own program counter/Stack
- Under control of JVM after start
- Should execute clear atomic task
- Threads impact performance (unless multiple
processors), so use only when necessary
4Java 1.5 New Concurrency Constructs
- See package java.util.concurrent
- Article at
- http//java.sun.com/developer/technicalArticles/J2
SE/concurrency/ - Understanding theory in CS2200
- We just learn mechanics of programming in 2335!
5Life Cycle of a Thread
6Making a Thread in Java
- Preferred Implement the Runnable interface
- public class MyTask implements Runnable
- public void run( )
- //your code here
-
-
- (JDK 1.4) Then create a thread and pass your
Runnable object. - //driver
- Thread t new Thread(new MyTask( ), MyName)
- (JDK 1.4) Then start the thread.
- t.start()
7Java 1.5 Thread Pool
- Creating threads is expensive.
- Let JVM create some threads, keep them around and
use them to execute your Runnable objects. - Java.util.concurrent.ExecutorService can manage
threads - CachedPool
- FixedPool
- ScheduledPool
- (JDK 1.5) Create a thread pool.
- ExecutorService pool Executor.newFixedThreadPool
(5) - (JDK 1.5) Start the thread
- pool.execute(new MyTask())
8Making a Thread in Java (2)
- Alternative Subclass Thread class
- public class MyThread extends Thread
- public void run( )
-
- public MyThread ( String s )
- super(s)
-
-
- Then create the thread and start it
- //in Driver
- MyThread mt new MyThread(My ID)
- mt.start()
9Thread Problems
- Calling run( ) instead of start( ).
- Messing up priorities (if it aint broke, dont
fix it!) - Need to wakeup/terminate a thread?
t.interrupt() (not t.stop()!!!!) - Need to let someone else go? t.yield()
- Need to wait for a thread to finish? t.join()
- Race Conditions use synchronized or new
concurrency constructs (ReentrantLock) to protect
critical parts of your code. - Deadlock await( ), signalAll( ), signal( ), 1.5
constructs - await must have a signalAll/signal somewhere
- signalAll/signal must be after a lock
10GUI and Thread Problems
- Symptom Application stops responding.
- Cause Listener (handler) takes too long.
AWT Event Queue
Mouse/Key Events
Native OS
AWT Event Dispatch Thread
Processes
Your listener code executes in the Event Dispatch
Thread. Long code No events get processed!
11Solutions
- Keep Listener code execution time short
- What if I have a lot to do?
- Make a SwingWorker (download from Sun)
- Use FoxTrot (download from SourceForge)
- Only perform GUI updates (paint etc) from the
event dispatch thread (Swing not thread-safe). - Use
- java.awt.EventQueue.invokeLater(someRunnable )
- java.awt.EventQueue.invokeAndWait(someRunnable)
- (note) javax.swing.SwingUtilities wraps
EventQueue
12Example
public static void main(String args)
//Schedule a job for the event-dispatching
thread //creating and showing this
application's GUI. java.awt.EventQueue.invok
eLater( new Runnable()
public void run()
createAndShowGUI()
)
13Networking
- Talking to other computers
- Two models
- Client/Server
- Peer to Peer
- Communications uses Protocols an agreed upon
format for messages - TCP/IP is standard for internet
- Connection is a host port
14TCP/IP in Java
- Reliable (TCP) (Can test Server with Telnet)
- Socket
- ServerSocket
- Unreliable (UDP)
- DatagramSocket
- Multicast (Usually for Peer to Peer)
- MulticastSocket
- These all block (wait) until data is available to
read.
15Non-blocking IO (nio)
- Can have multiple clients without threads
- Server must maintain all state for every client
- ServerSocketChannel
- SocketChannel
16Remote Method Invocation (RMI)
- Call methods in other processes directly
- Even if other process is on different machine!
- Security Issues make it tough to get up on all
machines - All apps must be Java apps.
- NOT SUPPORTED IN CS2335. Use prohibited on some
labs (like Lab 3).
17Java-Specific Network Libraries
- JSDT Java Shared Data Toolkit
- Building groupware, chat, whiteboards, etc.
- JXTA Java P2P Framework
18Basic Sequence (TCP)
- Server starts up a server socket on a particular
port number and waits for a client to try and
connect - Client creates a socket to a particular host and
port. - Server accepts the connection. Starts a thread
to handle the new client with a dedicated socket. - Server and client send messages over streams
- Client disconnects at end of session
19Most Common Method
- Reliable Connection (TCP)
- Simple Server (1 client at a time)
- public void run( )
- ServerSocket theServer new
ServerSocket(43902) - Socket theClient null
- while (true)
- theClient theServer.accept( )
- handleClient(theClient)
-
Note This handles one client request at a time!
20After Connection
- Can get client information
- theClient.getInetAddress().getHostName()
- Can get streams to interact
- theClient.getInputStream( )
- theClient.getOutputStream( )
- Remember to flush streams
- Typically wrap input in BufferedReader
- Typically wrap output in PrintWriter
21A Simple Client
- We make a socket to connect to host
- Socket s new Socket (localhost, 43902)
- Then we grab the streams just like in the Server
example.
22What about multiple clients
- We have to have the server fire off a thread to
handle each connection. - In our SimpleServer, instead of calling
handleClient method, we have to create a thread
with the handler code, and start that thread up. - After starting the thread, the server can go back
immediately to accepting connections.
23(No Transcript)
24What about complex data?
- So what if we do not want a text-based protocol?
- We can serialize objects across the network
connection, just like strings. - ObjectInputStream / ObjectOutputStream
- All apps must be in Java
25Tricks to ObjectStreams
- When stream first made, Java sends version number
and sync information, therefore - Always open the output stream first and flush
- Then open the input stream. Otherwise the input
will block looking for version info, and there is
none. - When sending many objects, watch out for
buffering problems - Use readUnshared/writeUnshared as opposed to
readObject/writeObject
26Where do I start????
- First have to decide on a PROTOCOL
- What kind of information goes between the
distributed machines? - Typically Data and Commands
- Text Strings (SMTP Example RFC 821)
- Client MAIL FROMwatersr_at_cc.gatech.edu \n
- Server 250 OK \n
- Client QUIT \n
- Server 250 smtp.cc.gatech.edu \n
-
27Protocols
- Text is nice for cross platform, ease of testing
(can use telnet to test servers/clients) - What about binary data?
- MIME / UUENCODE etc.
- Object Serialization
- Restricts you to Java only
- Protocol consists of message objects that are
commands and data. - Must build client/servers in parallel and more
expensive test harness - Binary/Text data transmission is transparent
28Protocols
- How much does the server need to remember between
messages - Stateless servers Server keeps no information,
each client request is atomic Request-Response - State servers Server keeps information about
previous client exchanges. Knows where it is at
any point.
29Protocol Design for Simple Game
- Guess a number, clients connect to a server and
send guesses, server notifies client if they win. - State vs. Stateless
- Important Phases
- Connect / Setup
- Commands
- Data
- Disconnect / Cleanup
30Now we design the client/server
- Need just one client at a time guessing?
- Single thread client/server
- RMI
- Multiple clients guessing at a time?
- Multi threaded server
- RMI
- NIO
- Multiple clients sharing guesses?
- Multicast
- JXTA Peer-to-Peer