Multi-threading & Concurrency Flashcards
What is a thread?
A lightweight unit of execution within a process that shares the same memory space and resources
Threads enable concurrent execution within the same process.
What is a process?
An independent program in execution with its own memory space
Processes are isolated from one another.
What is the key difference between threads and processes?
Multiple threads can run in the same process and share memory, while processes are isolated from each other
Define synchronous execution.
Tasks run one after the other, blocking until each is completed
Define asynchronous execution.
Tasks can run in parallel or independently without waiting for others to complete
What is the purpose of the synchronized keyword?
Ensure that only one thread can execute a block of code or method at a time
What are the two approaches to creating threads in Java?
- Extend Thread
- Implement Runnable (interface)
Why is it considered best practice to implement Runnable in Java?
Java supports single inheritance, meaning if you use extend, you can only extend Thread
What does the sleep() method do?
Pauses the execution for a specified time but does not release any locks
What does the wait() method do?
Releases the lock and waits for another thread to notify using notify() or notifyAll()
What are Reentrant Locks?
A more flexible locking mechanism than synchronized, allowing more control (e.g. try-locking)
Define deadlock.
A situation where two or more threads are waiting indefinitely for each other’s resources, causing a standstill
What are some strategies to prevent deadlock?
- Lock ordering
- Try-lock mechanisms
- Apply a timeout strategy
What is a race condition?
Occurs when two threads share data simultaneously, and the result depends on the thread scheduling
What is a solution to prevent race conditions?
Use synchronization or atomic variables
What does the volatile keyword do?
Ensures that changes to a variable are always visible to other threads and prevents caching of variables across threads
List the thread lifecycle states.
- New
- Runnable
- Blocked
- Waiting
- Timed waiting
- Terminated
What does the Runnable interface do?
Returns no result and cannot throw checked exceptions
What is the main difference between Callable and Runnable?
Callable can return a result and throw exceptions, while Runnable cannot
What is a New thread state?
Thread instance is created but not yet started
What is a Runnable state?
Thread is ready to run, waiting for CPU time
What is the blocked thread state?
Waiting for a monitor lock
What is the waiting thread state?
Waiting indefinitely until notified
What is timed waiting thread state?
Waiting for a specified period
What is terminated thread state?
Finished execution