当您要发送匿名函数时,执行(可运行和可序列化)是否太昂贵? [英] Is it too costly to do a (Runnable & Serializable) when you want to send an anonymous function?

查看:58
本文介绍了当您要发送匿名函数时,执行(可运行和可序列化)是否太昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做类似的事情

 executor.execute((Runnable & Serializable)func);

在func是一个匿名函数的地方,我必须在项目中大量使用它,否则我将不得不为我要调用的每个不同函数创建一个类,并在每个这些类中实现Runnable和Serializable,其优点是我想在编译时拥有类型,而不是在运行时进行类型转换,我想知道执行这种转换是否过于昂贵或琐碎且不代表性能上的巨大差距.

如果您在此方面有现实生活的经验,并且愿意分享,那真是太棒了.

谢谢.

解决方案

铸造是微不足道的",因为它仅验证给定对象扩展了某个类或实现了一个接口-不会更改对象本身. >

在您的情况下,如果func代表lambda表达式或方法引用

executor.execute((Runnable & Serializable) () -> System.out.println("5"));
executor.execute((Runnable & Serializable) System.out::println);

LambdaMetafactory 确保生成的lambda对象实际上实现了RunnableSerializable,甚至可能优化了转换.

但是如果func是您的方法的参数:

public void execute(Runnable func) {
    executor.execute((Runnable & Serializable)func);
}

java编译器和java运行时都不会以某种方式神奇地使func可序列化.

在这种情况下,您可以将方法重写为

public <T extends Runnable & Serializable> void execute(T func) {
    executor.execute(func);
}

需要调用者提供一个Runnable和Serializable对象-一个自动生成的对象(通过lambda表达式或方法引用)或一个手动"编码的类.

I am doing sht like:

 executor.execute((Runnable & Serializable)func);

Where func is an anonymous function, I have to heavily use this in the project otherwise I would have to create a class for every different function I want to call and implement Runnable and Serializable in each of those class, the advantage would be that I would have the type at compile time rather than casting it at run time, I would like to know if doing this cast is too costly or is trivial and does not represent a big gap in performance.

If you have a real life experience on this and you are willing to share it, it would be awesome.

Thanks in advance.

解决方案

Casting is "almost trivial" in that it only verifies that the given object extends some class or implements an interface - it does not change the object itself.

In your case, if func stands for a lambda expression or a method reference

executor.execute((Runnable & Serializable) () -> System.out.println("5"));
executor.execute((Runnable & Serializable) System.out::println);

the LambdaMetafactory guarantees that the generated lambda object really implements Runnable and Serializable and the cast might even get optimized away.

If however func is a parameter to your method:

public void execute(Runnable func) {
    executor.execute((Runnable & Serializable)func);
}

neither the java compiler nor the java runtime will somehow magically make func Serializable too.

In this case, you could rewrite your method as

public <T extends Runnable & Serializable> void execute(T func) {
    executor.execute(func);
}

which requires the caller to provide a Runnable and Serializable object - either an autogenerated one (through lambda expression or method reference) or a "manually" coded class.

这篇关于当您要发送匿名函数时,执行(可运行和可序列化)是否太昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆