15 Java Multithreaded Programming PDF
15 Java Multithreaded Programming PDF
Multithreaded
Programming in Java
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/java.html
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
3
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Courses
taught JSP,
by coreservlets.com
experts
(edited by
Marty) Web Services, Hadoop, Android.
Java,
JSF 2, developed
PrimeFaces,and
HTML5,
Ajax, jQuery, Spring,
Hibernate,
RESTful
Spring, Hibernate/JPA, GWT, Hadoop, HTML5, RESTful Web Services
Agenda
Why threads?
Basic approach
Make a task list with Executors.newFixedThreadPool
Add tasks to list with taskList.execute(someRunnable)
Related topics
Race conditions and synchronization
Helpful Thread-related methods
Advanced topics in concurrency
5
Overview
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
6
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Convenience
A clock icon
Multi-client applications
HTTP Server, SMTP Server
Cons
7
Steps for
Concurrent Programming
First, make a task list
ExecutorService taskList =
Executors.newFixedThreadPool(poolSize);
The poolSize is the maximum number of simultaneous threads.
For many apps, it is higher than the number of tasks, so each
task has a separate thread.
There are other types of thread pools, but this is simplest
Approach One:
Separate Classes that
Implement Runnable
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
9
Developed and taught by well-known author and developer. At public venues or onsite at your location.
11
14
0
0
0
1
2
1
1
3
2
2
3
4
3
4
5
15
Passing arguments
If you want different threads to do different things, you pass args to
constructor, which stores them in instance variables that run
method uses
Disadvantages
Hard to access main app.
If you want to call methods in main app, you must
Pass reference to main app to constructor, which stores it
Make methods in main app be public
16
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Circle class
public class Circle implements Shape {
public double getArea() { some real code }
}
Note
You can implement many interfaces
public class MyClass implements Foo, Bar, Baz { }
18
Bad
If run accesses any shared data (instance variables), you have
to worry about conflicts (race conditions)
Very hard to pass arguments, so each task starts off the same
20
23
24
0
0
0
1
1
2
1
2
3
3
2
4
3
4
4
25
Disadvantages
Tight coupling
run method tied closely to this application
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Example
public class OuterClass {
private int count = ;
public void foo() {
InnerClass inner = new InnerClass();
inner.bar();
}
private class InnerClass {
public void bar() {
doSomethingWith(count);
}
}
28
29
31
// Inner class
32
You can also use anonymous inner classes. This is not different enough to warrant a separate
example here, especially since we showed examples in the section on event handling.
33
0
0
0
1
1
2
1
2
3
3
4
5
2
3
4
Disadvantages
Tight coupling
run method tied closely to this application
Summary of
Approaches
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
36
Developed and taught by well-known author and developer. At public venues or onsite at your location.
MultithreadedServer.java
(Continued)
public void listen() {
int poolSize =
100 * Runtime.getRuntime().availableProcessors();
ExecutorService taskList =
Executors.newFixedThreadPool(poolSize);
try {
ServerSocket listener = new ServerSocket(port);
Socket socket;
while(true) { // Run until killed
socket = listener.accept();
taskList.execute(new ConnectionHandler(socket));
}
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
ioe.printStackTrace();
The later sections on network programming will give details on ServerSocket and Socket.
}
But the basic idea is that the server accepts a connection and then puts it in the queue of
tasks so that it can be handled in a background thread. The network servers section will
}}
give a specific example of this code applied to making an HTTP server.
39
ConnectionHandler.java
public class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
handleConnection(socket);
} catch(IOException ioe) {
System.err.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
public void handleConnection(Socket socket)
throws IOException{
// Do something with socket
}
}
40
Developed and taught by well-known author and developer. At public venues or onsite at your location.
42
Expected Output
Set
Set
Set
Set
Set
Set
Set
Set
Set
Set
44
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
to
to
to
to
to
to
to
to
to
to
0
1
2
3
4
5
6
7
8
9
Set
Set
Set
Set
Set
Set
Set
Set
Set
Set
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
currentThreadNum
to
to
to
to
to
to
to
to
to
to
0
1
2
3
4
5
5
7
8
9
In older Java versions, the error showed up rarely: only about 1 in 50 times. In newer Java
versions (that give each thread a smaller time slice and where the underlying computer is
faster), it happens often. There is another version of the code in the Eclipse project that even on
new Java versions, manifests the problem only about 1 in 50 times.
This solution does not fix the problem. In some ways, it makes it worse!
45
Normal interpretation
Once a thread enters that section of code, no other thread
can enter until the first thread exits.
Stronger interpretation
Once a thread enters that section of code, no other thread
can enter any section of code that is synchronized using
the same lock object
47
Helpful Thread-Related
Methods
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
49
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Thread.sleep(milliseconds)
Puts calling code to sleep. Useful for non-busy waiting in
all kinds of code, not just multithreaded code. You must
catch InterruptedException, but you can ignore it:
try { Thread.sleep(someMilliseconds); }
catch (InterruptedException ie) { }
someThread.getName(), someThread.getId()
Useful for printing/debugging, to tell threads apart
50
Methods in ExecutorService
Class
execute(Runnable)
Adds Runnable to the queue of tasks
shutdown
Prevents any more tasks from being added with execute (or
submit), but lets current tasks finish.
shutdownNow
Attempts to halt current tasks. But author of tasks must have
them respond to interrupts (ie, catch InterruptedException), or
this is no different from shutdown.
awaitTermination
Blocks until all tasks are complete. Must shutdown() first.
Callable
Runnable
run method runs in background. No return values, but
run can do side effects.
Use execute to put in task queue
Callable
call method runs in background. It returns a value that
can be retrieved after termination with get.
Use submit to put in task queue.
Use invokeAny and invokeAll to block until value or
values are available
52
Lower-Level Threading
Use Thread.start(someRunnable)
Implement Runnable, pass to Thread constructor, call start
Thread t = new Thread(someRunnable);
t.start();
Extend Thread
Put run method in Thread subclass, instantiate, call start
SomeThread t = new SomeThread();
t.start();
Advanced Topics
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
54
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Executors.newScheduledThreadPool
Lets you define tasks that run after a delay, or that run
periodically. Replacement for pre-Java-5 Timer class.
Executors.newCachedThreadPool
Optimized version for apps that start many short-running
threads. Reuses thread instances.
Executors.newSingleThreadExecutor
Makes queue of tasks and executes one at a time
55
Stopping a Thread
public class SomeTask implements Runnable {
private volatile boolean running;
public void run(){
running = true;
while (running) {
...
}
doCleanup();
}
for() {
taskList.execute(new SomeHandler(...));
}}}
57
Synchronization Solution
Solution 1: synchronize on outer class
If your handler is an inner class, not a separate class
public OuterClassName {
public void someMethod() {
...
taskList.execute(new SomeHandler(...));
}
private class SomeHandler implements Runnable {
public void run() { ... }
public void doSomeOperation() {
synchronized(OuterClassName.this) {
accessSomeSharedObject();
}
}
58
Synchronization Solutions
Solution 2: synchronize on the shared data
public void doSomeOperation() {
synchronized(someSharedObject) {
accessSomeSharedObject();
}
}
Synchronization Solution
(Continued)
Solution 4: synchronize on arbitrary object
public class SomeHandler implements Runnable{
private static Object lockObject
= new Object();
...
public void doSomeOperation() {
synchronized(lockObject) {
accessSomeSharedObject();
}
}
...
}
61
notify/notifyAll
Wakes up all threads waiting for the lock
A notified thread doesnt begin immediate execution, but is placed
in the runnable thread queue
http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
63
Developed and taught by well-known author and developer. At public venues or onsite at your location.
References
Books
Java Concurrency in Practice (Goetz, et al)
Chapter 10 (Concurrency) of Effective Java, 2nd Ed
(Josh Bloch)
Effective Java is the all-time best Java practices book
Online references
Lesson: Concurrency (Oracle Java Tutorial)
http://docs.oracle.com/javase/tutorial/essential/concurrency/
Summary
Basic approach
ExecutorService taskList =
Executors.newFixedThreadPool(poolSize);
Three variations
taskList.execute(new SeparateClass());
taskList.execute(this);
taskList.execute(new InnerClass());
65
synchronized(referenceSharedByThreads) {
getSharedData();
modifySharedData();
}
doOtherStuff();
Questions?
JSF 2, PrimeFaces, Java 7 or 8, Ajax, jQuery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT,
and other Java EE training. Also see the Java 8 tutorial and general Java programming tutorial.
Developed and taught by well-known author and developer. At public venues or onsite at your location.