我想要实现的目标的一个简短示例:
class Country {
final int id;
final String name;
static List<Country> values = new List<Country>();
static final Country US = new Country._create(1, 'United States');
static final Country UK = new Country._create(2, 'United Kingdom');
Country._create(this.id, this.name) {
values.add(this);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个带有私有命名构造函数的 Country 类。我想创建一组静态国家/地区常量和所有可用国家/地区的列表。
这就是问题所在:
void main() {
print('Countries:');
for (Country country in Country.values) {
print(country.name);
}
}
Run Code Online (Sandbox Code Playgroud)
由于静态成员的延迟初始化,我的值列表是空的。然而:
void main() {
print('US id is: ${Country.US.id}');
print('Countries:');
for (Country country in Country.values) {
print(country.name);
}
}
Run Code Online (Sandbox Code Playgroud)
仅当我在代码中引用 US 常量时,它才会添加到列表中。 …
我正在开发我的第一个Spring Boot应用程序,但遇到以下问题。
我想设置默认所有bean都是延迟加载的。我知道我可以将它添加@Lazy到我所有的@Componentbean 中,但我希望默认所有 bean 都设置为惰性...
在Spring Boot 中,我没有 XML 配置文件或配置类,但我只有一个application.properties配置文件。
那么,如何将所有 bean 的默认行为设置为 lazy=true
我在 Spring Boot 2.0.5 下,使用 Spring Data JPA
我有一堂这样的课程(为了理解):
@Component
public class Synchronizer {
@Autowired
private MyService myService;
@Transactional
public void synchronizeAuto() {
List<MyTest> tests = myService.getTests();
tests.get(0).getMyLazyObject().getName();
}
}
Run Code Online (Sandbox Code Playgroud)
配置在这里(还有其他配置文件我省略了):
@Configuration
@EnableAsync
@EnableScheduling
@EnableTransactionManagement
public class SpringAsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {
@Autowired
private AppConfigProperties appConfigProperties;
@Autowired
private Synchronizer synchronizer;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
executor.setThreadNamePrefix("threadPoolExecutor-");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncExceptionHandler();
}
@Override
public void …Run Code Online (Sandbox Code Playgroud) class HeavyweightObjcet
{
public void operate() {
System.out.println("Operating...");
}
}
class LazyInitializer
{
HeavyweightObjcet objcet;
public void operate()
{
if (objcet == null)
objcet = new HeavyweightObjcet();
objcet.operate();
}
}
Run Code Online (Sandbox Code Playgroud)
Here I'm making a virtual proxy for a heavyweight object. Each time before calling HeavyweightObject::operate, the program checks first whether the object is null or not. This part is checked once and only once through the entire lifetime of the object.
A possible improvement maybe using the state pattern …
我看到了这样的答案,试图通过评论来澄清,但对这里的例子不满意。
也许是时候提出这个具体问题了......
为什么枚举单例实现被称为惰性?
public enum EnumLazySingleton {
INSTANCE;
EnumLazySingleton() {
System.out.println("constructing: " + this);
}
public static void touchClass() {}
}
Run Code Online (Sandbox Code Playgroud)
它与急切的实现有何不同?
public class BasicEagerSingleton {
private static final BasicEagerSingleton instance = new BasicEagerSingleton();
public static BasicEagerSingleton getInstance() {
return instance;
}
private BasicEagerSingleton() {
System.out.println("constructing: " + this);
}
public static void touchClass() {}
}
Run Code Online (Sandbox Code Playgroud)
两者都将初始化实例而不访问INSTANCE/getInstance()- 例如 call touchClass()。
public class TestSingleton {
public static void main(String... args) …Run Code Online (Sandbox Code Playgroud) java singleton enums double-checked-locking lazy-initialization
使用扩展属性配置 Exec-Task 时遇到问题。
我的 Exec-Task 的配置依赖于扩展中定义的 String-Property。不幸的是,在配置 Exec-Task 时,该属性尚未设置。这导致TaskCreationException:
Could not create task ':myTask'.
org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':myTask'.
...
Caused by: org.gradle.api.internal.provider.MissingValueException: Cannot query the value of extension 'myConfig' property 'command' because it has no value available.
at org.gradle.api.internal.provider.AbstractMinimalProvider.get(AbstractMinimalProvider.java:86)
Run Code Online (Sandbox Code Playgroud)
Could not create task ':myTask'.
org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':myTask'.
...
Caused by: org.gradle.api.internal.provider.MissingValueException: Cannot query the value of extension 'myConfig' property 'command' because it has no value available.
at org.gradle.api.internal.provider.AbstractMinimalProvider.get(AbstractMinimalProvider.java:86)
Run Code Online (Sandbox Code Playgroud)
问题似乎在于myConfig.command.get()它规避了惰性评估。 …
我正在使用一些需要连接到数据库的类.只有在执行实际操作时才需要连接.我想延迟连接阶段,直到确实需要它为止.为此,我想做类似的事情:
class MyClass
def __init__(self):
self.conn = None
def connect(self):
if self.conn : return
self.conn = ConnectToDatabase()
@connect
def do_something1(self):
self.conn.do_something1()
@connect
def do_something2(self):
self.conn.do_something2()
Run Code Online (Sandbox Code Playgroud)
但我不知道如何connect为类定义装饰器.
我当然可以这样做:
def do_something1(self):
self.connect()
self.conn.do_something1()
Run Code Online (Sandbox Code Playgroud)
但使用装饰器似乎是一种更易读的解决方案.可能吗?
假设这适用:
public class Cat : Animal { }
Run Code Online (Sandbox Code Playgroud)
并假设我有一个方法:
public void Feed(Animal animal) { ... }
Run Code Online (Sandbox Code Playgroud)
我可以这样称呼它:
var animal = new Cat();
Feed(animal);
Run Code Online (Sandbox Code Playgroud)
当Feed重构为仅支持Lazy<Animal>参数时,如何才能使其正常工作?我想以var lazyAnimal = new Lazy<Cat>();某种方式传递给我.
这显然不起作用:
var lazyAnimal = new Lazy<Cat>();
Feed(lazyAnimal);
Run Code Online (Sandbox Code Playgroud) 懒惰评估被认为是一种延迟流程直到第一次需要的方式.这往往会避免重复评估,这就是为什么我认为这样做的速度要快得多.像Haskell(和JavaScript ..?)这样的函数语言内置了这个功能.
但是,我不明白为什么和为什么其他"正常"方法(即相同的功能但不使用惰性评估)更慢..这些其他方法如何以及为什么重复进行评估?有人可以通过提供简单的例子并解释每种方法的机制来详细说明这一点吗?
另外,根据Wikipedia关于懒惰评估的页面,这些被认为是这种方法的优点:
但是,我们可以控制所需的计算并避免重复相同的计算吗?(1)我们可以使用ie链接列表来创建无限数据结构(2)我们可以做(3)已经.. ??? 我们可以定义类/模板/对象并使用它们而不是原语(即JavaScript).
另外,在我看来(至少从我见过的案例中),懒惰的评估与递归和使用"头部"和"尾部"(以及其他)概念密切相关.当然,有些情况下递归是有用的,但懒惰的评价不仅仅是......?不仅仅是一种解决问题的递归方法..?Streamjs是一个JavaScript库,它使用递归和一些其他简单的操作(头部,尾部等)来执行惰性求值.
看来我无法理解它...
在此先感谢任何贡献.
recursion performance haskell lazy-evaluation lazy-initialization
我一直在阅读MSDN上的这篇异步文章,但我无法理解Lazy<T>给定示例的目的.
public class AsyncCache<TKey, TValue>
{
private readonly Func<TKey, Task<TValue>> _valueFactory;
private readonly ConcurrentDictionary<TKey, Lazy<Task<TValue>>> _map;
public AsyncCache(Func<TKey, Task<TValue>> valueFactory)
{
if (valueFactory == null) throw new ArgumentNullException("loader");
_valueFactory = valueFactory;
_map = new ConcurrentDictionary<TKey, Lazy<Task<TValue>>>();
}
public Task<TValue> this[TKey key]
{
get
{
if (key == null) throw new ArgumentNullException("key");
return _map.GetOrAdd(key, toAdd =>
new Lazy<Task<TValue>>(() => _valueFactory(toAdd))).Value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,当你调用.Value时Lazy<T>,它将调用内部的构造函数.从示例中,它立即被调用,为什么要添加Lazy<T>?
c# ×2
java ×2
spring ×2
asynchronous ×1
c#-4.0 ×1
covariance ×1
dart ×1
decorator ×1
enums ×1
gradle ×1
gradle-task ×1
haskell ×1
hibernate ×1
kotlin ×1
lazy-loading ×1
oop ×1
performance ×1
properties ×1
python ×1
recursion ×1
scheduler ×1
singleton ×1
spring-boot ×1
static ×1