2080 1

CSC419 ยท 2080 ยท 10 marks

Why do we need to synchronize the thread? Justify with an example. An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle elem

Why do we need to synchronize the thread? Justify with an example. An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element. Write a function that accepts an integer array and returns 1 if it is a centered array, otherwise it returns 0.[10]

Advanced Java ProgrammingChapter 1: Programming in JavaConcurrency

Quick answer

Thread synchronization is the mechanism that ensures that two or more concurrent threads do not simultaneously execute a critical section (a segment of code that accesses shared resources). Without synchronization, multiple threads accessing and modifying shared data can produce inconsistent or incorrect results, a situation known as a race condition.

Thread Synchronization and Centered Array


Part 1: Why Do We Need to Synchronize Threads? (with Example)

What is Thread Synchronization?


Why Do We Need Synchronization?

When multiple threads share a common resource (such as a variable, file, or object), the following problems can occur without synchronization:

ProblemDescription
Race ConditionTwo threads read/write shared data simultaneously, causing unpredictable results
Data InconsistencyShared data gets corrupted because updates from one thread overwrite another
Thread InterferenceOperations of one thread interfere with operations of another thread

Synchronization solves these problems by allowing only one thread at a time to access the critical section using the synchronized keyword in Java.


Example: Without Synchronization (Problem)

class Counter {
    int count = 0;

    // No synchronization - PROBLEM
    public void increment() {
        count++;
    }
}

class MyThread extends Thread {
    Counter c;

    MyThread(Counter c) {
        this.c = c;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            c.increment();
        }
    }
}

public class WithoutSync {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();

        MyThread t1 = new MyThread(c);
        MyThread t2 = new MyThread(c);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        // Expected: 2000, but actual result is unpredictable (e.g., 1768, 1854...)
        System.out.println("Count: " + c.count);
    }
}

Problem: Both t1 and t2 access count++ simultaneously. The operation count++ is not atomic - it involves three steps:

  1. Read the value of count
  2. Increment it
  3. Write it back

Two threads can read the same value before either writes back, causing lost updates.


Example: With Synchronization (Solution)

class Counter {
    int count = 0;

    // Synchronized method - only one thread can execute at a time
    public synchronized void increment() {
        count++;
    }
}

class MyThread extends Thread {
    Counter c;

    MyThread(Counter c) {
        this.c = c;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            c.increment();
        }
    }
}

public class WithSync {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();

        MyThread t1 = new MyThread(c);
        MyThread t2 = new MyThread(c);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        // Always prints: Count: 2000 (correct and consistent)
        System.out.println("Count: " + c.count);
    }
}

How it works:

  • The synchronized keyword places a lock (monitor) on the object.
  • When t1 enters increment(), it acquires the lock.
  • t2 must wait until t1 releases the lock before it can enter.
  • This guarantees mutual exclusion and data consistency.

Summary of Synchronization Benefits

  • Prevents race conditions
  • Ensures data consistency across threads
  • Provides mutual exclusion for critical sections
  • Enables safe communication between threads

Part 2: Centered Array Function

Problem Definition

An array with an odd number of elements is centered if:

  • All elements except the middle one are strictly greater than the middle element.

Return: 1 if centered, 0 otherwise.


Logic / Algorithm

Step 1: Check if the array length is odd.
        If even, return 0 (no middle element exists).

Step 2: Find the middle index = length / 2

Step 3: Get the middle element = array[middleIndex]

Step 4: Loop through all elements except the middle one.
        If any element is <= middle element, return 0.

Step 5: If all elements pass the check, return 1.

Java Implementation

public class CenteredArray {

    // Function to check if array is centered
    public static int isCentered(int[] arr) {

        int n = arr.length;

        // Step 1: Check if number of elements is odd
        if (n % 2 == 0) {
            return 0; // Even number of elements, no middle element
        }

        // Step 2: Find the middle index and middle element
        int midIndex = n / 2;
        int midValue = arr[midIndex];

        // Step 3: Check all elements except the middle one
        for (int i = 0; i < n; i++) {
            if (i != midIndex) {
                // Every other element must be STRICTLY GREATER than middle
                if (arr[i] <= midValue) {
                    return 0; // Not centered
                }
            }
        }

        // Step 4: All conditions satisfied
        return 1;
    }

    // Main method to test
    public static void main(String[] args) {

        int[] arr1 = {3, 5, 1, 4, 2}; // middle = arr[2] = 1, all others > 1
        int[] arr2 = {5, 3, 4, 2, 6}; // middle = arr[2] = 4, but 3 <= 4, not strictly greater, so not centered

        System.out.println("Array 1 result: " + isCentered(arr1)); // Expected: 1 (centered)
        System.out.println("Array 2 result: " + isCentered(arr2)); // Expected: 0 (not centered)
    }
}

Dry Run

Array 1 = {3, 5, 1, 4, 2}: length = 5 (odd), midIndex = 2, midValue = 1. Checking the remaining elements: 3 > 1, 5 > 1, 4 > 1, 2 > 1, all strictly greater, so the function returns 1.

Array 2 = {5, 3, 4, 2, 6}: length = 5 (odd), midIndex = 2, midValue = 4. Checking the remaining elements in order: 5 > 4 passes, but 3 > 4 fails (3 <= 4), so the function immediately returns 0.


Conclusion

Thread synchronization is needed whenever multiple threads share mutable state, because without it, interleaved reads and writes to the same variable produce race conditions and lost updates, as shown by the count++ example above. The isCentered function above solves the array problem in a single pass: it rejects even-length arrays immediately, then checks every non-middle element against the middle value, returning 0 the moment any element fails the strictly-greater-than condition, and 1 only if every element passes.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.