44 lines
1.3 KiB
Markdown
44 lines
1.3 KiB
Markdown
# Answers
|
|
|
|
## Question 1
|
|
|
|
Atomic variables are thread-safe variables provided by Java.
|
|
|
|
They allow multiple threads to update a value safely without using synchronized blocks or locks.
|
|
|
|
Regular variables do not provide this protection and may cause race conditions.
|
|
|
|
## Question 2
|
|
|
|
Four classes from the `java.util.concurrent.atomic` package are:
|
|
|
|
- AtomicInteger
|
|
- AtomicLong
|
|
- AtomicBoolean
|
|
- AtomicReference
|
|
|
|
`AtomicInteger` is used for thread-safe integer operations such as incrementing or decrementing a counter.
|
|
|
|
## Question 3
|
|
|
|
Atomic variables are useful for simple operations on a single variable.
|
|
|
|
For more complex operations involving multiple variables or multiple steps, locks are usually a better choice.
|
|
|
|
## Question 4
|
|
|
|
Yes. A program can be free of race conditions but still have poor performance.
|
|
|
|
Too much synchronization, lock contention, and thread management overhead can slow down the program.
|
|
|
|
## Question 5
|
|
|
|
Adding more threads does not always improve performance because threads compete for CPU time and shared resources.
|
|
|
|
In some cases, too many threads can actually reduce performance.
|
|
|
|
## Question 6
|
|
|
|
Deadlocks are difficult to detect because they depend on thread scheduling.
|
|
|
|
A program may work correctly many times and then suddenly deadlock under different execution conditions. |