Professional Documents
Culture Documents
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. tutorial Available at public venues, Customized or customized Java EE Training: versions http://courses.coreservlets.com/ can be held on-site at your Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. organization. Contact hall@coreservlets.com for details. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
Why threads? Basic approach
Make a task list with Executors.newFixedThreadPool Add tasks k to li list with i h taskList.execute(someRunnable) kLi ( R bl )
Related topics
Race conditions and synchronization Helpful Thread-related methods Advanced topics in concurrency
5
Overview
Customized Java EE Training: http://courses.coreservlets.com/
6
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. 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
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
11
0 0 0 1 2 1 1 3 2 2 3 4 3 4 5
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
15
Pass reference to main app to constructor, which stores it Make methods in main app be public
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. 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 bli class l M Cl MyClass i l implements t F Foo, B Bar, Baz B {}
17
Bad
If run accesses any shared h dd data t (i (instance t variables), i bl ) you h have to worry about conflicts (race conditions) Very hard to pass arguments, so each task starts off the same
19
22
23
0 0 0 1 1 2 1 2 3 3 2 4 3 4 4
Disadvantages
Tight coupling
run method tied closely to this application
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Example
27
28
29
30
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.
32
0 0 0 1 1 2 1 2 3 3 4 5 2 3 4
Disadvantages
Tight g coupling p g
run method tied closely to this application
Summary of Approaches
Customized Java EE Training: http://courses.coreservlets.com/
35
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. 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.
38
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 }
39
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Occasional Output
Setting Counter Setting Setting Counter Counter Counter Counter C Counter t Counter Counter Counter Counter Counter Counter Counter Cou te Counter Counter currentNum to 0 0: 0 currentNum to 1 currentNum to 1 0: 1 1: 0 1: 0 0: 2 0 0: 3 1: 1 0: 4 1: 1 1: 2 1: 3 1: 2 1: : 3 1: 4 1: 4
44
45
Normal interpretation
Once a thread enters the code, code no other thread can enter until the first thread exits.
If two pieces of code say synchronized(blah), the question is if the blahs are the same object instance.
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Thread.sleep(milliseconds)
P Puts calling lli code d to sleep. l Useful U f l for f non-busy b waiting i i in i all kinds of code, not just multithreaded code. You must catch InterruptedException, p p but y you can ignore g it:
try { Thread.sleep(someMilliseconds); } catch (InterruptedException ie) { }
shutdown
Prevents any more tasks from being added with execute (or submit), but lets current tasks finish.
shutdownNow
Attempts p 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 execute to put in task queue
Callable
call method runs in background. g It returns a value that can be retrieved after termination with get. Use submit to put in task queue. Use U i invokeAny k A and di invokeAll k All to block bl k until il value l or values are available
Example: p y you have a list of links from a Web p page g and want to check status (404 vs. good). Submit them to a task queue to run concurrently, then invokeAll will let you see return values when all links are done being checked.
51
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 M l a carryover f from pre-Java-5 J 5 days; d still ill widely id l used. d
Extend Thread
Put run method in Thread subclass, subclass instantiate instantiate, call start
SomeThread t = new SomeThread(); t.start();
Advanced Topics
Customized Java EE Training: http://courses.coreservlets.com/
53
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. 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 pre-Java-5 Java 5 Timer Timer class.
Executors.newCachedThreadPool
Optimized version for apps that start many short-running threads Reuses threads. Re ses thread instances. instances
Executors.newSingleThreadExecutor
Makes q queue of tasks and executes one at a time
Stopping a Thread
public class SomeTask implements Runnable { private volatile boolean running; public void run(){ running = true; while (running) { ... } doCleanup(); }
Compilers on multiprocessor systems often C f do optimizations that prevent changes to variables from one thread from being seen by another thread. To guarantee that other threads see your changes, either use synchronized methods, declare the variable volatile, or use AtomicBoolean.
56
public class SomeThreadedClass implements Runnable { public synchronized void doSomeOperation() { accessSomeSharedObject(); } ... public void run() { while(someCondition) { doSomeOperation(); // Accesses shared data doSomeOtherOperation();// // No shared data } } }
Synchronization Solution
Solution 1: synchronize on the shared data
public bli void id doSomeOperation() d S O ti () { synchronized(someSharedObject) { accessSomeSharedObject(); } }
Note that if you synchronize a static method, the lock is the corresponding di Class Cl object, bj t not t this thi
57
Why doesnt this problem usually occur with thread mechanism two (with run method in main class)?
58
59
notify/notifyAll
Wakes up p all threads waiting g for the lock A notified thread doesnt begin immediate execution, but is placed in the runnable thread queue
http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
61
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. 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 alltime best Java practices book
Online references
Lesson: Concurrency (Sun Java Tutorial)
http://java.sun.com/docs/books/tutorial/essential/concurrency/ htt //j /d /b k /t t i l/ ti l/ /
Summary
Basic approach
ExecutorService i taskList k i = Executors.newFixedThreadPool(poolSize);
Three variations
taskList.execute(new SeparateClass()); taskList.execute(this); taskList.execute(new InnerClass());
63
Questions?
Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.