Download Thread

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Multi-threading in Java
OOP Tirgul No. 10, 2009
Threads in Java
public class Counter implements Runnable {
public static void main(String[] arg) {
Thread t=new Thread(this);
t.start();
new Thread(Runnable target)
}
Allocates a new Thread object.
package java.lang;
public interface Runnable {
public abstract void run();
}
@Override public void run() {
void start()
for (int i = 0; i < 1000; i++)
Causes this thread to begin execution;
System.out.println(i);
the JVM calls the run method of this thread.
}
}
public class Counter extends Thread {
public static void main(String[] arg) {
Thread t=new Counter();
t.start();
}
@Override public void run() { ... }
}
Alternatives of Thread Implementation
• What are the
advantages of using
Runnable over
extending Thread?
• We often avoid manual
thread creation and use
a Thread Pool – a.k.a.
ExecutorService
Daemon Threads
• Daemon threads are threads that run as
servants for other threads.
• The JVM process ends when only daemon
threads exist.
Thread1
Thread2
Daemon
Thread
Thread3
Use
Daemon
Thread
Taking a Look Inside JVM
VisualVM can be launched from the directory where
JDK is installed. Connect to running Java program and
see what is going on!
https://visualvm.dev.java.net/
Race Condition Example
Avoiding Race Condition
• Thread 2 can change the state before Thread
1 is finished – potential race condition.
• Thread 2 waits – prevents the race condition.
Thread 1
Thread 2
Nonsynchronized
method
Synchronized
method
Thread 1
Thread 2
Synchronized
• Synchronized keyword for methods
– synchronized void add() { … }
– synchronized void remove() { … }
• Synchronized block
– synchronized(object) { … }
• Static synchronized = synchronized(class)
• Synchronized collections:
– Vector, Hashtable,
– Collections.synchronized Collection…
• Synchronization is expensive!
Volatile
public class Example {
public boolean done = true;
public void doItAgain() {
done=true;
}
public synchronized checkDone() {
done = false;
if (done) {
System.out.println(“Done!”);
}
}
}
BUT, another thread might
call the doItAgain() method
before the if statement!
The Java optimizer figures
that this statement is dead will never be executed - and
eliminates it.
Volatile
public class Example {
public volatile boolean done = true;
public void doItAgain() {
To prevent this problem, the
volatile keyword can be
done=true;
added to the variable’s
}
declaration
public synchronized checkDone() {
done = false;
if (done) {
System.out.println(“Done!”);
}
}
}
The Java optimizer will not
make any assumptions here
Achieving Thread Safety
• Immutability
– Integer, String, etc.
– final
– Collections.unmodifiableCollection…
• Guard by locks
– synchronized
– volatile
• Confine changes to single thread
– local variables
– ThreadLocal
Concurrent Collections
• ConcurrentHashMap
– Concurrent (scalable) replacement for Hashtable or
Collections.synchronizedMap
– Allows reads to overlap each other
– Allows reads to overlap writes
– Allows up to 16 writes to overlap
– Iterators don't throw ConcurrentModificationException
• CopyOnWriteArrayList
– Optimized for case where iteration is much more frequent
than insertion or removal
– Ideal for event listeners
Concurrent Collection Performance
Blocking Queues
Extends Queue to provides blocking operations
• Retrieval: take—Wait for queue to become nonempty
• Insertion: put—Wait for capacity to become available
Blocking
Queue
Thread
Thread
take
take
take
Thread
take
Thread
Blocking Queues
Extends Queue to provides blocking operations
• Retrieval: take—Wait for queue to become nonempty
• Insertion: put—Wait for capacity to become available
Blocking
Queue
Thread
Thread
Thread
take
When the queue is empty, the
thread blocks until a resource
is returned to the queue
Thread
Blocking Queues – Log Writer
Producer-Consumer Pattern
• LogWriter example illustrates the producerconsumer pattern
– Ubiquitous concurrency pattern, nearly always relies
on some form of blocking queue
– Decouples identification of work from doing the work
• Simpler and more flexible
• LogWriter had many producers, one consumer
– Thread pool has many producers, many consumers
• LogWriter moves IO from caller to log thread
– Shorter code paths, fewer context switches, no
contention for IO locks → more efficient
Executors
Framework for Asynchronous Execution
• Standardize asynchronous invocation
– Framework to execute Runnable and Callable tasks
• Separate submission from execution policy
– Use anExecutor.execute(aRunnable)
– Not new Thread(aRunnable).start()
• Cancellation and shutdown support
• Usually created via Executors factory class
– Configures flexible ThreadPoolExecutor
– Customize shutdown methods, before/after hooks,
saturation policies, queuing
Executor and ExecutorService
Executors
Executors Example
Futures and Callables
Representing Asynchronous Tasks
Futures Example
Implementing a concurrent cache
More:
Effective Java 2nd edition
Java Concurrency In Practice
http://www.javaconcurrencyinpractice.com/