15 Java Multithreaded Programming
15 Java Multithreaded Programming
Multithreaded
Programming in Java
Originals of slides and source code for examples: http://courses.coreservlets.com/Course-Materials/java.html
Also see Java 8 tutorial: http://www.coreservlets.com/java-8-tutorial/ and many other Java EE tutorials: http://www.coreservlets.com/
Customized Java training courses (onsite or at public venues): http://courses.coreservlets.com/java-training.html
Overview
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
• Second, add tasks to the list (three options)
– Make a separate class that implements Runnable.
• Make instances of this class and start threading via
taskList.execute(new MySeparateRunnableClass(…))
– Have your existing class implement Runnable.
• Start threading via taskList.execute(this)
– Use an inner class.
• taskList.execute(new MyInnerRunnableClass(…))
8
© 2015 Marty Hall
Approach One:
Separate Classes that
Implement Runnable
Customized Java EE Training: http://courses.coreservlets.com/
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
9 Developed and taught by well-known author and developer. At public venues or onsite at your location.
13
14
Thread Mechanism One: Results
pool-1-thread-1: 0
pool-1-thread-2: 0
pool-1-thread-3: 0
pool-1-thread-2: 1
pool-1-thread-2: 2
pool-1-thread-1: 1
pool-1-thread-3: 1
pool-1-thread-2: 3
pool-1-thread-3: 2
pool-1-thread-1: 2
pool-1-thread-1: 3
pool-1-thread-1: 4
pool-1-thread-3: 3
pool-1-thread-2: 4
pool-1-thread-1: 5
15
18
Review of Interfaces: Benefits
• Class can be treated as interface type
– public interface Shape {
public double getArea();
}
– public class Circle implements Shape { … }
– public class Rectangle implements Shape { … }
Shape[] shapes =
{ new Circle(…), new Rectangle(…) … };
double sum = 0;
for(Shape s: shapes) {
sum = sum + s.getArea(); // All Shapes have getArea
}
19
23
24
Thread Mechanism Two:
Results
pool-1-thread-3: 0
pool-1-thread-1: 0
pool-1-thread-2: 0
pool-1-thread-2: 1
pool-1-thread-3: 1
pool-1-thread-3: 2
pool-1-thread-1: 1
pool-1-thread-2: 2
pool-1-thread-3: 3
pool-1-thread-2: 3
pool-1-thread-1: 2
pool-1-thread-3: 4
pool-1-thread-1: 3
pool-1-thread-2: 4
pool-1-thread-1: 4
25
29
31
You can also use anonymous inner classes. This is not different enough to warrant a separate
33 example here, especially since we showed examples in the section on event handling.
34
Thread Mechanism Three:
Results
pool-1-thread-2: 0
pool-1-thread-1: 0
pool-1-thread-3: 0
pool-1-thread-3: 1
pool-1-thread-1: 1
pool-1-thread-1: 2
pool-1-thread-2: 1
pool-1-thread-3: 2
pool-1-thread-3: 3
pool-1-thread-1: 3
pool-1-thread-1: 4
pool-1-thread-1: 5
pool-1-thread-2: 2
pool-1-thread-2: 3
pool-1-thread-2: 4
35
Preview of Approach
Four: Lambda
Expressions
Customized Java EE Training: http://courses.coreservlets.com/
Java 7, Java 8, JSF 2, PrimeFaces, Android, JSP, Ajax, jQuery, Spring MVC, RESTful Web Services, GWT, Hadoop.
37 Developed and taught by well-known author and developer. At public venues or onsite at your location.
Preview of Lambdas
• Anonymous inner class
taskList.execute(new Runnable() {
@Override
public void run() {
doSomeTask(…);
}
});
• Lambda equivalent
taskList.execute(() -> doSomeTask(…));
Summary of
Approaches
41
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
42 }} give a specific example of this code applied to making an HTTP server.
ConnectionHandler.java
public class ConnectionHandler implements Runnable {
private Socket socket;
public RaceConditionsApp() {
ExecutorService taskList;
taskList = Executors.newFixedThreadPool(POOL_SIZE);
for (int i=0; i<POOL_SIZE; i++) {
taskList.execute(this);
}
}
45
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
47 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!
48
Arbitrating Contention for
Shared Resources
• Synchronizing a section of code
synchronized(someObject) {
code
}
Helpful Thread-Related
Methods
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.
• submit, invokeAny, invokeAll
– Variations that use Callable instead of Runnable. See next
slide on Callable.
54
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
• Example: you have a list of links from a Web page and
want to check status (404 vs. good). Submit them to a task
queue to run concurrently, then invokeAll will let you see
55
return values when all links are done being checked.
Lower-Level Threading
• Use Thread.start(someRunnable)
– Implement Runnable, pass to Thread constructor, call start
• Thread t = new Thread(someRunnable);
• t.start();
– About same effect as taskList.execute(someRunnable), except
that you cannot put bound on number of simultaneous threads.
– Mostly a carryover from pre-Java-5 days; still widely used.
• Extend Thread
– Put run method in Thread subclass, instantiate, call start
• SomeThread t = new SomeThread(…);
• t.start();
– A holdover from pre-Java-5; has little use in modern Java
applications.
56
© 2015 Marty Hall
Advanced Topics
...
}
doCleanup();
}
public OuterClassName {
public void someMethod() {
...
taskList.execute(new SomeHandler(...));
}
Synchronization Solutions
• Solution 2: synchronize on the shared data
public void doSomeOperation() {
synchronized(someSharedObject) {
accessSomeSharedObject();
}
}
• Note that if you use “synchronized” for a static method, the lock
is the corresponding Class object, not this
62
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();
}
}
...
}
Wrap-Up
Summary
• Basic approach
ExecutorService taskList =
Executors.newFixedThreadPool(poolSize);
• Three variations
– taskList.execute(new SeparateClass(…));
– taskList.execute(this); Really four variations, with lambdas being
– taskList.execute(new InnerClass(…)); the fourth. But lambda expressions are not
covered in detail yet.
Questions?
More info:
http://courses.coreservlets.com/Course-Materials/java.html – General Java programming tutorial
http://www.coreservlets.com/java-8-tutorial/ – Java 8 tutorial
http://courses.coreservlets.com/java-training.html – Customized Java training courses, at public venues or onsite at your organization
http://coreservlets.com/ – 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
Many additional free tutorials at coreservlets.com (JSF, Android, Ajax, Hadoop, and lots more)