Week 2 Flashcards
What is Concurrency?
To be able to perform multiple processes at the same time - including the potential interaction between them
What is multiple tasks at the same time sometimes called?
Parallelism
Why are we interested in Concurrency?
- Allowing programs to interact with other systems/ users
- Multi-core Systems
What are Threads?
Treated as Lightweight Processes
Threads exist within a process
Many threads running at same time in a particular process
What is Multi-Threading?
OS can run threads in parallel:
Virtually on a Single Core Processor
Actually on a Multi Core Processor
What is a problem with Threads?
Liveness
Liveness threads refer to a thread safety issue that occurs when a program doesn’t produce a final result
Liveness issues can have serious consequences, such as deadlocks that prevent a program from running further
What are the 2 ways to create Threads in Java?
- Using (and extending) the Thread class
- Using the Runnable interface
What are the 2 Ways to Stop a Thread in Java?
- Setting a flag:
public void run() {
while (!done) {
//…
}
}
Loop will exit (and thread will stop) on the next iteration after done is set to true
- Interrupting:
public void run() {
while (!isInterrupted() ) {
//…
}
}
When isInterrupted() is called for this thread, it will stop
Except that if the thread is sleeping/ waiting will throw InterruptedException and immediately return from run()
What is a Race Condition?
Issue with Threads
When 2 or more Threads try to access same resources it is called a Race Condition
How do you fix Race Conditions?
Synchronisation
Simply add the synchronize keyword to methods in the class
When one Thread is executing a synchronized method for an object, all other Threads that invoke synchronized methods for the same object block suspend execution until first thread is done with the object
What is Statement Synchronisation?
Where you synchronise a set of statements, not necessarily the whole method
What are Atomic Actions?
Self contained
We cannot interrupt an atomic process at any given time
What is Deadlock?
Deadlock is a situation where two or more processes are unable to proceed because each is waiting for the other to release a resource
This creates a cycle of dependency that halts all progress, causing the system or the involved processes to become stuck indefinitely
What is Starvation?
Where a thread can’t gain regular access to shared resources because another thread is frequently calling the object’s methods
Greedy Thread and Starved Thread
What is Livelock?
Like Deadlock
Except it occurs when 2 Threads are too busy responding to one another to do work