mardi 26 février 2019

Pattern match interface for Java 8 showing compiler Warning

I am building a command line tool that should validate some logic and if that fails it should print the error and exit, some of that logic could throw a runtime exception. I am using below java BiConsumer Interface.

BiConsumer<Consumer<T>,String> tryOrDie = 
    (block,msg)->
    {
        try
        {
            block.accept((T) this);
        }
        catch (Throwable t)
        {
            log.error(t.getMessage(), t);
            log.error(msg);
            System.exit(-1);
        }
    };

So for example if my block would get other processes running this tool. This could be called like this to get other UNIX java processes with the name of this program (MyProgram)

final String currentPid=ManagementFactory.getRuntimeMXBean().getName();
currentPid=currentPid.substring(0,currentPid.indexOf("@"));    
String GET_ALERT_PID="ps -ef | grep MyProgram | grep -v grep | tr -s ' ' | cut -d ' ' -f 2";
    tryOrDie.accept(y->{
                    otherPids = new BufferedReader(new InputStreamReader(Wrap.startProcess(GET_ALERT_PID))).lines().map(String::trim)
                            .filter(pid -> !pid.equalsIgnoreCase(currentPid))
                            .collect(Collectors.toList());
                }, "Could not determine if other running processIds of IsawsvcAlert were running");

The code works as expected, however I still get compiler warning Type safety: Unchecked cast from IsawsvcAlert to T on line

block.accept((T) this);

Could this cause any memory leak or another issue? Is there any help to remove this type safety in the compiler? That would be helpful.

Aucun commentaire:

Enregistrer un commentaire