how to handle race condition with Runnable using separate thread for lambda inside hashmap

无人久伴 提交于 2019-12-24 07:13:15

问题


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?

来源:https://stackoverflow.com/questions/43992323/how-to-handle-race-condition-with-runnable-using-separate-thread-for-lambda-insi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!