+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Java Tutorials - Concurrency
1. Java Tutorials - Concurrency
Process - self-contained execution environment
Thread - lightweight processes, shares process’
memory and open files
Main Thread - creates the additional threads
2. Defining and Starting a Thread - Provide a Runnable object
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
3. Defining and Starting a Thread - Subclass Thread
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
4. Thread
sleep() - Causes the current thread to suspend execution for a specified period
t.join() - causes the current thread to pause execution until t's thread terminates
5. Thread Errors
Thread Interference - happens when two operations (consisting of multiple
steps), running in different threads, but acting on the same data, and the
sequences of steps overlap.
Memory consistency errors - different threads have inconsistent views of what
should be the same data
Synchronization helps prevents thread errors
6. Liveness and Liveness Problems
Liveness - A concurrent application's ability to execute in a timely manner
Problems:
Deadlock - a situation where two or more threads are blocked forever, waiting for each other
Starvation - a thread is unable to gain regular access to shared resources and is unable to make
progress. Shared resources are made unavailable for long periods by "greedy" threads.
Livelock - threads are not blocked - they are simply too busy responding to each other to resume work.
Example: two people walking towards each other in a corridor, when one person goes to the left, the other
goes to the right, and vice-versa
7. Immutable Objects
- state cannot change after it is constructed
- Maximum reliance on immutable objects is widely accepted as a sound
strategy for creating simple, reliable code.
- cannot be corrupted by thread interference or observed in an inconsistent
state.
8. Strategy for Defining Immutable Objects
1. Don’t provide setter methods
2. Make all fields final and private
3. Don’t allow subclasses to override methods
- Declare class as final
- Make constructor private, construct instances in factory methods
4. Don’t allow instance fields to be changed
- Don’t provide methods that modify the mutable objects
- Don’t share references to mutable objects. Never store references to external, mutable objects passed to the
constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal
mutable objects when necessary to avoid returning the originals in your methods.
9. High Level Concurrency Objects
Lock Objects
Executors - separate thread management from the rest of the application
Concurrent Collections
Atomic Variables
ThreadLocalRandom
10. java.util.concurrent Executor Interfaces
Executor - supports launching new tasks, executes submitted Runnable tasks
ExecutorService - extends Executor, manages termination, produces Futures for
tracking progress of asynchronous tasks
ScheduledExecutorService - schedule commands after a delay, or periodically
11. Thread Pools - Consists of Worker Threads
- Using worker threads minimizes the overhead due to thread creation
Fixed Thread Pools
- always has a specified number of threads running
- if a thread is terminated while it is still in use, it is automatically replaced
with a new thread
- Degrades gracefully: the application will not be servicing requests as quickly
as they come in, but it will be servicing them as quickly as the system can
sustain
12. Fork/Join Framework
- ExecutorService implementation that helps take advantage of multiple
processors
- designed for work that can be broken into smaller pieces recursively
- The goal is to use all the available processing power to enhance the
performance of the application
- distributes tasks to worker threads in a thread pool
- uses a work-stealing algorithm: Worker threads that run out of things to do
can steal tasks from other threads that are still busy
- Uses ForkJoinPool class to execute ForkJoinTask processes
13. Fork/Join Pseudocode
if (my portion of the work is small enough)
do the work directly
else
split my work into two pieces
invoke the two pieces and wait for the results
15. Atomic Variables java.util.concurrent.atomic
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}
16. java.util.concurrent.ThreadLocalRandom
- random number generator isolated to the current thread
- As contrasted to the global java.util.Random
- ThreadLocalRandom.current().nextX(...)
- Consider instead using SecureRandom in security-sensitive applications