Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Threads
- - A `thread` is a unit of execution
- - They run in parallel, different tasks associated with them
- - Efficient use of resources
- - Operating System divides processing time among the threads
- - Extend the thread class
- - Provides more flexibility
- - Methods
- public void start() // invokes run on a thread object
- public void run() // When it is executing
- public final void setName(String name) // Give thread a name
- public void setPriority(int priority) // Gives thread priorities 1-10
- public final void setDaemon(boolean b)
- public final void join()// Current thread invokes this method on a second thread
- public final void interrupt() // Interrupts current thread
- public void isAlive() // Whether the thread is running or not
- ### Priorities
- - Cannot guarantee execution order
- ### Life Cycle of Threads
- - New Thread ⇒ New: start() ⇒ Runnable: run() ⇒ Running: sleep() / wait() ⇒ Waiting ⇒ Terminates / Dead
- - Running ⇒ Terminates
- - In waiting, a thread could be waiting for a resource other threads are using
- - Timed waiting
- ### Threads Project
- - Take large database
- - Create 8 threads; different functionalities
- ### Sychronization
- - Example:
- - A program that processes deposits and withdrawals
- - 2 Threads & 2 Variables
- - One variable is transaction name
- - One variable is amount
- - Uses monitors and locks
- - A `monitor` is a protective wrapper around code
- - Monitor will use `locks`
- Struct A {
- A1(A a){
- int value;
- a.value = a.value-1;
- Queue<process> q
- if(a.value < 0){
- // log
- q.push(p);
- q.block();
- }
- if(a.value < 1){
- //logic
- a.pop();
- a.wakeup();
- }else{
- return;
- }
- }
- A2(A1 a){
- a.value = a.value+1;
- if(a.value < 1){
- // logic
- q.pop();
- q.wakeup();
- }
- }
- # Lock Interface
- - This is better than synchronization
- - Guarantee of the sequence you are trying to produce
- - No timeout
- - Lock() and Unlock()
- - Can be called in different methods
- - Important Methods in Lock class
- - Lock()
- - Unlock()
- - public boolean TryLock()
- - Determine if you can put a lock on it; checks if lock is present or not
- - LockInterruptibility()
- - Some algorithms for traversing data structures that are concurrently accessed
- - "Hand over Hand"
- - Chain locking
- - Acquire ⇒ Release ⇒ Acquire next
- - Non blocking attempt to acquire a lock
- - TryLock()
- - Attempt to acquire a lock that can be interrupted
- - LockInterruptibility
- - `Re-entrant Lock` enables many reads, but only one write at any given time
- - Can lock and unlock in different scopes
- Lock l
- l.lock();
- try{
- // access that is protected by this lock
- }finally{
- // l.unlock();
- }
- ### Starvation vs. Deadlock
- - `Starvation` may happen if a process requires a resource for execution that is never allotted.
- - Faulty resource allocation decision
- - Low priority process may wait forever if a higher priority process monopolies what is needed
- - `Deadlock` happens when one thread holds a resource that the other one needs and vice versa
- ### Fork / Join
- - Both can break a task into smaller tasks for processing
- - Smaller tasks are independent
- - The `fork` part is the smaller broken up tasks
- - `Join` will take the results from the fork and combine them into one.
- ### Condition Interface
- - Provides a thread the ability to suspend it's new condition execution until a condition is true.
- public void await() // Thread waits until a signal or interrupted
- public boolean await(long time, Time unit) // same as ^ or waiting until time elapsed
- public long await Interruptibility() // Thread waits until signalled
- public void signalled() // wake up a thread that is waiting
- public void signalAll() // wakes up all threads that are waiting
- public void awaitUntil() // Specified deadline has passed ll
- ### Low Level Concurrency
- - Includes
- - Synchronized
- - Can lead to performance issues
- - Volatile
- - Wait()T
- - Notify()
- - NotifyAll()
- - All those methods are not easy to use
- - Easy get deadlock, starvation, and brace conditions
- ### High Level Concurrency
- - Common choice for developers vs. low level
- - Use:
- - Semaphores
- - Thread pools
- - Specify the maximum amount of threads that the application will use
- - Executor Service
- - fixedPool = Executors new FixedThreadPool(int numOfThreads);
- - Maximum of numOfThreads will be active
- - If more than 2 threads are specified-extra threads put in a queue
- - `Executor` is any object capable of executing a task
- - Cannot be shutdown
- - Cannot be canceled
- - Exception methods in executor class:
- - boolean awaitTermination(long timeout, TimeUnit)
- - Block the calling thread until all the tasks have completed their execution
- - Shutdown request, timeout occurs, current thread is interrupted
- - boolean shutdown()
- - void shutdown()
- - orderly shutdown
- # Mutual Exclusion
- - No more than 1 thread can be in its `critical section` at any given time
- - A thread which dies in its critical non section will not affect other threads ability to continue
- - No deadlock
- - If a thread wants to enter critical section: it should be allowed to do so
- - No saturation
- - Threads not forced into a lock step execution of a critical section
- # Dekker's Algorithm
- - First solution of critical section problem
- - Many versions (up to 5)
- - 5th version - most efficient
- - Solution to critical section problem
- - Mutual exclusion, progress, bounded waiting
- # Flavored Thread Motion
- - Used to determine entry into critical section
- - Avoided deadlock
- - No indefinite postponement
- main(){
- int flavoredThread = 1;
- boolean thread1WantsToEnter = false, thread2WantsToEnter = false;
- Thread1(){
- do{
- thread1WantstoEnter=true;
- while(thread2WantsToEnter){
- if(flavoredThread == 2){
- thread1WantsToEnter=false;
- while(flavoredThread==2){
- thread1WantsToEnter=true;
- }
- }
- }
- }
- }
- }
- $$S = \frac{1}{(1-p)(\frac{p}{s})}$$
- - p = part improved, process
- - s = performance
- - p = 30%
- - s = double
- # Synchronized vs. Re-entrant Lock
- - `Synchronized` the implicit lock is given when you enter the block - automatic
- - Lock is released when thread leaves the block
- - `Re-entrant` Lock() and Unlock()
- - Synchronized is more rigid when multiple locks are acquired
- - Release is in opposite order
- - Re-entrant more flexible
- - Most functionality to a user
- - Fairness:
- - Synchronized: any waiting thread can acquire the lock
- - Can lead to stravationo
- - Re-entrant class has a constructor ⇒ boolean
- - Pass it as true, leads to threads waiting the longest are handled first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement