Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading in OCPJP exam

I have encountered a question which I am struggled to understand though I found the answer. Please look at this and provide me an explanation on the answer.

public class TestSeven extends Thread {
  private static int x;
  public synchronized void doThings() {
    int current = x;
    current++;
    x = current;
  }
  public void run() {
    doThings();
  }
} 

question and given answer is... Which statement is true?

A. Compilation fails.

B. An exception is thrown at runtime.

C. Synchronizing the run() method would make the class thread-safe.

D. The data in variable "x" are protected from concurrent access problems.

E. Declaring the doThings() method as static would make the class thread-safe.

F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe.

Bold one is given as the answer. Thanks for the replies in advance !!

like image 502
Sidath Bhanuka Randeniya Avatar asked Apr 04 '16 06:04

Sidath Bhanuka Randeniya


2 Answers

If you have a synchronized instance method like that, it synchronizes on the instance, i.e. every instance can access the method on its own. But x is static, so any instance of TestSeven can access it concurrently. If doThings() is static, it synchronizes on the class, so only one instance can access synchronized code at a given time.

like image 91
user140547 Avatar answered Sep 29 '22 10:09

user140547


Here is what will happen.

public static syncronized void doThings();

This will synchronize method at class level. Which means only one instance of class will be able to access the code at an instance of time, Which means there is no possibility of static variable x to be modified by other instances.

In other case,

public syncronized void doThings();

This means that doThings(); method is synchronized on current object. i.e. an instance of TestSeven, so multiple instances can access the method which in turn can change the static shared variable x which is not desirable.

like image 35
Prasad Kharkar Avatar answered Sep 29 '22 10:09

Prasad Kharkar