Created
April 6, 2014 14:28
-
-
Save jnizet/10006815 to your computer and use it in GitHub Desktop.
Accessing to a non-thread-safe collection by multiple threads leads to problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.foo; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.CountDownLatch; | |
public class UnsynchronizedCollectionAccess { | |
public static void main(String[] args) throws InterruptedException { | |
final CountDownLatch latch = new CountDownLatch(1); | |
final List<Integer> list = new ArrayList<Integer>(); | |
Runnable modification = new Runnable() { | |
@Override | |
public void run() { | |
try { | |
latch.await(); | |
for (int i = 0; i < 1_000_000; i++) { | |
list.add(i); | |
} | |
} | |
catch (InterruptedException e) { | |
// stop running | |
} | |
} | |
}; | |
Thread t1 = new Thread(modification); | |
Thread t2 = new Thread(modification); | |
t1.start(); | |
t2.start(); | |
latch.countDown(); | |
t1.join(); | |
t2.join(); | |
if (list.size() != 2_000_000) { | |
System.out.println("something's wrong. Lack of synchronization maybe?"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment