Multithreading Flashcards
What happens if you mark any logic with the synchronized key word?
The synchronized key word prevents multiple threads from accessing the resource simultaneously
Once the lock is acquired by the current thread, it executes the critical section of code within the synchronized block.
Once the execution of the critical section of code is completed, the lock is released, and any waiting threads are notified that the lock is now available.
The waiting threads then compete for the lock, and the first thread to acquire the lock can enter the critical section of code.
Describe 5 ways you can handle concurrent access to shared data in a multithreaded environment?
- Synchronization: ie., locks, semaphores, monitors
- Atomic operations
- Thread-safe data structures: ie., concurrent collections in Java
- Immutable objects to represent data that doesn’t change so it can be shared between threads in a safe manner
- Thread local storage to store data specific to that thread
When does a race condition occur?
A race condition occurs when two threads access a shared variable at the same time
Describe 3 benefits of the synchronized keyword?
Prevents race conditions
Provides thread safety
Easy to use
Describe 3 examples of drawbacks of the synchronzied keyword?
- Can lead to performance issues
- Can cause deadlocks
- Only synchronizes access to the critical part of the code