Given:
import java.util.*;
public class AccessTest {
public static void main(String[] args) {
Thread t1 = new Thread(new WorkerThread());
Thread t2 = new Thread(new WorkerThread());
t1.start(); t2.start; // line1
}
}
class WorkPool {
static ArrayList<Integer> list = new ArrayList<>(); // line2
public static void addItem() { // line3
list.add(1); // Line4
}
}
class WorkerThread implements Runnable {
static Object bar = new Object ();
public void run() { //line5
for (int i=0; i<5000;i++) WorkPool.addItem(); // line6
}
}
Which of the four are valid modifications to synchronize access to the valid list between threads t1 and t2?
A.
Replace line 1 with:
Synchronized (t2) (t1.start();) synchronized(t1) (t2.start();)
B.
Replace Line 2 with:
static CopyWriteArrayList<Integer> list = new CopyWriteArrayList<>();
C.
Replace line 3 with:
synchronized public static void addItem () {
D.
Replace line 4 with:
synchronized (list) (list.add(1);)
E.
Replace line 5 with:
Synchronized public void run () {
F.
replace line 6 with:
Synchronized (this) {for (in i = 0, i<5000, i++) WorkPool.addItem(); }
G.
Replace line 6 with:
synchronized (bar) {for (int i= 0; i<5000; i++) WorkPool.addItem(); }
Explanation:
Away to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:
For example:public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects’ methods. Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.
Reference: The Java Tutorial,Intrinsic Locks and Synchronization
Since the two WorkerThread are 2 different objects it doesn’t make any sense to put a synchronize(this) as a wrap for the cycle!!
It makes more sense to declare synchronyzed the addItem method. The answer at this question is wrong!
Yes, C and D are right answers.
If I change line 6 with F then I got java.lang.ArrayIndexOutOfBoundsException.
yes , c and d are correct
Why is G incorrect
Tested B (if CopyOnWriteArrayList),C,D,G
E: doesn’t make any sense
F: this cannot be used in static method
A: dead/live lock
+1
+1
+1
Explanation: E,F are incorrect and G is correct. http://stackoverflow.com/questions/19688666/synchronized-run-method
B C D F
BCD
all tested
CDG
sorry BCG
Ans: CEFG
(B) should be
Replace line 2 with:
static CopyOnWriteArrayList list = new CopyOnWriteArrayList();
(D) should be
Replace line 4 with:
synchronized (list) {list.add(1);}