1337 race condition.
Level 14
Sam was trying to make a program to show how 1337 he is. But the output isn't always correct. Help him fix his program so he can impress his friends.
package org.hackthissite.missions.extbasic;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExtBasic14 {
private final ExecutorService executorService = Executors.newFixedThreadPool(100);
private static final int MAX = 1337;
private int timeToGetLeet = 0;
ExtBasic14() throws InterruptedException {
for (int i = 0; i < MAX; i++) {
executorService.execute(new Runnable() {
public void run() {
incrementLeetness();
}
});
}
executorService.shutdown();
while (!executorService.isTerminated()) {
Thread.sleep(500);
}
System.out.println(timeToGetLeet);
}
private void incrementLeetness() {
int obfusticatedIncremental = timeToGetLeet;
obfusticatedIncremental = obfusticatedIncremental + 1;
timeToGetLeet = obfusticatedIncremental;
}
/**
* @param args
*/
public static void main(String[] args) throws InterruptedException {
new ExtBasic14();
}
}
Solution:
- ExecutorService has to use a thread safe queue (Which it does by default). This is all that is needed.
- It is necessary to synchronize the ExecutorService object in the incrementLeetness method since the incrementLeetness method can be called from differens threads.
- Input "private synchronized void incrementLeetness() {" and check.
- It's done.
- Congratz! You have completed all the missions in this category