Search⌘ K
AI Features

Quiz 5

Explore common thread safety challenges in Java and learn how to fix concurrency problems using synchronization and atomic variables. Understand why proper locking is crucial to avoid race conditions and stale data in multithreaded environments.

We'll cover the following...

Question # 1

Is the following class thread-safe?

public class Sum {

    int count = 0;

    int sum(int... vals) {

        count++;

        int total = 0;
        for (int i = 0; i < vals.length; i++) {
            total += vals[i];
        }
        return total;
    }

    void printInvocations() {
        System.out.println(count);
    }
}
Technical Quiz
1.
A.

Yes

B.

No


1 / 1

Show Explanation

The class isn't thread-safe because it has state that can be mutated by different threads without synchronization amongst them. The state consists of the variable count

Question # 2

What are the different ways in which we can make the ...