我有缓存列表,我的代码是这样的
public class MyList {
private final List<String> cache = new ArrayList<String>();
private List<String> loadMyList() {
// HEAVY OPERATION TO LOAD DATA
}
public List<String> list() {
synchronized (cache) {
if( cache.size() == 0 ) {
cache.addAll(loadMyList());
}
return Collections.unmodifiableList(cache);
}
}
public void invalidateCache() {
synchronized (cache) {
cache.clear();
}
}
}
因为列表加载非常重,我收到一个请求,如果列表加载当前正在进行中,我将返回“旧”缓存数据...
这可能吗,有人可以指导我如何从这里开始吗
编辑:Adam Horvath 和 bayou.io 提出了这样的建议
public class MyList
{
private final List<String> cache = new ArrayList<String>();
private final List<String> oldCache = new ArrayList<String>();
private volatile boolean loadInProgress = false;
private List<String> loadMyList()
{
// HEAVY OPERATION TO LOAD DATA
}
public List<String> list()
{
synchronized (cache)
{
if( loadInProgress )
return Collections.unmodifiableList( oldCache );
else
return Collections.unmodifiableList(cache);
}
}
public void invalidateCache()
{
synchronized (cache)
{
// copy to old cache
oldCache = new ArrayList<String>( cache );
// set flag that load is in progress
loadInProgress = true;
// clear cache
cache.clear();
// initialize load in new thread
Thread t = new Thread(new Runnable()
{
public void run()
{
cache.addAll( loadMyList() );
// set flag that load is finished
loadInProgress = false;
}
});
t.start();
}
}
}
修改后的代码会有问题吗?? 由于我在多线程和/或兑现优化方面没有经验,我将不胜感激任何和所有性能建议
最佳答案
“因为列表负载非常重,所以我收到一个请求,如果列表加载当前正在进行中,我将返回“旧的”缓存数据...”
由于您的“同步(缓存)” block ,这不会发生。您需要一个 volatile boolean 标志(互斥锁)来告诉您正在生成一个列表。当线程尝试获取 list() 并且互斥量为真时,它将接收缓存的。当 loadMyList() 完成时将其设置为 false。
因此,删除同步块(synchronized block)并开始在单独的线程中加载您的列表。
public class MyList {
private List<String> cache = new ArrayList<String>();
private volatile boolean loadInProgress = false;
private List<String> loadMyList() {
// HEAVY OPERATION TO LOAD DATA
}
public List<String> list() {
// Whatever is in cache, you can always return it
return Collections.unmodifiableList(cache);
}
/**
* Starts the loader-thread and then continues.
*/
public void invalidateCache() {
// Next two lines make sure only one Loader-thread can be started at the same time
synchronized (cache) {
if (!loadInProgress) {
// initialize load in new thread
Thread t = new Thread("Loader-thread") {
@Override
public void run() {
List<String> toAssign = loadMyList();
// You can simply assign instead of copying
cache = toAssign;
// cache now "points to" refreshed list
loadInProgress = false;
}
};
loadInProgress = true;
t.start();
// Now let's exit the synchronized block. Hopefully the Thread will start working soon
} else {
// A Thread is already working or about to start working, don't bother him
}
}
}
}
关于Java缓存对象返回旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31319328/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案