I was getting a code review from my software mentor (who is a C# programmer). He recommended I use lambda in my application to avoid using a large chain of if/else if
statements. I created a hashmap with two types String
and Runnable
.
He said it looks good, but now we have a problem where there is a race condition... meaning Runnable is creating a separate thread, and if the Runnable.run()
thread does not win the race it could cause problems down the line (especially being in the constructor).
Here is the sample code to show the problem...
import java.util.HashMap;
import java.util.Map;
public class testLambda {
String[] numArray = {"One", "Two", "Three"};
testLambda(String num){
Map<String, Runnable> printNumbers = new HashMap<>();
printNumbers.put(numArray[0], () -> printStringOne());
printNumbers.put(numArray[1], () -> printStringTwo());
printNumbers.put(numArray[2], () -> printStringThree());
printNumbers.get(num).run();
}
private void printStringOne(){
System.out.println("1");
}
private void printStringTwo(){
System.out.println("2");
}
private void printStringThree(){
System.out.println("3");
}
public static void main(String[] args) {
new testLambda("Three");
new testLambda("Two");
new testLambda("One");
}
}
There are a couple solutions where I am not sure to handle either of them...
Somehow place a hold on the current thread until the Runnable thread has completed execution, and using some type of
join
after it's been completed to let the current thread continue running.Instead of using Runnable for executing the lambda void type expression, somehow use something else where it will execute a void type lambda.
Anyone have any ideas?