Multithreading Flashcards

1
Q

What happens if you mark any logic with the synchronized key word?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Describe 5 ways you can handle concurrent access to shared data in a multithreaded environment?

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When does a race condition occur?

A

A race condition occurs when two threads access a shared variable at the same time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Describe 3 benefits of the synchronized keyword?

A

Prevents race conditions
Provides thread safety
Easy to use

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Describe 3 examples of drawbacks of the synchronzied keyword?

A
  • Can lead to performance issues
  • Can cause deadlocks
  • Only synchronizes access to the critical part of the code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly