Wk3L1 - Synchronization Flashcards

1
Q

What does the volatile keyword do in Java?

A

The volatile keyword forces all reads and writes to a variable to go directly to main memory, bypassing the cache. It solves cache coherency problems but does not prevent data races.

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

Why is the volatile keyword not commonly used?

A

It only works for 32- and 64-bit variables and does not solve issues related to multiple threads writing to the same memory location. Using main memory over the cache is also expensive.

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

What are Atomic Variables?

A

Atomic variables provide a thread-safe way to handle shared variables without using synchronization. Instead of operators like x++, methods like x.incrementAndGet() are used, ensuring atomicity.

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

How does the CAS (Compare-and-Swap) operation work with Atomic Variables?

A

M: Memory location.
A: Expected value in memory.
B: New value to set if the current value matches the expected value. If the expected value doesn’t match, the update fails, and the programmer must handle it.

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

What is a Critical Section in multithreading?

A

A critical section is a part of the code where a shared resource is accessed by multiple threads. Proper synchronization is needed to prevent data races when entering a critical section.

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

What is an Intrinsic Lock in Java?

A

Every Java object has an intrinsic lock associated with it. A thread that acquires this lock can block other threads from accessing synchronized code sections that use the same lock.

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

How do you use the Synchronized Method in Java?

A

By adding the synchronized keyword to the method signature, you ensure that only one thread can execute the method at a time, using the object’s intrinsic lock.

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

How do you use the Synchronized Statement in Java?

A

Use synchronized (object) followed by a block of code in curly braces. The specified object must be the same for each thread to ensure proper synchronization.

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