Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Simple embedded MCUs usually do not have any means to "snoop" the bus checking if anybody (even itself) invalidates cache contents with writes to cached memory addresses.
If your MCU has separate data and instruction caches (which most modern MCUs have) and you copy code as data from flash to RAM, you need to flush the data cache (to ensure everything you copied is physically written to RAM) and invalidate the instruction cache (which might contain "old" information from before the copy) to really execute the code you just copied instead of executing what was there before and still resides in instruction cache.
You might get away not doing the latter if you can be sure your MCU has never "seen" the memory area before you just copied (since it will not have cached anything and needs to physically read RAM anyway), but it's good practice to do data cache flushes and instruction cache invalidation nevertheless to stay on the safe side.
Copying code from flash to RAM is a special case of self modifying code and you as a programmer need to make sure it's doing no damage.
|
In embedded system, boot-loader used to init the board and load image. Usually, boot-loader runs in norflash during the 1st stage and need copy itself (.txte+.date code) from flash to ram, then jump to ram execute code.
My question is: when copy code from flash to RAM and cache enable, do we must flush data cache and invalidate the instruction cache? I found uboot and other bootloader execute this operation, but if I don't do that, the system still could boot successful, what's the reason why we must flush data cache after copy code from flash to ram?
|
What's the reason why we must flush data cache after copy code from flash to ram?
|
In short
Expires header instructs the browser how long it should cache content in client side cache. Browser will serve the content from client side cache until the expiration date is reached.
When client side cache is expired browser will send request to server again. Request includes If-None-Match header with the previous Etag value it received from server. If value of If-None-Match header still matches current Etag value on server it will respond with 304 Not Modified.
When you use Etag and If-None-Match headers and want server to send updated content, value of Etag header must change.
Longer explanation
Lest assume you have the following code.
$app = new \Slim\Slim();
$app->get("/hello", function() use ($app){
$app->etag("unique-etag-1");
echo "Hello world.\n";
});
$app->run();
Then you make a request.
If-None-Match0
On subsequent requests browser will send If-None-Match1 request header. Value of this header is the same as value of previously received If-None-Match2 header.
When Slim receives the request it compares the value of If-None-Match3 header to the value you set with If-None-Match4 call. If these match If-None-Match5 will be returned.
If-None-Match6
If the content of URI changes or you want to browser to refetch the content for some other reasons, change the value of If-None-Match7 header.
If-None-Match8
Now when browser makes new request you will get If-None-Match9 response.
Etag0
|
I'm using Slim framework in order to develop an API.
I wanted to cache some request in the HTTP cache with:
$app->etag('Unique-ID')
But the time expiration didn't seems to work :
$app->expires('10 seconds')
When i look the headers with Chrome, first call i get a 200 Status Code : OK.
Second call, i get a 304 Status Code : OK.
Waiting 30 seconds.
Third call, i still get a 304 Status Code : NOT OK in my mind.
Should i not get a 200 Status Code because the cache is expired ?
Thank you.
|
HTTP cache not expires with Slim Framework
|
3
LocMemCache isn't suitable for production.
You should only use cache-based sessions if you’re using the Memcached cache backend. The local-memory cache backend doesn’t retain data long enough to be a good choice, and it’ll be faster to use file or database sessions directly instead of sending everything through the file or database cache backends. Additionally, the local-memory cache backend is NOT multi-process safe, therefore probably not a good choice for production environments.
https://docs.djangoproject.com/en/1.6/topics/http/sessions/#using-cached-sessions
Generally when I'm deploying for the first time I'll start with the DB Cache configured just to prove the configuration. Then switch it over Memcache or Redis.
Share
Improve this answer
Follow
answered Apr 16, 2015 at 14:00
Dwight GunningDwight Gunning
2,5152525 silver badges3939 bronze badges
2
Didn't realise it was not multi process safe. I'll look into a switch to memcached
– joeButler
Apr 16, 2015 at 14:10
When I first went through this I found the docs kind of hard to read and interpret. Glad you've got it straight now :-)
– Dwight Gunning
Apr 16, 2015 at 14:27
Add a comment
|
|
I'm having an issue with using using the cache backend for django
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
When I set the session engine to use cache instead of the DB. I am unable to login. From the app logs I can see that the auth is successful, the response also contains the set-cookie header for session_id. So that all seems to be working. Except that I am just returned to the login page after logging in. I guess this session
If I comment out the session engine, it reverts back to using the DB session engine and works as expected.
This is working on my python 2.7 machine locally, on the server where this doesn't work there is python 2.6 running (I'm not sure if this is relevant, but it's about the only real difference I can find). The pip packages are mostly identical, I think this all come from within django anyway.
I'm using django 1.6.7 in both places.
|
Login issue with django cached sessions
|
You can pass a File to Glide.
Glide.with(context).load(new File("your/file/name.jpg")).into(pollWebView);
|
In my app, i have an image view, the image content I get from the server is in the format of base64 encoded string. I store it locally and decode it to bitmap. This bitmap is loaded to the image view. This makes the app to scroll slow.
Now I found the reason behind that is no caching is done for the bitmap. One recommended a solution to use glide. But I did not find any method to load bitmap using glide. I just found the following method
Glide.with(context).load("http://goo.gl/gEgYUd").into(pollWebView);
can we load bitmap using glide?
|
Android glide load bitmap
|
Here a possible solution based on our comments.
Get the native EhCache object (as the Cache interface from Spring doesn't support getKeys method) from the cache manager
@Autowired private CacheManager cacheManager;
...
EhCache cache = (EhCache) cacheManager.getCache("EmployeesByCompanyId").getNativeCache();
Then you can iterate the cache keys, get the ones starting with companyId and remove them from the cache
for (Object key: cache.getKeys()) {
if((String)key.startsWith(companyId))
cache.remove(key);
}
See http://ehcache.org/apidocs/2.8.4/net/sf/ehcache/Ehcache.html
|
I use Ehcache 2.9.0 In my Spring Application and I would like to be able to cache a result based on the pagination.
First is how I use Ehcache right now:
@Cacheable(value ="EmployeesByCompanyId", key="#companyId")
public List<Employee> getEmployeesByCompanyId(String companyId) throws Exception {
return employeeRepository.getEmployeesByCompanyId(companyId);
}
@CacheEvict(value ="EmployeesByCompanyId", key="#company.id")
public Employee createNewEmployee(Employee employee, Company company)
{ ... }
Now is how I would like to use it for the same purpose but with a pagination. Example (not correct but it's the idea):
@Cacheable(value ="EmployeesByCompanyId", key="#companyId#page#maxResult"})
@Override
public List<Employee> getEmployeesByCompanyId(String companyId, int page, int maxResult) throws Exception {
return employeeRepository.getEmployeesByCompanyId(companyId, page, maxResult);
}
Then when I had a new employee to the list it should Evict the cache but I would like to evict the cache related to a companyId. If I write something like that would it remove the cache related to the companyId:
@CacheEvict(value ="EmployeesByCompanyId", key="#companyId")
How should I do to make the caching work with the pagination and evict the cache related to the companyId when I add a new employee to this company?
|
Ehcache Java Spring MVC and pagination @Cacheable
|
3
Caching for the all resources loaded in WKWebView is set by default. All you have to do is to set the right headers in the HTTP response for these resources so that iOS SDK will cache these honoring the rules specified in the Cache-Control header in the Response.
For example you set the max-age to some big number in Cache-Control to ensure caching for longer durations.
Refer the below article which explains all parameters in the HTTP Response which the iOS SDK will use to implement caching on the device side.
https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=en
Share
Improve this answer
Follow
answered May 24, 2016 at 9:45
ChandraChandra
37933 silver badges1313 bronze badges
Add a comment
|
|
I use WKWebView to display rich text including images.
I want to cache these images on disk.
How can I get these HTTP requests and cache the responses?
|
How to cache resources loaded by WKWebView?
|
You need to edit the DNS details for yourdomain.ext so that it points to yourdomain.ext.web.cdn.anycast.me for example.
There are typically two types of DNS records that you need to worry about, A records which point to an IP address and CNAMEs which point to a URL.
The root/apex of a domain can only point to an IP on most systems.
The root domain in your case is example.com and can only use an A record.
Subdomains can use both CNAME's and A records.
Apex A record example (example.com):
Hostname Type Target
-------- ---- ---------------------------------
@ CNAME 1.1.1.1
WWW subdomain CNAME example (www.example.com):
Hostname Type Target
-------- ---- ---------------------------------
www CNAME yourdomain.ext.web.cdn.anycast.me
The advantage of using the cname is it can hold a number of IPs that can change, if you simple pointed your site at one of their IP addresses they could disable it and take your site down, so it you are given a URL always use a CNAME to it instead of an A record to an IP.
This is why many websites use WWW.example.com or subdomain.example.com.
It is worth noting that using a cname as an apex is not RFC compliant and some hosts do not allow it or offer an alternative proprietary record type to achieve this on their internal system.
Another way around this if your nameserver provider is RFC compliant is to have to apex be an A record and point to a page with a redirect to the CDN or to use a service like wwwizer.
DNS Glossary
|
I just bought a cdn from ovh.ie for my website example.com
Here are the instructions. however, i am unable to set up it. Can someone guide me on how to set it up step by step?
1) Report the Backends (IP of your servers) ;
2) Declare the domain/sub-domains that you want to intergrate with the CDN ;
3) Point your domain to the CNAME created after your domain is registered;
4) Add your first cache rule.
Adding a domain on the CDN generates a CNAME with the format yourdomain.ext.web.cdn.anycast.me, you need to point the DNS of yourdomain.ext to this CNAME to activate it.
Once configured, a time delay is necessary so that all of your CDNs are operational. Otherwise, it will reach its full performance with progressive caching as set by your rules
|
how to set up a cdn?
|
3
I had exactly the same problem. My tomcat installation has custom [web.xml] and [conf.xml] files at conf folder, to serve HTTPS connections. In my case, the problem was with a HTTPS security constraint inside [conf.xml] file:
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Context</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
This constraint force clients to use always HTTPS, even with port 80 opened. Once this contraint was removed from web.xml, cache began to work ("cache-control" header with "max-age", and "expires" with the correct date).
Share
Improve this answer
Follow
answered May 8, 2016 at 15:25
LuisLuis
6144 bronze badges
1
1
Explained here with more details stackoverflow.com/a/36028585/320761
– Lukasz Frankowski
Jul 6, 2016 at 13:07
Add a comment
|
|
In the response header of all requests, there is a cache-control: private , and Expires that is set. I'd like to know where this is set.
I have the following setup:
1. F5 load balanced to two CentOS 6.4 servers hosting Tomcat 7.0.42.0
2. I've set an ExpiresFilter for images, css and js files. However, these types are not always cached.
There are two environments , however only 1 of the environments is showing the response header Cache-Control private, and Expires Wed, 31 Dec 1969 19:00:00 EST. The other env does not show this.
I've done a diff of the server.xml, web.xml and context.xml of Tomcat, and there are no major differences.
Googling results in some posts related to SSL config, but I cant figure what exactly the issue is.
Response header with cache-control and expires in the past:
Cache-Control private
Content-Length 0
Date Fri, 06 Mar 2015 16:08:16 GMT
Expires Wed, 31 Dec 1969 19:00:00 EST
Location https://myhost.com/mypage
Response HTTP/1.1 302 Found
Server Apache-Coyote/1.1
|
Tomcat and cache-control: Private, and Expires: <date in past> - Where is this set?
|
I would just use Rails.cache like so:
def self.some_long_query_that_changes_every_day
Rails.cache.fetch ['some_cache_key'], expires_in: 12.hours do
self.where(field: value)
end
end
fetch will either read from the unexpired cache or make the db query and store it in the cache with that key.
The only tricky part is the expires_in part. Depending on when exactly your data changes, you might want to compute the expires_in depending on what time it gets stored.
expire_in = Time.now.utc.end_of_day - Time.now.utc
Rails.cache.fetch ['some_cache_key'], expires_in: expire_in....
Or something similar.
|
In my Rails app, I only do 10 unique SQL queries. However, each takes a long time (1 - 5 seconds). The result of each query only changes every 24 hours.
What solutions are available to make this more performant?
I'm using Postgres and Ruby on Rails.
Should I be caching query results somewhere? Should I be using "stored procedures" (don't know what they are yet)? Is there something else I should be researching?
|
Improve performance for a SQL query that returns the same result for 24 hours
|
sync flushes outstanding file writes. It doesn't affect cached file reads, though. The drop_caches method you found online does clear the disk cache, so any future read will also hit the disk.
All this is unrelated to L1/2/3 CPU caches. Couldn't be, even. The sync function itself will be in L1 cache!
You need assembly code to flush the cache, but you forgot to state which CPU you have.
|
I want to run some experiments on an algorithm in order to see how cache efficient it is.
I run the main code of the algorithm on one input several times (iterations), get the values of different counters (branch mispredictions, L2, L3 cache accesses, misses etc) and then after all the iterations are finished I find the average of each counter and return it as an output.
In order for the experiment to be precise, I need to clear the cache before every new iteration.
So the code is looking something like this:
main()
for (it = 0; it < iterations; it++)
clear_cache();
run algorithm
update counters
return average of all counters
Everything is working as expected but I am not very sure about how to do the clearing of the cache properly.
I have found the following method online:
void clear_cache(){
sync();
std::ofstream ofs("/proc/sys/vm/drop_caches");
ofs << "3" << std::endl;
sync();
}
However if the total amount of iterations is large, this method takes a lot of time to execute. On the other hand if I completely remove sync(); the clearing process becomes much faster.
But I have no idea what sync(); does in practice. Why does everything becomes faster without sync();? Do I need this call in order to be sure that all L1,L2 and L3 caches will be clear before each new iteration?
thank you in advance
|
What would be the most correct way to clear L1,L2 and L3 caches in C++?
|
I think it's a perfectly valid approach, and, to give an example, the play2-auth library provides a way to do this with its CacheIdContainer.
As the author there points out the main advantage of this stateful approach over one using session cookies is that it invalidates a user's prior sessions when they log in somewhere else.
The main disadvantage, at least if you're using Play's default EHCache, is that sessions will not persist across server restarts, but you could use something like memcache to get around that.
|
What I want to do is to implement a simple authentication mechanism in my Play application. Unlike it is done in Play's ZenTask Tutorial, I don't think it is a good idea to store the session id of an authenticated user solely in a session (which, in Play, is a signed cookie), because then the server does not have any control of the login state of users that are already logged in. Image a user account gets deleted or you want to enforce the logout of a specific user - in case this user has a valid cookie, he still will be authenticated successfully on the next request because the server will only check for the presence of a session id in the cookie.
So I'm wondering: what about using the Play cache API for storing session ids of users? On every page request, the session id included in the request could be looked up in the cache. If it is not there, then the user has to log in.
The benefits from my point of view:
the mentioned problem is gone. Deleted users or users for which a logout is enforced are no longer logged in because the cache contents can be changed on the server side
At the moment, I don't need more than one machine for the play application, so Play could internally use EHCache. In case I need to scale and have to deploy additional machines in the future, EHCache could be replaced by an external and distributed memached server without having to change the code.
What do you think?
|
Using the Play cache API for storing user session ids?
|
2
Try this:
cache_clear_all('field:node:' . $node->nid, 'cache_field');
Share
Improve this answer
Follow
edited Oct 17, 2019 at 8:26
simhumileco
33.1k1616 gold badges141141 silver badges121121 bronze badges
answered Mar 1, 2015 at 8:36
rafatrafat
82722 gold badges1010 silver badges2525 bronze badges
Add a comment
|
|
In Drupal 7 Views 3 how do I programmatically clear the cache of a view I've created?
I don't want to clear all caches or even all views caches, just a specific view.
Thanks!
|
How to programmatically clear a cached View in Drupal 7?
|
Use a disk cache. Jack Wharton's DiskLruCache is very good https://github.com/JakeWharton/DiskLruCache.
It will save what you want to disk and read from it, and you can build around it to set max-age values for cache.
|
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the preferred way of caching different objects (including images) on Android? My goal is to cache some data for quick access, and to keep them available for longer time (for days).
Thanks!
|
Best solution to cache objects and images on Android? [closed]
|
You cannot do the initialization at program start, but you can do it at the first method call. All further calls will access the cached value instead of recomputing your value.
Since rust forbids things with destructors inside static variables, you need to do your own cleanup management. Logically this means you need unsafe code to break rust's safety system. The following example uses a static mut variable to cache a heap allocated object (an i32 in this case).
The cacheload function works like a Singleton.
Just remember to call cachefree() from c after you are done.
use std::{ptr, mem};
static mut cache: *const i32 = 0 as *const i32;
unsafe fn cacheload() -> i32 {
if cache == ptr::null() {
// do an expensive operation here
cache = mem::transmute(Box::new(42));
}
return *cache;
}
unsafe fn cachefree() {
if cache != ptr::null() {
let temp: Box<i32> = mem::transmute(cache);
cache = ptr::null();
drop(temp);
}
}
fn main() {
let x;
unsafe {
x = cacheload();
cachefree();
}
println!("{}" , x);
}
|
I'd like to load data from a file, then cache this data (including quite large arrays) in a static variable. This obviously is not the preferred way of doing this, but:
I'm writing a Rust library invoked by a C(++) program, and don't currently have any objects which out-live invocation of the Rust functions. Using a static avoids me having to hack up the C code.
The program doesn't do anything concurrently internally, so synchronisation is not an issue.
How can this be done in Rust?
I have found lazy-static which solves a similar problem, but only for code not requiring external resources (i.e. items which could in theory be evaluated at compile time).
|
Caching externally-loaded data in a static variable
|
It applies to writes as well, failure to write to the store does not affect rest of the transaction.
The reason for this is that the actual persistence API is not transactional (edit: newer versions of Infinispan support transactional persistence, too). Therefore, with 2-phase commits (in first phase - prepare - all locks are acquired, in second one - commit - the write is executed) the write to the store is executed in the second phase. Therefore, the failure cannot rollback changes on different nodes.
Although Infinispan is trying to get close to strongly consistent in-memory database, it is still rather a cache given the guarantees. If you are more interested in the design limitations (and some of them also theoretical limitations), I recommend reading Infinispan wiki.
|
I am using Infinispan 6.0.2 via the Wildfly 8.2 sub-system. I have configured a transactional cache that uses a String Based JDBC Cache Store to persist content placed in the infinispan cache.
My concern is that after reading the following in the Infinispan documentation that there is potential for the cache and cache store to become out of sync when putting/updating/removing multiple entries into the cache in the same transaction due to the transaction committing/rolling-back in the cache but only partial succeeding/failing in the cache store.
4.5. Cache Loaders and transactional caches
When a cache is transactional and a cache loader is present, the cache loader won’t be enlisted in the transaction in which the cache is part. That means that it is possible to have inconsistencies at cache loader level: the transaction to succeed applying the in-memory state but (partially) fail applying the changes to the store. Manual recovery would not work with caches stores.
Could some one please clarify if the above statement only refers to loading from a cache store if it also refers to writing to a store as well.
If this is also the case when writing to a cache store are there any recommended strategies/solutions for ensuring a cache and cache store remain in sync?
The driving factors behind this for me is that I am using Infinispan both for write-through and over-flow of business critical data and need confidence that the cache store correctly represents the state of the data.
I have also asked this question on the Infinispan Forums
Many thanks in advance.
|
Enlisting a Infinispan Cache Store in a Cache Transaction?
|
3
Some research shows that this is called fingerprinting. See http://guides.rubyonrails.org/asset_pipeline.html#what-is-fingerprinting-and-why-should-i-care-questionmark (that doc is for Rails, but HTTP concepts are identical to node of course).
Node Static Asset does this for express.
var staticAsset = require('static-asset');
app.use(staticAsset(__dirname + "/public/") );
Then in a template:
<script src="{{ assetFingerprint("/client.js") }}"></script>
There is also Static Expiry which works similarly.
Share
Improve this answer
Follow
edited Jan 14, 2015 at 12:44
answered Jan 14, 2015 at 12:30
mikemaccanamikemaccana
116k101101 gold badges404404 silver badges509509 bronze badges
Add a comment
|
|
I'm aware of Express' maxAge directive for static content:
app.use(express.static(__dirname + '/public', { maxAge: 86400000 }));
However I'd like to set up a system where:
Browsers cache any resource that has not changed
Browsers fetch the latest version of resources that have changed
I understand this is normally done with checksums, ie: serve all resources with a checksum as part of their URL. Old URLs are cached forever, new content means new URLs.
How can I set this up in express?
|
How can I make express do checksum-based caching?
|
You can do Session.Abandon() if you are inside application. But here you want to remove session from Redis from outside application. You can do that as long as you know application name (the one you provided inside web.config) and session id.
Session Data is stored inside Redis as _Data and some supporting internal data is stored inside Internal. If user is concurrently running another page you might see _Write_Lock.
If you remove all three from Redis it is basically equivalent of doing Session.Abandon(). If you are going to do this using C# program using StackExchange.Redis then I would recommend removing it using LUA script so all three will be removed at once and no other command can intervene.
You should have a place where you can find that database entry has been modified and run this code when necessary.
string applicationName = "<Actual Application Name>";
string sessionId = "<Actual Session Id>";
RedisKey dataKey = String.Format("{0}_{1}_Data", applicationName, sessionId);
RedisKey internalKey = String.Format("{0}_{1}_Internal", applicationName, sessionId);
RedisKey writeLockKey = String.Format("{0}_{1}_Write_Lock", applicationName, sessionId);
RedisKey[] keys = new RedisKey[3];
keys[0] = dataKey;
keys[1] = internalKey;
keys[2] = writeLockKey;
string removeSessionScript = (@"
redis.call('DEL',KEYS[1])
redis.call('DEL',KEYS[2])
redis.call('DEL',KEYS[3])"
);
db.ScriptEvaluate(removeSessionScript, keys, null);
|
I am using the ASP.Net Session state using the NuGet RedisSessionStateProvider.
I am consuming the session data from the application using something like this:
public UserSessionData GetUserSessionData()
{
if (HttpContext.Current.Session == null || HttpContext.Current.Session["Key"] == null)
{
UserSessionData sessionData = ReadSessionFromDatabase();
HttpContext.Current.Session.Add("Key", sessionData);
return sessionData;
}
else
{
return (UserSessionData)HttpContext.Current.Session["Key"];
}
}
With the method above, the first time the value is read from the Database and stored in the Session (Redis Cache). Next time the value is requested is read from Redis Cache without going to the SQL.
It works fine. Sometimes when I need to invalidate the values cached and force a read from the database I call HttpContext.Current.Session.Abandon(). This is done as example when the user changes his plan.
Imagine a situation where I need to invalidate the cache because some change in the Database but this change is no trigger by the user. This change is done by another website (some internal website for manage users) or is done by a Webhook (a plan change notification for the user).How would you force the user to re again the data from the Database (delete cached data) when this is not trigger in the HttpContext?
I tested flushing all the redis cache with flushdb and it works. But off course it force all user session to read data again. How would you invalidate cache for only some user?
|
Redis Session State Provider invalidate session
|
According to docs 0 means that cache is disabled.
Just set it to some large value. If you need it in many places define it as a constant to avoid confusion of magic number antipattern, ie:
define('IMMUTABLE_CACHE', 60 * 60 * 24 * 365 * 100);
$channels = Channels::model()->cache(IMMUTABLE_CACHE);
|
I'm using query caching with infinite expire time. Consider a piece of code below for example:
$channels = Channels::model()->cache(0)->findAll(array('order' => 'channel_name'));
This statement is supposed to make in entry in the cache and it is doing, but it is not fetching the data from cache, rather it is directly going to DB for the result.
While, if I provide a expire time > 0 (zero), then it works smoothly. For example:
$channels = Channels::model()->cache(20)->findAll(array('order' => 'channel_name'));
works perfectly for 20 seconds and fetch the results from cache.
We are confirmed about it as we enabled the log and saw the profiling.
Infinite expire time works also fine for caching key/value pair using Yii::app()->cache->set() or Yii::app()->cache->get()
Any idea if im doing anything wrong ?
thanks.
|
Yii query caching with infinite expire time
|
Not possible.
suPHP runs each PHP request in a new process, so caching extensions that try to save data in memory across requests don't work. (Or, rather, they work, but any stored data is only accessible to that job, and is lost at the end of the request.)
Use something like memcached if you need data caching.
|
Is it possible to use apcu (as a php 5.5 module) in combination with suPHP?
The answer to What is best PHP Handler for APC says no:
suPHP also cannot work with an opcode caching extension such as eAccelerator or APC
but this post is over a year old and maybe not referring to apcu.
I can successfully enable the apcu module (in cPanel) and transfer content via apc_store and apc_fetch - but not between requests. It forgets what I've been storing when I reload the script/page.
So my first concern is to rule out if I'm trying something that's impossible anyway?
PS: for the record, What is userland caching APCu extension in PHP? gives some helpful background
|
apcu and suPHP - possible?
|
3
For caching static files, I would recommend you to do this way
location /static/ {
alias /home/ubuntu/app/staticfiles/;
expires 365d;
}
for "No such file or directory" errors do run
./manage.py collectstatic
Share
Improve this answer
Follow
answered Dec 13, 2015 at 10:59
narennaren
14.9k55 gold badges4040 silver badges4545 bronze badges
Add a comment
|
|
I am trying to configure Nginx to leverage on static file caching on browser. My configuration file is as following
server {
listen 80;
server_name localhost;
client_max_body_size 4G;
access_log /home/user/webapps/app_env/logs/nginx-access.log;
error_log /home/user/webapps/app_env/logs/nginx-error.log;
location /static/ {
alias /home/user/webapps/app_env/static/;
}
location /media/ {
alias /home/user/webapps/app_env/media/;
}
...
}
When I add in the following caching configuration, the server fails to load static files and I am not able to restart my Nginx.
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
}
The nginx-error log shows open() "/usr/share/nginx/html/media/cover_photos/292f109e-17ef-4d23-b0b5-bddc80708d19_thumbnail.jpeg" failed (2: No such file or directory)
I have done quite some research online but cannot solve this problem.
Can anyone help me or just give me some suggestions on implementing static file caching in Nginx? Thank you!
|
Django Nginx static file caching on browser
|
you can try the following:
Cast the entry in the EntryProcessor to BinaryEntry and set the expiration time.
For example:
public class MyEntryProcessor extends AbstractProcessor implements PortableObject {
@Override
public Object process(Entry myEntry) {
((BinaryEntry)myEntry).expire(100);
return myEntry;
}
}
http://docs.oracle.com/middleware/1212/coherence/COHJR/com/tangosol/util/BinaryEntry.html
|
I'm trying to implement a business functionality which uses Coherence transient caches.
One of the features I was planning to depend upon is auto-eviction of cache entries, when providing a (configurable) time-to-live at the time of putting an item in the cache. The interface NamedCache provides an API to achieve this (http://download.oracle.com/otn_hosted_doc/coherence/330/com/tangosol/net/NamedCache.html#put(java.lang.Object, java.lang.Object, long)).
However, I'm also planning to use Entry-Processors to ensure effective concurrency across the cluster. I'm stuck at a point now where, within the scope of the processor, I'm supposed to work with InvocableMap.Entry to get/set values with a key in the cache. Unfortunately, there is no setValue method which lets me specify the time-to-live value.
I'm assuming here that interfacing directly with the NamedCache reference inside the EntryProcessor's process method will not be a good idea, and will compromise the concurrency guarantees which EntryProcessor provides.
Can you please share your thoughts on what could be the best way to get an entry evicted after a certain amount of time (which is dynamically decided), while ensuring optimal concurrency across a cluster of nodes?
I'm not completely hung up on using the auto-eviction functionality. However, if I were to abandon that, I may have to rely upon a timer-based programmatic removal of the entry, which works reliably across a cluster. Again, I'm falling short of ideas on this one. Ideally, I would want Coherence to deal with this.
Many thanks in advance.
Best regards,
- Aditya
|
Coherence EntryProcessor query
|
Short answer: you can't change eviction timeout value, or any property of Cache / LoadingCache created by CacheBuilder.
Anyway, why would you want to change the timeout? (Also bare in mind that Guava Caches are quite simple.) If you really do want to change the timeout, you have two choices:
create new Cache with target semantics and copy old cache contents, ex.
LoadingCache<String, Long> newCache = CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.SECONDS)
.removalListener(inQueueRemovalListener)
.build(inQueueCacheLoader);
newCache.putAll(inQueueLoadingCache.asMap());
but you'll loose original access times etc.
don't use CacheBuilder at all and implement LoadingCache yourself, for example using AbstractLoadingCache skeletal implementation with your own policy for changing timeouts. It's not easy though, because you have nice LoadingCache's API but you have to implement whole thing by yourself (I tried it once but ended using more advanced cache than Guava's one).
|
I am using the following:
LoadingCache<String, Long> inQueueLoadingCache = CacheBuilder.newBuilder()
.expireAfterWrite(120, TimeUnit.SECONDS)
.removalListener(inQueueRemovalListener)
.build(inQueueCacheLoader);
After every 120 seconds, the cache entries are evicted and it works as expected.
My question is: How do I change the timeout value, say from 120 to 60 seconds, for the current cache? What will happen to the cache entries during this change?
|
Google Guava Cache - Change the eviction timeout values during run time
|
flush=1 will flush your current page. Simon Welsh has said it will:
Rebuild the manifests (YAML, statics, classes, templates)
Flush the current page's templates
Regenerates images on the current page
flush=all will flush every template in the site.
There is a Google group discussion on this topic:
https://groups.google.com/forum/#!topic/silverstripe-dev/RNWCiFAnRI0
|
So I can add URL params to flush the SilverStripe cache and it seems there are at least 2 options:
http://example.com?flush=1
http://example.com?flush=all
What is the difference between these options, and are there any other options for flushing?
|
What are the different types of "flush" that can be done in SilverStripe, and how are they different?
|
First of all I doubt that "The cache-line of my computer is 64K bytes". It's most likely to be 64 Bytes only. Let me try to answer your questions:
Question 1. For my case, is there a lot of cache misses due to my access pattern is random?
Not necessarily. It depends on how many operations you do on a buffer once it is cached.
So if you cache a 2K buffer and do lots of sequential work on it your
cache hit rate would be good. As Paul suggested, this works even better with hardware prefetching enabled.
However if you constantly jump between buffers and do relatively
low amount of work on each buffer, the cache hit rate will drop.
However 1024 x 2KB = 2MB so that could be a size for an L2 cache (if you have also L3, then L2 is generally smaller). So even
if you miss L1, there's a high chance that in both cases you will
hit L2.
Question 2. What is the size of neighbouring data a modern computer caches?
Usually the number of neighbors fetched is given by the cache line size. If the line size is 64B, you could fetch 16 integer values. So on each read, you fill a cache line. However you need to take into consideration prefetching. If your CPU detects that the memory reads are sequential, it will prefetch more neighbors and bring more cache lines in advance.
Hope this helps!
|
I have a continuous memory of 1024 buffers, each buffer sizes 2K bytes. I use a linked list to keep record of available buffers (Buffer here can be thought of being used by Producer and Consumer). After some operations, the order of buffers in the link list becomes random.
The modern computer architecture favours compact data, locality a lot. It caches neighbouring data when a location needs to be accessed. The cache-line of my computer is 64(corrected from 64K) bytes.
Question 1. For my case, is there a lot of cache misses due to my access pattern is random?
Question 2. What is the size of neighbouring data a modern computer caches? I think if you access a location in an array of integers, it will cache neighbouring integers. But my unit data (2K) is much larger than int (4). So, I am not sure how many neighbours will be cached.
|
Size of neighbouring data a modern computer caches for locality favour
|
HazelcastCachingProvider is just a delegate to automatically choose either client based or server bases CachingProvider.
For recent 3.4 SNAPSHOTS HazelcastCachingProvider also was moved to com.hazelcast.cache.HazelcastCachingProvider. For the new documentation please see the just drafted documentation version for 3.4: https://github.com/hazelcast/hazelcast/blob/master/hazelcast-documentation/src/JCache.md
You'll see it got waaaaaaay longer :)
|
I'm having a strange warning when I try to use Hazelcast-based implementation of JCache (i.e. JSR 107) as follows (original sample code):
// Explicitly retrieve the Hazelcast backed javax.cache.spi.CachingProvider
CachingProvider cachingProvider = Caching.getCachingProvider(name);
// Retrieve the javax.cache.CacheManager
CacheManager cacheManager = cachingProvider.getCacheManager("com.hazelcast.cache.impl.HazelcastCachingProvider");
Here is the logged message:
oct. 30, 2014 5:17:59 PM com.hazelcast.cache.impl.HazelcastCachingProvider
WARNING: Could not load client CachingProvider! Fallback to server one... java.lang.ClassNotFoundException: com.hazelcast.client.cache.impl.HazelcastClientCachingProvider
Why it si trying to load HazelcastClientCachingProvider will I asked for com.hazelcast.cache.impl.HazelcastCachingProvider. Am I using the wrong JCache provider?
|
HazelcastClientCachingProvider class not found exception when requesting hazelcast jcache provider
|
Your Internet search gave you the right answer.
Block size of 16 bytes -> need 4 bits to specify the offset within the block.
8K byte cache and 16 byte lines -> 512 blocks. (8K / 16 = 512)
Direct mapped cache -> 512 / 1 way set associativity = 512 sets
512 sets -> need 9 bits for the index (512 = 2^9)
With a 32 bit address, if 4 bits are used for the block offset and 9 for the index that means that the remaining 19 bits are needed for the tag.
Since this is a direct map cache, no bits are needed for a replacement policy (e.g. LRU). You'll need at least one bit for validity. With 2 bits you can implement a cache coherence algorithm like MESI. So figure 20 to 21 bits are needed per block.
|
If i have a
32bit address
,
cache size(c) 8 KB
,
Block Size(b) 16 B
,
Set Associativity(a) 1
its a Direct Mapped Cache
what would be the bits per line in cache? including dirty bit and validity bit.
what would be the total no of lines in cache?
some idea which i got via searching on internet is
offset bits = log b = 4 bits
index bits = log c/b * 1024 = 9 bits
tag bits = 32 - offset - index = 19 bits
validity and dirty would have 1, 1 bit
still confused that how i will calculate size of cache or how many lines this cache would have?
|
Cache bits per row and total length
|
This would work as long as CacheEntry is a proper immutable object (as opposed to a mere effectively immutable object). This is because immutable objects can be safely published without synchronisation and object reference assignment is atomic.
In other words, it wouldn't be safe if CacheEntry is not fully immutable, as the consumer thread may see an object that isn't fully constructed. Also, if what is cached is primitive types whose assignments aren't atomic (double, long), the consumer thread could see garbage (half assigned values).
EDIT:
According to Java Concurrency in Practice, an object can be safely published without synchronization if:
Its state cannot be modified after construction
All its fields are declared final
It is properly constructed (the this keyword does not escape during construction)
|
I'm curious whether this caching idea is guaranteed to work:
@RequiredArgsConstructor @Getter class CacheEntry {
static CacheEntry get(String string, int start) {
int hash = string.hashCode() ^ start; // or something better
int index = hash & (cache.length-1);
CacheEntry result = cache[index];
if (result!=null && result.matches(string, start)) return result;
result = new CacheEntry(string, start, computeSomething(string, start));
cache[index] = result;
return result;
}
private boolean matches(String string, int start) {
if (string.equals(this.string)) return false;
if (start == this.start) return false;
return true;
}
private static ImmutableSomething computeSomething(String string, int start) {
...
}
private static final CacheEntry[] cache = new CacheEntry[256];
private final String string;
private final int start;
private final ImmutableSomething something;
}
The annotations come from lombok. Just imagine each does what its name says.
The goal is to save calls to computeSomething and also to minimize allocations.
The caching is neither synchronized nor thread local. There's no guarantee that one thread will see updates done by another one. That's acceptable. Neither is there any guarantee that one thread doesn't overwrite the entries from another one. That's acceptable, too.
In a small benchmark I wrote it lead to a nice speedup when compared to sane caching alternatives. My concern is correctness: Can ever happen, that a thread sees an invalid entry (e.g., one containing a wrong something)?
|
Is this caching thread safe?
|
2
Example for using DRF-extensions caching with all GET params as key hash on ReadOnlyModelViewSet.
Define your key constructor (key hash):
from rest_framework_extensions.key_constructor.constructors import DefaultKeyConstructor
from rest_framework_extensions.key_constructor.bits import QueryParamsKeyBit
class QueryParamsKeyConstructor(DefaultKeyConstructor):
all_query_params = QueryParamsKeyBit('*') # Don't change, * is default on drf-extension dev version only
And your view:
class UserViewSet(ListCacheResponseMixin, viewsets.ReadOnlyModelViewSet):
serializer_class = UserSerializer
list_cache_key_func = QueryParamsKeyConstructor()
set DRF-extensions and django caching settings in settings.py, for example:
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0"
}
}
REST_FRAMEWORK_EXTENSIONS = {
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 20
}
Share
Improve this answer
Follow
answered Sep 18, 2015 at 6:31
hagaihagai
14822 silver badges88 bronze badges
Add a comment
|
|
I'm using Django Rest Framework and DRF-extensions (http://chibisov.github.io/drf-extensions/docs/#how-key-constructor-works).
I have an API call /user/:id/products, which provides the full list of products that a user has access to. Because it's an expensive query, I'm caching it based on method id, format, language, user, and retrieval SQL query.
I have another API call /pay which handles all of our payments. The product ids are POST arguments to that API call.
After a user pays, immediately it directs them to the product page--but since the product query is cached, it still displays the old list of products, not the updated list with the new products they just purchased. I know about the cache.delete method, but getting the key from /pay is difficult since it's a completely different API call.
What I would like to do is add a parameter force_refresh to the /user/:id/products API call, that, if present, calculates the hash key as if the force_refresh parameter weren't present and then clears the cache for that key. However, I can't find the right place in KeyConstructor within drf-extension's caching framework to stick this in. What is the best way for me to let the server know to delete the cache for this query?
|
How to use a query parameter to have the server delete the API call cache (django, DRF)
|
If you don't have access to the Apache configuration itself, you can try setting expiration rules via an .htaccess file. Contrary to popular belief, not only Rewrite rules, but any Apache configuration rules can be contained there … if the Apache config allows it. But, it's worth giving it a try.
To only cache certain files, you can use a directive like:
<FilesMatch "\.(ico|pdf|jpg|png|gif|js|css)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>
(You can remove those extensions you don't want to cache, and add others.)
Now, as for CSS and JS, it is generally recommended to do the following: Instead of changing the file name itself, simply change the references to theses files by adding a (meaningless) query string to them.
For example, when embedding a JS file, do it like this:
<script src="/path/to/file.js?rev=123" type="text/javascript"></script>
Next time you update that file, simply increment the rev number.
|
I maintain a website that receives regular updates and style changes. Following these changes, often my client will protest that I've somehow 'broken' their website purely because their browser has cached the old CSS stylesheets and/or scripts, sometimes even after a refresh.
This question (How to control web page caching, across all browsers?) explains how I can overcome the problem with just about any of the technologies at my disposal but I don't want a blanket no-cache solution, I would like the browser to maintain the images - particularly the larger ones that rarely change.
Is this possible using, say, PHP, HTML, or even JavaScript?
Call me OCD but I'd prefer not to modify the file names each time there is a change to the content (though I'm willing to resort to this), I'm looking for a control mechanism if one exists.
I understand this can be achieved via Apache Expires module (as explained here: Website image caching with Apache) but the hosting account my client uses doesn't appear to grant me the access to do it and if I'm honest I'm far from an Apache expert.
|
Force browser to only cache images (not scripts and links)
|
What I would do to always load a non-cached image in fancybox is to dynamically add a version ?v= trialing parameter to the fancybox href using the beforeLoad callback like :
$(".fancybox").fancybox({
beforeLoad: function () {
this.href = this.href + "?v=" + new Date().getTime()
}
});
That way, fancybox will always (re)load the image instead of using a cached one.
See JSFIDDLE
|
I'm running into issues where fancybox is loading a cached image. I would like to ensure that the image is not cached before it appears on the page, but I haven't been success with trying to accomplish this through its various callbacks (beforeShow, afterShow, afterLoad, beforeLoad).
This is what I currently have:
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
},
beforeShow: function(){
if($('.fancybox-image').length>0){
console.log($('.fancybox-image').attr('src'));
clearCacheImages('fancybox');
}
}
});
function clearCacheImages(source){
if(source == "all"){
// console.log('loading all images');
jQuery('img').each(function(){
jQuery(this).attr('src',jQuery(this).attr('src')+ '?' + (new Date()).getTime());
});
}else if(source=="fancybox"){
// console.log('loading fancybox image: ' + $('.fancybox-image').attr('src'));
$('.fancybox-image').attr('src',$('.fancybox-image').attr('src')+ '?' + (new Date()).getTime());
}
}
When I click the next button in the fancybox slideshow, it shows the previous image rather than the first. Anyone know how and when to ensure that the fancybox image isn't cached?
|
fancybox ensure fancybox-image isn't cached
|
3
cache is useless in the context you are using it. In this situation cache is saying save the result of the map, .map(word => (word, 1)) in memory. Whereas if you didn't call it the reducer could be chained to the end of the map and the maps results discarded after they are used. cache is better used in a situation where multiple transformations/actions will be called on the RDD after it is created. For example if you create a data set you want to join to 2 different datasets it is helpful to cache it, because if you don't on the second join the whole RDD will be recalculated. Here is an easily understandable example from spark's website.
val file = spark.textFile("hdfs://...")
val errors = file.filter(line => line.contains("ERROR")).cache() //errors is cached to prevent recalculation when the two filters are called
// Count all the errors
errors.count()
// Count errors mentioning MySQL
errors.filter(line => line.contains("MySQL")).count()
// Fetch the MySQL errors as an array of strings
errors.filter(line => line.contains("MySQL")).collect()
What cache is doing internally is removing the ancestors of an RDD by keeping it in memory/saving to disk(depending on the storage level), the reason an RDD must save its ancestors is so it can be recalculated on demand, this is the recovery method of RDD's.
Share
Improve this answer
Follow
edited Jul 15, 2014 at 14:18
answered Jul 15, 2014 at 14:10
aaronmanaaronman
18.5k88 gold badges6363 silver badges7979 bronze badges
1
You explain how cache is expected to work, and to be used, but not why it is slow. See my related but more precise question
– Juh_
Jun 16, 2016 at 12:40
Add a comment
|
|
When I use the cache to store data,I found that spark is running very slow. However, when I don't use cache Method,the speed is very good.My main profile is follows:
SPARK_JAVA_OPTS+="-Dspark.local.dir=/home/wangchao/hadoop-yarn-spark/tmp_out_info
-Dspark.rdd.compress=true -Dspark.storage.memoryFraction=0.4
-Dspark.shuffle.spill=false -Dspark.executor.memory=1800m -Dspark.akka.frameSize=100
-Dspark.default.parallelism=6"
And my test code is:
val file = sc.textFile("hdfs://10.168.9.240:9000/user/bailin/filename")
val count = file.flatMap(line => line.split(" ")).map(word => (word, 1)).cache()..reduceByKey(_+_)
count.collect()
Any answers or suggestions on how I can resolve this are greatly appreciated.
|
spark map(func).cache slow
|
Most of your assumptions are correct except the following ones:
saveOrUpdate is not used to propagate update changes but to:
persist a transient entity (e.g. save)
reattach a detached entity (e.g. update)
When you load an entity in a Session, it's loaded into 1st level cache and any change you make to the entity will be discovered and propagated during flush time. So you don't have to call saveOrUpdate in this case.
In your example at step 3), Hibernate doesn't detect any change in your first session so it has nothing to update, even if some other session has already update the entity.
In order to prevent "lost updates" Hibernates offers:
optimistic locking (@Version)
pessimistic locking (instructing the db to acquire locks)
If you choose optimistic locking, and in step 3. you change the entity name to 'CCC' you will get a org.hibernate.StaleObjectStateException (during flush time), indicating you have a stale version of the entity you try to save.
|
I'm new in Hibernate, I know that level1 cache is session-scope and level2 cache is cross-sessions, suppose I have an entity Person which contains fields Id and Name.
create session1 and load a person, Id=1, Name="AAA"
create session2, update this person,
session.saveOrUpdate(person), Id=1, Name="BBB"
back to session1 and update again,
session.saveOrUpdate(person), Id=1, Name="AAA"
Below is my guess about what hibernate do internally:
for step 1
hibernate search level1 cache of session1, nothing there
hibernate search level2 cache, nothing there
hibernate search database
entity is stored into level1 and leve2 caches
now both level1 and level2 caches have an entity, person with id=1 and name="AAA"
for step 2
hibernate search level1 cache of session2, nothing there
hibernate search level2 cache, get the entity(person with id=1 and name="AAA")
store this entity into level1 cache of session2
compare this entity to the parameter of session.saveOrUpdate(person)
name is changed, so an update is needed
level1 cache of session2 is updated
level2 cache is updated
database is updated
for step 3
hibernate search level1 cache of session1, get the entity(person with id=1 and name="AAA")
compare this entity to the parameter of session.saveOrUpdate(person)
nothing changed
so database will not be updated?
I'll try to write some test code, but before that, it would be strongly appreciated if someone can point out any misunderstanding above, that would be helpful for me to understand hibernate caches deeper.
Thanks in advance.
|
How does Hibernate 1st and 2nd Level cache work with multiple sessions
|
Try setting the following in you OnActionExecuting to prevent caching:
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
Prevent Caching in ASP.NET MVC for specific actions using an attribute
However, according to
Authorize Attribute Lifecycle
ASP.NET will cache ActionFilter attributes. So you may not be able to call the constructor more than once and will instead will have to refactor your code for maintaining the attribute state.
Update
You may be able to controll this by setting the cache policy:
protected void SetCachePolicy( AuthorizationContext filterContext )
{
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}
Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed
|
I have an attribute on a controller, controller action:
[InitialisePage(new[]{PageSet.A, PageSet.B})]
public ActionResult Index()
{
...
}
attribute:
public class InitialisePageAttribute : FilterAttribute, IActionFilter
{
private List<PageSet> pageSetList = new List<PageSet>();
public InitialisePageAttribute(PageSet pageSet)
{
this.pageSetList.Add(pageSet);
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
MySettings.GetSettings().InitialiseSessionClass(pageSetList);
}
}
When the action is called for the second time the constructor for the attribute isn't called? It just goes straight to the OnActionExecuting method, the pageSet list is still set.
I guess these are cached, where are they cached? Is this optional behavior?
thanks
|
MVC Controller Attribute, are these cached? Attribute constructor only called once?
|
When you cache the sprite, you are saving off how it looks at that instant.
Can you explain why you want to cache it? The only reason I can think of to cache it would be to apply filters. Each time you cache it, the contents are drawn to an off-screen canvas, which is then drawn in place of it. This makes a lot of sense if you have complex content, like a container or graphics, which do not change, but with the spritesheet, it means you are creating a new bitmap to draw a bitmap. The spritesheet itself is a great way to be filesize, network, and GPU-optimzed, so re-caching it is basically negating all those benefits.
If you want to cache anyways, you will need to re-cache it, or call updateCache() every time it changes. Here is an example using the ticker.
createjs.Ticker.on("tick", function() {
user.hero.updateCache();
// or
user.hero.cache(0,0,30,40)
}, this);
Here is a quick demo I did a while back using a few approaches for filters. It provides an example of constant re-caching, as well as an example where the entire spritesheet is cached to apply the filter once, and then that cached version is used for the sprite.
http://jsfiddle.net/lannymcnie/NRH5X/
|
How can I cache SpriteSheets in EaselJS? I have a Sprite object and when I use user.hero.cache(0, 0, 30, 40); it stops playing animation (probably because I'm just caching the current frame, not the entire SpriteSheet image). So how can I cache it?
Here's my relevant EaselJS code:
data = {
images: ["Graphics/hero.png"],
frames: {
width: 30,
height: 40
},
animations: {
stand: 0,
run: [1, 2, "runLoop", 0.15],
runLoop: [3, 7, true, 0.15],
jump: [8, 10, "happy", 0.5],
happy: 11,
fall: 12,
stopFalling: [13, 14, "stand", 0.2],
almostFalling: [16, 19, true, 0.1]
}
};
user.hero.spriteSheet = new createjs.SpriteSheet(data);
user.hero = new createjs.Sprite(user.hero.spriteSheet, "stand");
user.hero.name = "hero";
user.hero.x = user.hero.safeX = 40 * 3;
user.hero.y = user.hero.safeY = 0;
user.hero.offset = 4;
user.hero.regX = user.hero.offset + 2;
user.hero.regY = user.hero.offset;
user.hero.width = 30 - (user.hero.offset * 2) - 10;
user.hero.height = 40 - (user.hero.offset * 2);
user.hero.xvel = user.hero.yvel = 0;
user.hero.cache(0, 0, 30, 40); // <--- This is the problem.
movableObjContainer.addChild(user.hero);
movableObj.push(user.hero);
Without cache:
With cache:
I've tried caching the data.image or user.hero.spriteSheet too, without success.
Is there any way to cache the SpriteSheet without compromising its animations?
|
Cache SpriteSheets in EaselJS
|
Answers from: Better Way to Prevent IE Cache in AngularJS?
in AngularJS this snippet should prevent response caching:
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
}]);
Alternatively you could specify it in your backend that the response should not be cached, although the specific implementation of this depends on your backend implementation.
|
My Angularjs app works fine in Chrome but not in IE9 (haven't testing >IE9 yet).
I am fetching some data from the DB and displaying the results in a list. I can then delete the data and add new data saving to the DB each time. IE9 shows the original data that I started with even though when I look in the DB the data has changed as I would expect.
I assume this is down to caching behaviour in IE9 but I'm not sure how I should go about tackling this.
I'm using a MEAN stack. Any suggestions/advice would be great.
|
Angularjs - IE9 Caching Behaviour
|
You are making a mistake giving the ImageLoader a disk cache. Volley already has a shared disk cache for every response, be it an image are not, that works according to HTTP cache headers by default.
You are supposed to provide a memory bitmap cache to the ImageLaoder. Look at the documentation.
The reasoning for it is how Volley is designed. This is the image request logic for Volley:
Image with url X is added to the queue.
Check image memory cache (provided by you) - If available, return bitmap. quickest
Check shared disk cache - If available, check cache headers to see that image is still valid. If valid - add to memory bitmap cache and return. slower, but still pretty quick
This step means that either the image was in the disk cache but its cache headers are missing or expired, or the image wasn't available in the cache at all. Either way, Volley performs a network request and caches the response in both caches. slowest
So by providing a disk cache - you are both slowing down your app and taking up to twice as much disk space with redundant image saving.
Use a memory cache.
|
i'm using volley to load my images and cache them.
mImageLoader = new ImageLoader(getRequestQueue(context), mImageCache);
which mImageCache is a DiskLruImageCache.
volley fetches images from server by ImageRequest which extend the ImageRequest<Bitmap>
and in request class there is boolean that defines whether to cache the response or not
/** Whether or not responses to this request should be cached. */
private boolean mShouldCache = true;
and ImageRequest hasn't disabled mShouldCache.
as you can see the default value is true so after volley fetches an image caches it under the volley cache directory by diskBasedCache.
so now i have to cache bitmap one from ImageRequest and one from ImageLoader how can i disable ImageRequest cache ? or any other suggestions ?
|
volley imageCache and imageRequest both cache the image
|
Not really an answer, just a heads up. Seeing that your question is tagged java, I assume you want to do this from an application, and not from the browser. I'm pretty sure that's impossible, because each Android app is running in it's sandbox. Communication between apps is done through Intents and IPC. In both cases, you are limited by what the target app is offering support for.
|
I am currently trying to find a way to programatically inject items into a mobile browser's cach on Android devices. The browser type doesn't matter, it can be Firefox, Chrome, Android's built in browser, etc.. Is there any documentation or examples of ways to programatically inject objects into the browsers of Android devices?
|
Injecting items in Android browsers caches
|
It is true that IIS caches all the static content by default. The definition of the type of files to be considered as static is defined in the applicationHost.config under the staticContent section. If you want to override the policy or add additional type for caching, then you would need to add/change the Caching/Profiles section
|
I'm doing a research on how IIS static content caching works and the more I read the more confused I get.
According to the offical site:
IIS automatically caches static content (such as HTML pages, images, and style sheets), since these types of content do not change from request to request. IIS also detects changes to the files when you make updates, and IIS flushes the cache as needed.
(http://www.iis.net/learn/manage/managing-performance-settings/configure-iis-7-output-caching)
However, I keep finding articles about how to enable static content caching for iis like this:
http://www.galcho.com/Blog/post/2008/02/27/IIS7-How-to-set-cache-control-for-static-content.aspx
So does iis cache by default or not? Am I maybe confusing client-side and server-side caching? Or are articles like these are outdated?
|
Does IIS cache static content by default or not?
|
Vainilla Spark is not able to do this (at the time of writing - Spark is evolving fast) .
There's a Spark-JobServer contributed by Ooyala that exactly fulfills your needs. It keeps a register with the jars for sequential job submission and provides additional facilities to cache RDDs by name. Note that on a Spark Cluster, the Spark-JobServer acts as a Spark driver. The workers will still need to load the jars from the driver when going to execute a given task.
See docs here: https://github.com/ooyala/spark-jobserver
|
I've got an Apache Spark MLlib Java application that should be run on a cluster a lot of times with different input values. Is it possible to cache the application jar on the cluster and reuse it to reduce startup time, network load and coupling of components?
Does the used cluster manager make any difference?
If the application jar is cached, is it possible to use the same RDD caches in different instances of my application?
|
Is it possible to cache the application jar when running Apache Spark applications on a cluster?
|
3
A coroutine contains a stack and a control block (preserved registers, put at the edge of the stack).
You could not reuse the coroutine itself but you could write your own stack-allocator which pre-allocates and caches stacks.
A newly created coroutine could re-use an already allocated stack from the cache.
Share
Improve this answer
Follow
answered Jun 10, 2014 at 7:02
olkolk
39211 silver badge33 bronze badges
1
Is there any way to avoid writing writing own stack allocator? I.e. if there already exists such allocator, it's better to use it rather than reinventing the own one?
– vralex
Dec 15, 2014 at 10:22
Add a comment
|
|
I'm currently allocating new coroutine instances quite often (see the code in my answer here).
The overhead of this is not trivial.
I would guess that there is some way to make this cheaper by reusing the previously allocated coroutine?
Not sure how to achieve this though?
I could use a boost::pool for the coroutine Allocator. However, that will not work for the StackAllocator, which is the expensive one...
|
Coroutine - Reuse?
|
What you've done is just a set up of a Cache Backend.
In order to benefit from caching you need to find the places where it is appropriate and would have a positive impact on performance: your views, templates..you can cache the whole views, templates, template fragments etc.
If you want some automation to help you, take a look at Johnny Cache package:
Johnny Cache is a caching framework for django applications. It works
with the django caching abstraction, but was developed specifically
with the use of memcached in mind. Its main feature is a patch on
Django’s ORM that automatically caches all reads in a consistent
manner.
Or django-cache-machine package:
Cache Machine provides automatic caching and invalidation for Django
models through the ORM.
There is also an interesting project called django-cacheops that is aiming to improve Django ORM caching, but it uses Redis backend.
Also, django_debug_toolbars caching panel can help you in the future.
Note that django querysets have a built-in internal cache, but it has nothing to do with a cache framework.
Further reading:
Using Django querysets effectively
Caching and QuerySets
|
I have my existing Django web application that uses a MySQLDB without memcaching.
I would like to implement memcaching to improve the responsiveness of this site. I see the instructions here.
However, these instructions leave me with some unanswered question(s). Is this all I need to do to get memcache working after I setup the memcached server? Or do I need to alter any of my code outside of settings.py? Does Django nicely handle all the memcaching operations behind the scenes for me whenever models are read or written? (If so, that's very cool!) How can I see what improvement the memcaching is having on the number of DB accesses?
|
What steps are needed to implement memcached in a Django application?
|
3
I'm almost certain that you're seeing this because inMemoryMisses does not include misses due to expired elements. On a get if the value is stored, but expired then you will not see an inMemoryMiss recorded, but you will see a cache miss.
Share
Improve this answer
Follow
answered May 30, 2014 at 15:41
Chris DennisChris Dennis
46622 silver badges44 bronze badges
Add a comment
|
|
These are the statistics for my Ehcache.
I have it configured to use only memory (no persistence, no overflow to disk).
cacheHits = 50
onDiskHits = 0
offHeapHits = 0
inMemoryHits = 50
misses = 1194
onDiskMisses = 0
offHeapMisses = 0
inMemoryMisses = 1138
size = 69
averageGetTime = 0.061597
evictionCount = 0
As you can see, misses is higher than onDiskMisses + offHeapMisses + inMemoryMisses. I do have statistics strategy set to best effort:
cache.setStatisticsAccuracy(Statistics.STATISTICS_ACCURACY_BEST_EFFORT)
But the hits add up, and the difference between misses is rather large. Is there a reason why the misses do not add up correctly?
This quesiton is similar to Ehcache misses count and hitrate statistics, but the answer attributes the differences to the multiple tiers. There is only one tier here.
|
Ehcache miss counts
|
If you want to use a CacheDependency for another cache key:
The key you depend on (ie OtherKey) must be found in the cache (See this article). Otherwise your items will not be found in the cache.
You need to create a different CacheDependency instance per item. Otherwise you will get the error An attempt was made to reference a CacheDependency object from more than one Cache entry (See the answer to this question)
So your code to insert the items would be something like this:
' Make sure OtherKey is found in the cache
HttpContext.Current.Cache.Insert("OtherKey", "SomeValue")
' Add the items with a different CacheDependency instance per item
Dim Keys As String() = New String(0) {}
Keys(0) = "OtherKey"
HttpContext.Current.Cache.Insert(Key1, Value1, New System.Web.Caching.CacheDependency(Nothing, Keys))
HttpContext.Current.Cache.Insert(Key2, Value2, New System.Web.Caching.CacheDependency(Nothing, Keys))
Please note that if you don´t add the cache item with key OtherKey, the dependent items will never be found.
Then when you remove OtherKey from the cache, the dependent items will be automatically removed. So this line would automatically remove both Key1 and Key2 from the cache:
HttpContext.Current.Cache.Remove("OtherKey")
Hope it helps!
|
Based on a datetime value I insert values into the cache:
Dim Value1 As String = "value1"
Dim Value2 As String = "value2"
Dim Key1 As String = "Key" & New Date(2014, 1, 1, 1, 1, 0).ToString
Dim Key2 As String = "Key" & New Date(2014, 1, 1, 1, 2, 0).ToString
HttpContext.Current.Cache.Insert(Key1, Value1)
HttpContext.Current.Cache.Insert(Key2, Value2)
Is it possible to invalidate those cache items using another cache item as CacheDependency?
I tried the following, but this doesn't work:
Dim Keys As String() = New String(0) {}
Keys(0) = "OtherKey"
Dim MyDependency As New System.Web.Caching.CacheDependency(Nothing, Keys)
HttpContext.Current.Cache.Insert(Key1, Value1, MyDependency)
HttpContext.Current.Cache.Insert(Key2, Value2, MyDependency)
'To clear all cache items:
HttpContext.Current.Cache.Remove("OtherKey")
When I use this (without the remove statement), the items never can be found in the cache. What am I doing wrong here?
|
Clean cache based on DependencyKey
|
Voyage is a an object graph serializer. Therefor the cache is absolutely needed. Your use case is probably not a prominent one of all that were considered when the design was made. You are just writing objects but from the view point of the serializer you could read any time and then it should be correct.
Anyway. Maybe it helps to fine tune your application. What Voyage does is that all active objects are hold in the cache. With active I mean that there is a reference to the object from any processing code at the moment. If the objects are not active anymore the garbage collector removes them and at the same time they are nil'ed in the cache. If the cache grows too big a compaction will start removing all the nil'ed entries making space for new objects.
If you have one method running that keeps a reference to all the objects you serialize than the cache will grow, it will compact but not free slots. So the compaction is tried again in the next step making the whole thing slow.
The thing you could do is that you process your objects (that have to be written) in a way that you hold a few, serialize them and then they should go out of scope so the cleaning process can manage them. Second I would extend the compactLimit on the cache using
VORepository current cache compactLimit: aNumber
This way the compaction is run less often giving your code and GC more time to resolve the problem in parallel.
|
We are using Voyage to store a lot of data to a MongoDB.
Currently the problem is, that Voyage is caching all the objects that are saved to the DB. And whenever the cache approaches the maximum of its size, it's becoming very slow.
Sure, we could just increase the maximum size of the cache, but the class description of VOMongoCache says:
Main purpose is not optimization but prevent duplicated objects (when
they should be the same)
Because we are saving only new generated objects, we don't need these caches anyway.
So we want to completely disable the caching.
Currently we just use this workaround to disable caching:
VOMongoCache>>
at: anOID put: anObject
self compactIfNeeded.
self mutex
critical: [ "objects at: anOID put: anObject" ].
We just commented out the part to add the object to the cache.
Is there any better solution to disable caching completely?
Thanks in advance!
|
How to disable caching in Voyage for Pharo?
|
Volley has 2 cache layers when it comes to images:
The L1 level: a memory cache provided by you in the ImageLoader constructor.
The L2 level: a disk cache that is shared among every request performed by the same RequestQueue.
The disk cache caches every response unless explicitly requested not to by the request. But, the caching is performed according to the HTTP cache headers of the response.
When you request an image, this is what Volley does:
Check L1 cache for image. Return if found.
Image not in memory - Check L2 cache. If found check expiration of the cache headers. If still valid, add to L1 cache and return image.
Image not on disk (either not there or expired) - Perform a network request. Cache the response in the disk cache and the bitmap in the memory cache and return.
I bet that the image that loaded from the disk has cache headers.
IMO, you have 3 options:
The image server is yours - add the appropriate cache headers.
The image server isn't yours - accept the fact the some images will not be cached on the disk.
Override the caching policy to better suit your needs. This means editing the Volley source code.
|
I have an app that loads images on each item on a list view, and I use Volley to make life easier for me; I need to have to images loaded from disk if it's already been downloaded before.
Problem: It won't work. It needs to re-download the images all over again. I need to have the image saved even after I exit the app.
Weird: It works only on one particular image (and it has nothing to do with size)!
What I Used: I patterned this using this site: https://github.com/rdrobinson3/VolleyImageCacheExample.
I also tried this: http://howrobotswork.wordpress.com/2013/06/02/downloading-a-bitmap-asynchronously-with-volley-example/
The Code:
String godzilla = "http://vineland.pynchonwiki.com/wiki/images/c/cf/Godzilla.jpg";
//String meme = "http://upload.wikimedia.org/wikipedia/en/d/d7/Meme_Many_Journeys.jpg";
ImageCacheManager.getInstance().getImageLoader().get(godzilla, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
viewHolder.backgroundImage = imageContainer.getBitmap();
updateBackgroundImage(viewHolder, viewHolder.backgroundImage, object);
updateLayoutAlignmentParams(viewHolder);
}
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
if(viewHolder.backgroundImage != null)
updateBackgroundImage(viewHolder, viewHolder.backgroundImage, object);
I've tried the meme website, and it still has problems. I had one particular site that contains an image that oddly works. Which makes it even more confusing.
Edit: Additional info, it seems like there's an error on adding lruEntries as lruEntries.remove(entry.key is being called on completeEdit().
|
Android Volley ListView Images Not Loading When Using DiskBasedCache
|
This: surfaceview.getDrawingCache(); will return the bitmap out of the SurfaceView and then you can draw it to the second SurfaceView: canvas.drawBitmap(bitmap, 0, 0, null);.
Another way is to copy the canvas, not the surface view, like this:
Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
This means, that if you'll draw something on the canvas, it will be actually drawn on the bitmap.
|
In my android app there are two SurfaceViews. One SurfaceView is drawn upon when user touches it. I want to copy and replicate the content of this SurfaceView on the other SurfaceView. Probably this can be done by caching the content of the first SurfaceView in a bitmap and then drawing the bitmap on the second SurfaceView. But how to cache the first SurfaceView ?
There are a few similar questions on this forum but they really do not work out for me.
|
How to cache surfaceview in a bitmap?
|
3
Here's one way you could use the GetVaryByCustom function in Global.asax.
public override string GetVaryByCustomString(HttpContext context, string custom)
{
var varyString = string.Empty;
if(context.User.Identity.IsAuthenticated)
{
varyString += context.User.Identity.Name;
}
return varyString;
}
What you could also do is get the user information with an ajax request and insert it using javascript, that way you don't need to recache the page for each user. Personally I would go with this approach if the username is the only thing that differs.
Share
Improve this answer
Follow
answered May 7, 2014 at 14:51
JuhaKangasJuhaKangas
88555 silver badges1717 bronze badges
2
I am not using Membership Provider. I have my own Users table in my database and my own custom logic by which I get user data and store it in Session on login.
– Bhushan Shah
May 8, 2014 at 6:00
Ok, sure, just apply that to this example instead. You can access the session from the HttpContext that is sent to this function.
– JuhaKangas
May 8, 2014 at 8:19
Add a comment
|
|
I have many create Views in my MVC application. I have cached the GET Index action method using [OutputCache] annotation, so that the view is stored in the cache.
I store the details about the currently logged in user in the Session, and display the user's first name in the layout after reading it from the Session.
The problem is, since I have cached the views, the layout is also cached. So even if a different user logs in, the first name of the previous user is visible, because the layout was cached last time.
Is there any way to prevent caching of the layout? Or is there any other way I can stop the first name display from getting cached?
I thought about using VaryByCustom, but I am not sure what to do in the GetVaryByCustomString method that I will need to override.
What would be the best approach to prevent caching of the layout, or alternately, varying the cache by user?
EDIT:
I must clarify that I am using my own custom user management logic. I have my own Users table in the database and I retrieve relevant data on login and store it in Session.
|
Prevent caching of layout file in MVC when caching Index action method
|
Beaware: Ehcache's LOCALRESTARTABLE strategy requires Enterprise license. Well this, would work perfectly, if I had a commercial license of EhCache, which I don't. Had I known that, I wouldn't have gone through the trouble.
Digging further using google and the documentation of Httpclient, the first thing you need to do is to add httpclient-cache-<version>.jar to your classpath.
After that, use the org.apache.http.impl.client.cache.CachingHttpClients instead of the org.apache.http.impl.client.HttpClients
Now you can build the configuration from the documentation.
CloseableHttpClient httpclient = CachingHttpClients.custom()
.setCacheConfig(cacheConfig)
.setHttpCacheStorage(ehcacheHttpCacheStorage)
.build();
Which leaves you trying to figure out how to configure a cacheconfig, which is fairly easy.
//build the cacheconfig. this part belongs to httpclient
CacheConfig cacheConfig = CacheConfig
.custom()
.setMaxCacheEntries(1000)
.setMaxObjectSize(8192)
.build();
The next thing to worry about is the EhCacheHttpCacheStorage, that is fairly problematic, since EhcacheHttpCacheStorage constructor takes an EhCache, but there is no direct way to initialize one. What you need to do is construct a CacheManager, add a cache to it, get it out of the httpclient-cache-<version>.jar0, and finally wrap it into httpclient-cache-<version>.jar1
Step 1: Create the manager:
httpclient-cache-<version>.jar2
Step 2: Create the cache:
httpclient-cache-<version>.jar3
Step 3: add it to the manager:
httpclient-cache-<version>.jar4
Step 4: get the cache out of the manager:
httpclient-cache-<version>.jar5
Step 5: wrap it into EhcacheHttpCacheStorage which implements HttpCacheStorage
httpclient-cache-<version>.jar6
And to make sure you can try this at home, here is everything in the right order, with the necessary imports
httpclient-cache-<version>.jar7
|
Today I wanted to integrate a persistent cache into apache's httpclient library. A quick look into the documentation for Http-Caching tells you:
The current release includes support for storing cache entries using EhCache and memcached implementations, which allow for spilling cache entries to disk or storing them in an external process.
Fair enough, a quick google-search later I had exactly no idea what to do and how to do that ;)
But there was one more hint:
If none of those options are suitable for your application, it is possible to provide your own storage backend by implementing the HttpCacheStorage interface and then supplying that to caching HttpClient at construction time.
So at least we know that the HttpCacheStorage needs to be initialized using some class that implements HttpCacheStorage.
The question in a one liner:
How do you integrate caching into any http-request?
How do you initialiase an EhCache?
How do your integrate an EhCache into the http-caching thingy.
|
Integrating persistent caching into Apache Httpclient with EhCache
|
using: (2^index bits) * (valid bits + tag bits + (data bits * 2^offset bits))
for the first one i get:
total bits = 2^15 (1+14+(32*2^1)) = 2588672 bits
for the cache with 16 word blocks i get:
total bits = 2^13(1 +13+(32*2^4)) = 4308992
the next smallest cache with 16 word blocks and a 32 bit address works out to be 2158592 bits, smaller than the first cache.
|
Preface: There are many different design patterns that are important to cache's overall performance. Below are listed parameters for
different direct-mapped cache designs.
Cache data size: 32 kib
Cache block Size: 2 words
Cache access time: 1-cycle
Question: Calculate the number of bits required for the cache listed above, assuming a 32-bit address. Given that total size, find the
total size of the closest direct-mapped cache with 16-word blocks of
equal size or greater. Explain why the second cache, despite its
larger data size, might provide slower performance that the first
cache.
Here's the formula:
Number of bits in a cache 2^n X (block size + tag size + valid field size)
Here's what I got: 65536(1+14X(32X2)..
is this correct?
|
Calculating number of bits in a cache
|
The main reason to have your cache on your app server is the issue of cost. This is the same idea of not having your DB on the same server as your web or app server.
If you have a small scale application you can probably squeeze all your resources on the same machine, but then your ability to recover from any type of failure (and "everything fails"), you will either lose data or it will take part of your service down for some of your users.
Once you have enough app servers your costs for the cache cluster is smaller per server.
From architecture point of view, when scale and high availability are important, you should have more smaller components than few more complex ones.
For example, if you want to add another app server to your fleet as you have more users, it will be faster to add a server, as you have less software components to install on this server, and the server can already serve previous users as their sessions are stored centrally. If you want to remove an app server (or when you lose one), the users that were served by that server can easily migrate to the other servers as their session/status is stored in the cache cluster.
|
TL;DR - should a simple cache cluster for session storage (using memcache or redis) live on the app's servers (i.e. along with nginx and php) or on its own separate ec2 instance (like elasticache or a customized ec2 instance)?
I'm in the process of using Amazon OpsWorks to set up my web app's infrastructure. I am leaning toward implementing the session cache through memcache instances installed on the app layer itself rather than as its own ec2 instance. For instance:
[ Load Balancer ]
/ | \
[ App Layer 1 ] – [ App Layer 2 ] – [ App Layer 3 ] * /w memcache or redis
vs.
[ Load Balancer ]
/ | \
[ App Layer 1 ] [ App Layer 2 ] [ App Layer 3 ]
\ | /
[ Cache Server(s) ] * ElastiCache or custom ec2 /w memcache or redis
What are the pros and cons here? To me the later solution seems unnecessary, though I can see how a high-traffic website with a really large session cache might need this.
Is there a reason I may not want to run redis or elasticache alongside my nginx/php app server stack? Does it make auto-scaling or monitoring performance more difficult to do perhaps?
|
Where should my caching daemon live?
|
You should specify a CachePolicy:
enum
{
NSURLRequestUseProtocolCachePolicy = 0,
NSURLRequestReloadIgnoringLocalCacheData = 1,
NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented
NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,
NSURLRequestReturnCacheDataElseLoad = 2,
NSURLRequestReturnCacheDataDontLoad = 3,
NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
};
typedef NSUInteger NSURLRequestCachePolicy;
Try this:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:myURLString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:nil]];
|
Developing the Native App for ipad,
Initial screen i have on 'ViewDidLoad' a webcall made to read a file on web getting me the results and showing the list.
Prob 1: when i change the content of file in Web it doesnt reflect in my app, even i kill app still result is old same. can anyone help me with this issue.
After this list select it lands to WebView.
Prob 2: When i change anything on server side javascript. it doesnt reflect on the Native App, it does still give me old response only. (i.e Javascript and Css changes are not reflect in App). Can anyone please help me throught this part.
IOS 7 native App in Ipad. If you need code i can post it.
|
Ios Application Caching the Webview & native calls
|
3
Java has a ReadWriteLock which supports reads concurrently and writes exclusively. As mentioned in the JavaDoc, it is a good choice if updates occur not very frequently and reads occur often. The faster your writer updates the List the better the performance you get.
The methods readLock() has to be called by readers and writeLock() by writers. Then you have to call lock() on the Lock obtained. If it is available, the tread will continue working, otherwise it will block, until the lock is available.
Use fairness when constructing the ReadWriteLock to enable reader and writer threads to obtain their locks in the order they requested it. Otherwise some thread could wait forever (in a worst case scenario).
The benefit of a ReadWriteLock is that many reader may share the same lock without obtaining it, which is an expansive operation. This benefit is only observable if the ratio between reading and writing is heavily in favor of reading.
Share
Improve this answer
Follow
edited Mar 21, 2014 at 13:58
answered Mar 21, 2014 at 13:45
HarmlezzHarmlezz
8,0282727 silver badges3636 bronze badges
2
Will it be faster than just changin volatile reference to new list object?
– Kinga Odecka
Mar 21, 2014 at 18:05
The Java volatile keyword only ensures that many threads reading the same shared data will have to update any locally cached values of that data. It does not provide any synchronization mechanism as far as I am aware of. Maybe you are interested in reading this example about the volatile keyword, which I think is a very good one.
– Harmlezz
Mar 24, 2014 at 8:02
Add a comment
|
|
Suppose that I have a List with role of cache. Most time list is read-only buy every few seconds I want to do atomic replacement of all List contents.
In atomic I mean that I don't want to allow cache clients to hit read between for example clear() and addAll().
What list implementation to use and how to perform replacement for best performance?
It is better to replace list contents or to replace reference value itself?
|
What is the best way to atomic-replace all contents in List in Java?
|
3
I have sorted this.
In the vcl_hash subroutine I needed to add the country code into the hashed data.
sub vcl_hash {
hash_data(req.url);
if (req.http.host) {
hash_data(req.http.host);
} else {
hash_data(server.ip);
}
hash_data(req.http.X-Country-Code);
return (hash);
}
The default vcl I am using had the whole vcl_hash subroutine commented out because it was using req.hash instead of hash_data() which is no longer available in Varnish 3 so adjust as necessary.
Share
Improve this answer
Follow
answered Mar 14, 2014 at 14:07
Richard CleverleyRichard Cleverley
11611 silver badge55 bronze badges
Add a comment
|
|
I am using Varnish to serve a website but need to have the caching dependent on Geo location. I have written a small Vmod that uses Ip2Location to set a request header that has the country code in which is then passed to my application (Magento) via Apache which serves up the relevant content but I need Varnish to also cache depending on the country code.
Is there any way to achieve this?
|
Varnish cache according to custom header
|
2
For selecting a good cache, with good in-memory read performance, take a look at the benchmarks at the cache2k benchmark page. It compares EHCache, guava cache, cache2k, and Infinispan.
If you don't need eviction, why you need a cache then? Anyway, within cache2k it is possible to switch to eviction implementations that have very low overhead, like this:
Cache<String, String> c =
CacheBuilder.newCache(String.class, String.class)
.source(new CacheSource<String, String>() {
@Override
public String get(String o) {
... fill code ...
}
})
.implementation(ClockCache.class)
.build();
Another low overhead eviction is org.cache2k.impl.RandomCache, which just selects an eviction candidate by a round robin pointer that walks through the hashtable. The different algorithms are not exposed within the API module, so you need to have cache2k-core.jar within your compile scope.
Disclaimer: I work on cache2k...
Share
Improve this answer
Follow
edited Nov 1, 2014 at 7:21
answered Mar 1, 2014 at 15:15
cruftexcruftex
5,61522 gold badges2020 silver badges3636 bronze badges
Add a comment
|
|
I want to implement a Cache in Java that is supposed to cache tags for a given id. (0-N tags for one id)
There are around 1000 unique tags in 100 million entities, but the actual number can vary by a few thousand.
It does not not need to consider id/tag eviction.
It is expected for the cache to throw a OutOfMemoryError if more tags exist than we can cache in memory.
However, the design should ensure that it takes as little memory as possible to cache the tags.
The cache has one method
'getTags()' method that takes an id and returns the tags for the entity.
This method on worst case ( barring garbage collection) take a few
100 nano seconds. It can be called 1000's of time in a few milliseconds.
The cache should be designed for multi threaded access with 1000's
of requests to getTags in a few ms.
Please suggest a good data structure/Collection to use which can offer me such a performance.
|
Implementing a Cache in Java for read performance with no eviction at all
|
ctx.Cache.Insert("stmodel", stModel, null,
MyClass.getSpecificDateTime(), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, OnCachedItemRemoved);
public static DateTime getSpecificDateTime()
{
TimeSpan currentTime = DateTime.Now.TimeOfDay;
DateTime newTime = DateTime.Now;
if (currentTime.Hours < 7){
newTime = newTime.Date + new TimeSpan(7, 0, 0);
}else if (currentTime.Hours < 11){
newTime = newTime.Date + new TimeSpan(11, 0, 0);
}else if (currentTime.Hours < 15) {
newTime = newTime.Date + new TimeSpan(15, 0, 0);
}else if (currentTime.Hours < 19){
newTime = newTime.Date + new TimeSpan(19, 0, 0);
}else {
newTime = DateTime.Now.AddDays(1);
newTime = newTime.Date + new TimeSpan(7, 0, 0);
}
return newTime;
}
|
I am using cache.insert() method to add some data to cache, and it uses absolute expiration and expires once in 4 hours.
Now I have a new requirement to expire the cache in specific times: 7am, 11am, 3pm, 7pm.
Is there a way to do it?
Current code:
ctx.Cache.Insert("stmodel", stModel, null,
DateTime.Now.AddHours(4), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, OnCachedItemRemoved);
Thanks in advance.
|
expire cache at specific time
|
2
If your app uses android:largeheap="true",
Never use Runtime.getRuntime().maxMemory() as you will most likely use more memory than availabe and OOM more often, instead use the memory class and calculate the size of the cache as follows:
/** Default proportion of available heap to use for the cache */
final int DEFAULT_CACHE_SIZE_PROPORTION = 8;
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int memoryClass = manager.getMemoryClass();
int memoryClassInKilobytes = memoryClass * 1024;
int cacheSize = memoryClassInKilobytes / DEFAULT_CACHE_SIZE_PROPORTION;
bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)
Share
Improve this answer
Follow
edited Apr 20, 2014 at 17:03
answered Feb 20, 2014 at 16:09
peteypetey
17k66 gold badges6767 silver badges9999 bronze badges
4
1
i have used the same but it is giving the same out of memory error is it because images are not recycled or what?? Lru is not performing these recycling things by default???
– Ravi
Feb 21, 2014 at 6:46
What is the value of DEFAULT_CACHE_SIZE_PROPORTION as I am unable to find any references to it.
– Theo
Feb 26, 2014 at 11:50
what if your app doesn't use largeHeap="true"?
– Adam Johns
May 14, 2014 at 14:16
check the bitmap being loaded and the stacktrace, it will usually tell you the memory limit and the attempt to allow the required memory needed at bOOM time.
– petey
May 14, 2014 at 15:26
Add a comment
|
|
I have used Memory LRU Caching for caching bitmaps in my android application.but after some of the bitmaps are loaded into LRU map app force closes saying out of memory exception. I have spent whole day behind this but yet not found the solution please anyone can help me out I am badly stuck in this problem.Thanks in advance.
HERE IS MY CODE
final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory / 8;
bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)
{
@SuppressLint("NewApi")
@Override
protected int sizeOf(String key, Bitmap value)
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2)
{
return value.getByteCount()/1024;
}
else
{
return (value.getRowBytes() * value.getHeight())/1024;
}
}
};
|
How to prevent Out of memory error in LRU Caching android
|
3
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT"); // *
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
If the 0 in the header expires isn't working on expires due to old browsers not understanding it, you can try putting the date to a time in the past.
Share
Improve this answer
Follow
edited Aug 24, 2019 at 9:35
answered Feb 16, 2014 at 13:22
Simone NigroSimone Nigro
4,79522 gold badges4040 silver badges7777 bronze badges
Add a comment
|
|
This question already has answers here:
Disable browser cache in PHP or JavaScript in a Flash application
(2 answers)
Closed 10 years ago.
I am using this code to disable cache in php but this code is not working on any browser. Please somebody help me, I don't want to save php web page in cache memory
header('cache-control: no-cache,no-store,must-revalidate');
header('pragma: no-cache');
header('expires: 0');
|
How to disable cache in php [duplicate]
|
3
Backbone.Relational.store.reset()
Share
Improve this answer
Follow
answered Feb 14, 2014 at 11:41
jaxjax
38.2k5858 gold badges184184 silver badges282282 bronze badges
Add a comment
|
|
How I can clear the cache of relational Backbone?
relational backbone remembers the previous values after fetch
|
How I can clear the cache of Backbone relational?
|
Yes, with Amazon S3 you can still set the Expires header of the objects stored in the bucket.
You will have to set this header when storing the object so there are two ways:
programatically using the API (set the Expiry header with your PUT request)
in the bucket browser that you use to upload the objects
If you use the API you can do something like
PUT /ObjectName HTTP/1.1
Host: BucketName.s3.amazonaws.com
Date: date
Authorization: authorization-string
Expires: expiry-date
http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
For the second case maybe this link will help: http://www.newvem.com/how-to-add-caching-headers-to-your-objects-using-amazon-s3/
Hope this helps.
|
I've been able to correctly (I think) enable caching on IIS. The only problem now is that when I run Google's PageSpeed Insights it still says
Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.
But all of the suggestions are external images. I am using Amazon's S3 to externally host images (linking to direct URLs, as
< img src="http://s3.amazon.com......."/>.
Is there a way I can "leverage browser caching" for these external images?
Thanks in advance.
Andy
|
Leverage browser caching - external images
|
3
The answer was also posted on the wro4j mailing list:
You could achieve this with a custom RequestHandler. The handler would accept request having disableCache request param set to true and the implementation would invalidate the cache for the requested group: cacheStrategy.put(cacheKey, null);
But before using the above approach, I would suggest a simpler one:
resourceWatcherUpdatePeriod=5
resourceWatcherAsync=true
The above two configuration properties should ensure that you get the most recent result after 5 seconds. The wro4j would check for you if there are any changed resources and will process them asynchronously without affecting your development cycle.
UPDATE
An example implementing the custom request handler which invalidates the requested group when the disableCache parameter is provided is available here.
Share
Improve this answer
Follow
edited Feb 14, 2014 at 22:18
answered Feb 11, 2014 at 8:36
Alex ObjeleanAlex Objelean
4,02322 gold badges2727 silver badges3636 bronze badges
3
Replied on wro4j mailing list too. I am looking for something like calling /wro/main.css?disableCache=false should give me result from cache and /wro/main.css?disableCache=true should give me result by freshly generated wro4j life cycle. Moreover I already have resourceWatcherUpdatePeriod configured. It would be really great if you can give me more inside of requestHander.Any example would be really helpful.
– sun2
Feb 11, 2014 at 15:57
The wro.properties way worked for me. This answer deserves more upvotes
– Andrea Ligios
Nov 16, 2016 at 8:28
Ah, you are the wro4j dev :) Good job then
– Andrea Ligios
Nov 16, 2016 at 8:30
Add a comment
|
|
I would like to configure Wro4j in such a way that it should dynamically enable/disable cache based on the properties file (not wro.properties)
is implementing a custom RequestHandeler good ideal?
Please let me know if there is any possible way to do it.
Moreover, It would be really great if i can do that based on request parameter:
eg: calling the URL /wro/main.css?disableCache=true should give me the main.css generated by Wro4j (with compete wro4j life cycle) and not from the cache.
Note: I am using spring MVC.
|
Wro4j enable/disable cache dyanamically
|
After disabling a RSS widget in administration, site is being cached correctly.
|
I installed wordpress 3.8.1 on GAE - transfered from a WP-MU installation on another host. I installed GAE plugin which is working but mentions I should also install batcache and memcached plugins. So I installed them both but they don't seem to be working- I get no debug output in <head> section, response is 200 and site is generally slow. What can I do to enable caching? Here are the response headers after 2 reloads with curl -i:
HTTP/1.1 200 OK
Vary: Cookie
X-Pingback: http://www.websiteinquestion.com/xmlrpc.php
Content-type: text/html; charset=UTF-8
Vary: Accept-Encoding
Date: Sun, 09 Feb 2014 23:20:32 GMT
Server: Google Frontend
Cache-Control: private
Alternate-Protocol: 80:quic,80:quic
Transfer-Encoding: chunked
There is some debug output when enabled:
Notice: Undefined offset: 1 in /base/data/home/apps/s~xxx/xxx.stringofnumbers/wordpress/wp-content/object-cache.php on line 374
Here is the app.yaml
application: xxxxx
version: xxx
runtime: php
threadsafe: no
default_expiration: "2d"
api_version: 1
instance_class: F1
automatic_scaling:
min_idle_instances: 0
max_idle_instances: 1
min_pending_latency: automatic
max_pending_latency: 15000ms
in wp-config.php I added
define('WP_CACHE', true);
I tried viewing the memcache stats on GAE console but I can't find the viewer anywhere. In settings memcache is set to shared mode.
|
Why is my wordpress site on GAE not being cached?
|
I've created something like this for my own personal use: a CACHE class. (I haven't documented the code yet though.) It appears to be more flexible than Python's lru_cache (I wasn't aware of that, thanks) in that it has several methods for adjusting exactly what gets cached (to save memory) and how the comparisons are made. It could still use some refinement (@Daniel's suggestion to use the containers.Map class is a good one – though it would limit compatibility with old Matlab versions). The code is on GitHub so you're welcome to fork and improve it.
Here is a basic example of how it can be used:
function Output1 = CacheDemo(Input1,Input2)
persistent DEMO_CACHE
if isempty(DEMO_CACHE)
% Initialize cache object on first run
CACHE_SIZE = 10; % Number of input/output patterns to cache
DEMO_CACHE = CACHE(CACHE_SIZE,Input1,Input2);
CACHE_IDX = 1;
else
% Check if input pattern corresponds something stored in cache
% If not, return next available CACHE_IDX
CACHE_IDX = DEMO_CACHE.IN([],Input1,Input2);
if ~isempty(CACHE_IDX) && DEMO_CACHE.OUT(CACHE_IDX) > 0
[~,Output1] = DEMO_CACHE.OUT(CACHE_IDX);
return;
end
end
% Perform computation
Output1 = rand(Input1,Input2);
% Save output to cache CACHE_IDX
DEMO_CACHE.OUT(CACHE_IDX,Output1);
I created this class to cache the results from time-consuming stochastic simulations and have since used it to good effect in a few other places. If there is interest, I might be willing to spend some time documenting the code sooner as opposed to later. It would be nice if there was a way to limit memory use as well (a big consideration in my own applications), but getting the size of arbitrary Matlab datatypes is not trivial. I like your idea of caching to a file, which might be a good idea for larger data. Also, it might be nice to create a "lite" version that does what Python's lru_cache does.
|
In Python we have lru_cache as a function wrapper. Add it to your function and the function will only be evaluated once per different input argument.
Example (from Python docs):
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
I wonder whether a similar thing exists in Matlab? At the moment I am using cache files, like so:
function result = fib(n):
% FIB example like the Python example. Don't implement it like that!
cachefile = ['fib_', n, '.mat'];
try
load(cachefile);
catch e
if n < 2
result = n;
else
result = fib(n-1) + fib(n-2);
end
save(cachefile, 'result');
end
end
The problem I have with doing it this way, is that if I change my function, I need to delete the cachefile.
Is there a way to do this with Matlab realising when I changed the function and the cache has become invalidated?
|
Does a function cache exist in Matlab?
|
I have done the same kinda think when i need to show the image in tableView, first i check that image is available locally or not then I download the image and save it like this
if (userBasicInfo.userImage == nil) {
__weak LGMessageBoxCell *weakCell = cell;
[cell.userImage setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:userBasicInfo.imageUrl]]
placeholderImage:[UIImage imageNamed:@"facebook-no-user.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
weakCell.userImage.image = image;
[weakCell setNeedsLayout];
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
UserBasicInfo* userBasicInfo = [[UserBasicInfo findByAttribute:@"userId" withValue:@(chatUser) inContext:localContext] objectAtIndex:0];
userBasicInfo.userImage = UIImagePNGRepresentation(image);
} completion:^(BOOL success, NSError *error) {
NSLog(@"%@",[error localizedDescription]);
}];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
} else {
cell.userImage.image = [UIImage imageWithData:userBasicInfo.userImage];
}
|
I need to set images to my imageViews. And there are a lot of images (I think it will be near 200mb). I need save it all, for using app locally without internet connection. It's very easy to use category UIImageView+AFNetworking, but I don't understand how it save and where?
So in subscribing of methods here
, you can see that it use a cache policy of NSURLCacheStorageAllowed. So images saved in cache folder on disk, right? That's all ok, but what limit of this storage? Do I need to implement next code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//another code...
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:200 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
return YES;
}
So NSURLCacheStorageAllowed is returned like storagePolicy from NSCachedURLResponse. So I understand that I mustn't to implement code that I wrote above.
Do all my images will be saved in cache storage locally, if I will using UIImageView+AFNetworking category?
|
UIImageView+AFNetworking and saving images
|
Are you using MAMP?
This happened to me, and had to do with a newer version of MAMP.
In your MAMP Dir go to : /bin/php/php5.5.3/conf/php.ini
And comment the Opcahe lines:
[OPcache]
;zend_extension="/Applications/MAMP/bin/php/php5.5.3/lib/php/extensions/no-debug-non-zts-20121212/opcache.so"
; opcache.memory_consumption=128
; opcache.interned_strings_buffer=8
; opcache.max_accelerated_files=4000
; opcache.revalidate_freq=60
; opcache.fast_shutdown=1
; opcache.enable_cli=1
Original answer by @coding-addicted here
|
I've been working on a set of web development projects over the last few months, and have encountered the following problem: no matter what I do, every browser I have caches every page I load, which makes it impossible to know if an edit hasn't worked or if I'm viewing a cached version. I've tried Google Chrome, in Incognito Mode and with the Developer Tools open. I've tried Mozilla Firefox, gone into about:config and disabled every single kind of caching I could find. I've tried Safari Private Mode. I've cleared my cache several times on each browser. I've tried adding headers that should prevent caching. I've tried appending a random number to the URL so the URL changes every time I open the page; I am still getting cached versions of the page somehow. Does anyone have any tips, in any of these browsers, to make the constant caching of pages stop? I'm running Mac OS X Mavericks, if that helps.
|
Stop caching my pages during local development
|
Yes you can do it with memcached but you have to setup your environment first.
1) Install memcached
sudo apt-get install memcached (ubuntu)
brew install memcached (mac os x)
2) Add dalli to => Gemfile
gem 'dalli'
3) Change environments/development.rb
config.action_controller.perform_caching = true
4) Finally your_controller.rb
@tweets = Rails.cache.fetch("your_unique_cache_key_name") do
TweetyClass.new.user_timeline
end
You can learn more from this tutorial.
|
I'm using the Twitter Gem.
My Model:
class TweetyClass
def initialize
@client = Twitter::REST::Client.new do |config|
config.consumer_key = TWITTER_CONFIG['consumer_key']
config.consumer_secret = TWITTER_CONFIG['consumer_secret']
config.access_token = TWITTER_CONFIG['access_token']
config.access_token_secret = TWITTER_CONFIG['access_token_secret']
end
end
def user_timeline
@client.user_timeline( count: 2)
end
end
My Controller:
def tweets
@tweets = TweetyClass.new.user_timeline
end
My View:
<% @tweets.each do |tweet| %>
<li><%= tweet.foo%></li>
<% end %>
Is there a way to cache the results so each time I call user_timeline it fetches the result from the app/app variable rather than going to Twitter and fetching the timeline of Tweets.
Apologies if I'm not using the correct terminology; I'm new to the subject of caching. Essentially what I want to do is improve the speed of my app and one thing that seems to slow it down is the time it takes to retrieve tweets using the user_timeline method. I'm assuming it's because it's retrieving this from Twitter each time and I thought caching may assist.
|
Can I cache a result using the Twitter gem? (Rails 4)
|
There is a new caching library so called imcache. This library supports CacheManager of the spring by imcache-spring project. An example use of this library can be found at this blog.
|
I am looking for caching solution that implements the org.springframework.cache.CacheManager other than ehcache. If there exist such solution, how to use it?
|
Spring Cache Abstraction with Custom Cache Manager
|
You can try adding this to your code -
$.ajaxSetup({ cache: true });
This will ensure that no cache-busting strategy is used by jQuery.
|
In my application I'm using the overlay effect of jquerytools.
I'm opening an external page inside the overlay as explained in this demo.
In my external page I'm using some javascripts to do validation and so on. My application is using the Struts2 framework.
The problem I have is concerning the performances of the overlay effect. In the web server (apache) I'm using the mod_expires to let the browser cache the resources.
The problem is that while the file jquery-1.7.2.min.js gets cached in all the application when opening the overlay it won't be cached because it's name changes with an dynamically generated numerical string.
For example the file name changes in this way:
Main application: jquery-1.7.2.min.js
Inside the overlay: jquery-1.7.2.min.js?_=1386932790620
This numerical string changes everytime, preventing the browser (Chrome) to cache the resource. So every time a user opens the overlay the jquery-1.7.2.min.js gets downloaded slowing down the performances.
You can see this problem in the attached pictures:
Caching:
Non caching:
I guess that the overlay effect of jquerytools is using AJAX to load an external page, so the question is:
is there a way to remove that numeric string from being attached to the resource name?
There'are other solutions to prevent the overlay effect to download everytime the javascript resource?
|
Caching of JS resources with AJAX call in JQuery tools
|
Well the solution is pretty simple :
Just use SQL_NO_CACHE in your select statement to exlude some query from mysql query cache,
so thoses query will not loose time processing for test if this query is cachable or not !
SELECT SQL_NO_CACHE whatyouwant
Hope it helps
|
In my site i have 20 simple querys cachable and 5 pretty big query no cachable on each page . So just activate mysql query cache isnot a good idea here, sure my 20 simple querys will cached but I loose 10% time processing for my 5 big querys for nothing.I'd like to say " hey mysql, don't try to test thoses 5 querys "
I Would like to use query cache just for some querys and exclude others..
So, is it possible to choose who's query will cahable with mysql,
or if not, do you know some other solution for that or an advise for my situation ?
thanks for ur lights
regards
Jess
|
Possible to exclude some query from Mysql query cache?
|
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", -1);
instead of using this from jquery try to pass the header on the requested page itself.
and try to use unique image name on the requested page. usually browser show previously rendered images from cache.
|
in which i have to create a simple image editor to perform operations like flip, flop, adding border etc. Am using jsp servlets. Whenever an operation is performed a POST ajax request is sent to the server with data - image server relative path and the name of the operation. Am using ImageMagick to perform the operations - for quality issues . Once the changes are done (till then using ajaxloader) response is sent back to the view. Everything works fine until the user clicks on the operation as soon as one operation completes. The old image -with previous image editing operation is displayed again and after sometime the changes are reflected. I googled it and came to the conclusion that it is due to caching. I tried all possible things -
appended the path of server relative path of the image with a time stamp
http://172.16.3.72:8080/~user/dataDir/workspace/2/tempData/ResizeImage.jpeg?random=1381852940376
appended the url of the ajax with a time stamp
http://172.16.3.72:8080/cdl/captureImage.htm?pageNumber=2&isbn=AndItWorksFinally2?random=.332223223
used cache: false in jquery
Used header to disable cache
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", -1);
but all these things didn't help. Is there something else and not the cache issue?
was wondering how facebook loads the images from the server so fast(no duplicates), when we click on the next button while viewing pictures.
|
Changes In Image Data Not Reflected In ModelView
|
Frontend configuration file:
'cache' => array(
'class' => 'system.caching.' . (!MW_DEBUG ? 'CFileCache' : 'CDummyCache'),
'keyPrefix' => md5('frontend.' . MW_VERSION . Yii::getPathOfAlias('frontend')),
),
Console configuration file:
'cache' => array(
'class' => 'system.caching.' . (!MW_DEBUG ? 'CFileCache' : 'CDummyCache'),
'keyPrefix' => md5('console.' . MW_VERSION . Yii::getPathOfAlias('backend')),
),
reference answer
|
I am creating caching for my app using console app.
But i unable share that cache for my web app.
(in my redis database its showing created from console)
any idea how can i share cache created from console to my web app?
|
Yii caching share caching between console app and web app?
|
Yes. This makes sense, especially for apps with lots of images, because you wouldn't want to be fetching those resources from memory every time a user loaded a view. This is true for dynamically-loaded content as well, which is why apps like Flipboard hog a ton of memory :P
If you're worried about it, just make sure to be more aggressive with releasing resources that are rarely used, for example view-specific images. Other things like background images, which may be on every view, should be kept around in cache.
|
I am just trying to figure out some memory confusion with my App. Do iphone apps have a cache that store images and such? My memory jumps up when I switch screens, but doesn't go back down when I switch back to the previous screen.
|
Do Iphone Apps have a Cache?
|
2
According to this (which is naturally Intel specific)
"The cache line size is 32 bytes, or 256 bits.
A cache line is filled by a burst of four reads on the processor’s 64-bit data bus."
This means 8 bytes are fetched in parallel from main memory, within these 8 bytes there's no first or last, they arrive simultaneously, as the bytes are fetched over a 64 bit wide bus.
As it takes 4 reads to fill a cache line, Intel seems to not specify the order of these 4 reads - which mean you're left with some choices, e.g.
assume that there is no specific order
assume the address are fetched from lowest to highest, or vice versa.
The first assumption is of course the safest - since the order is as far as I can find undocumented(so it could depend on the model, or other factors)
Share
Improve this answer
Follow
answered Sep 11, 2013 at 11:54
nosnos
226k5858 gold badges423423 silver badges511511 bronze badges
1
Intel has used 64-byte cache lines since Pentium 4 or so, or at least since Core 2 for P6 family, not sure about Pentium M. I'm not sure if they do "critical word first" or not; the data paths between memory controllers and cores are 32 bytes wide in Sandybridge family so they might start a DDR burst in the low or high half of the full line, but probably not at some other 8-byte chunk. Historically, simpler CPUs have done critical-word-first to enable early-restart of a stall after a cache miss.
– Peter Cordes
Jan 19 at 21:01
Add a comment
|
|
When a processor pre-fetches a cache-line of data, does it pre-fetch from that address up to the number of bytes or does it pre-fetch from that address up to half the cache line and back wards up to half the cache line?
For example assume cache line is 4 bytes and pre-fetching from address 0x06. Will it fetch bytes at 0x06 0x07 0x08 0x09 or will it pre-fetch from addresses 0x04 0x05 0x06 0x07.
I need this info for a program which I am writing and need to optimize.
|
How does a processor fetch cache lines?
|
The other option you have is using In-Role Cache for Web/Worker roles (Azure Cloud Services). Any role within the same cloud deployment can access the cache. If you have just 1 web role - this acts very similar to ASP.NET State Server which provides an in-memory cache. However, as you add more web roles - you can choose to distribute this in-memory cache across all roles or use a dedicate worker role for managing the cache.
Dedicated In-Role Cache: worker role uses all available memory
Co-Located In-Role Cache: percentage of available memory is used across all roles
See In-Role Cache FAQ on MSDN for more details.
|
I'm currently building a site that will be hosted in Microsoft Azure. The last site I created in this hosting environment used "Windows Azure Shared Caching". Some of you may already be aware that "Windows Azure Shared Caching" service will soon be deprecated over the next year.
I have applied for the preview release of "Windows Azure Cache". However, I'm finding that my request is still "queued".
I wouldn't mind using "Windows Azure Shared Caching" since the site I'm building will only be live for around 10 weeks and the fact it being deprecated next year doesn't worry me. However, I am unable to create a new caching service through the old Azure Management Portal since new caching has to be done using "Windows Azure Cache".
So my question...
Since my application for the new caching platform is still yet to be approved and I am unable to create a new caching service under the old platform, what other options are there? Have I missed something?
Microsoft is surely making things difficult.
|
Azure Caching Platform Options - What Are The Alternatives?
|
3
Didn't end up finding any good solutions, so ended up using this:
# This helper is useful for caching a response from an API, where the API is unreliable
# It will try to refresh the value every :expires_in seconds, but if the block throws an exception it will use the old value for up to :fail_in seconds before actually raising the exception
def cache_with_failover key, options=nil
key_fail = "#{key}_fail"
options ||= {}
options[:expires_in] ||= 15.seconds
options[:fail_in] ||= 5.minutes
val = Rails.cache.read key
return val if val
begin
val = yield
Rails.cache.write key, val, expires_in: options[:expires_in]
Rails.cache.write key_fail, val, expires_in: options[:fail_in]
return val
rescue Exception => e
val = Rails.cache.read key_fail
return val if val
raise e
end
end
# Demo
fail = 10.seconds.from_now
a = cache_with_failover('test', expires_in: 5.seconds, fail_in: 10.seconds) do
if Time.now < fail
Time.now
else
p 'failed'
raise 'a'
end
end
An even better solution would probably exponentially back off retries after the first failure. As it's currently written, it will pummel the api with retries (in the yield) after the first failure.
Share
Improve this answer
Follow
answered Sep 4, 2013 at 21:04
Brian ArmstrongBrian Armstrong
19.8k1717 gold badges116116 silver badges144144 bronze badges
Add a comment
|
|
We use this to get a value from an external API:
def get_value
Rails.cache.fetch "some_key", expires_in: 15.second do
# hit some external API
end
end
But sometimes the external API goes down and when we try to hit it, it raises exceptions.
To fix this we'd like to:
try updating it every 15 seconds
but if it goes offline, use the old value for up to 5 minutes, retrying every 15 seconds or so
if it's stale for more than 5 minutes, only then start raising exceptions
Is there a convenient wrapper/library for this or what would be a good solution? We could code up something custom, but it seems like a common enough use case there should be something battle tested out there. Thanks!
|
Rails cache fetch with failover
|
As mentioned in your comments the delegate passed to the ToOptimizedResultUsingCache method is only executed if the item doesn't exist in the cache. I would just add a "cached at" property to the response DTO and set it in that delegate.
public class OrdersService : Service
{
public object Get(CachedOrders request)
{
var cacheKey = "unique_key_for_this_request";
var returnDto = base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,() => {
return new MyReturnDto {
CachedAt = DateTime.Now
};
});
}
}
You can then use the CachedAt property to see when the item was cached.
If you don't want to modify your DTO you can just use a variable outside of the scope of delegate called when caching the result.
public class OrdersService : Service
{
public object Get(CachedOrders request)
{
var cacheKey = "unique_key_for_this_request";
var isCached = false;
var returnDto = base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,() => {
isCached = true;
});
// Do something if it was cached...
}
}
|
I have the caching hooked up in my request, but I'd like to be able to tell if the return I'm getting back is actually coming from the cache or not. Is there a way to see this? I have access to the code-base to make modifications.
ServiceStack's standard caching pattern:
public class OrdersService : Service
{
public object Get(CachedOrders request)
{
var cacheKey = "unique_key_for_this_request";
return base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,()=>
{
//Delegate is executed if item doesn't exist in cache
//Any response DTO returned here will be cached automatically
});
}
}
|
ServiceStack: How to tell if a return from a request was cached?
|
As Mongoose objects wrap a MongoDB document, there'd be no reason that you couldn't call
JSON.stringify(mongooseObject.toJSON())
which would return a string representing the MongoDB document. (toJSON) You could then store that result in a key/value in redis.
Where it starts to get more complex is that you'd need to first override the normal save and update functionality to save any modifications to your redis store rather than to the database. While doable, Mongoose wasn't designed for that and you'd be probably more successful to just use the native mongodb drivers and manage general document interactions that way. There are a number of extremely handy operators that you'd need to independently handle (like $push for example, which would add a single value to an array).
The real issue though is that you loose nearly all of the power of MongoDB by not being able to use the query engine or aggregation framework if all of the data isn't already stored in MongoDB (and even if it is, you're still bypassing your caching layer). And, if you're not using any of that functionality, then MongoDB may not be the best match for your needs (and you might instead consider something like CouchDB).
While I can see the potential value of using a caching layer for a high performance MongoDB system, the complexity of a write-back style cache may be more complex than it's worth (and not necessarily safe).
Of course, a write-through cache would be simpler (although you have the complexity of two data-stores and making sure writes are committed consistently if you're going to trust the cache and DB).
(As an aside, I'm not sure how you'd actually manage timeouts, as I thought redis deleted the values associated with keys if they were assigned a lifetime/timeout? I wouldn't want to loose data to the redis cache if you were doing write-back).
|
Is it possible to cache, say, mongoose document obejcts in Redis,
perhaps for implementing a write-back or write-through cache with timeout-based cache flush mechanisms?
P.S.:
I am familiar with mongoose-redis-cache, but I guess it supports only lean queries, which do not quite serve the purpose here. (But I may be wrong).
|
Caching mongoose objects with Redis
|
If you ultimately decide to move the cache outside your main webserver process, then you could also take a look at consistent hashing. This would be a alternative to a replicated cache.
The problem with replicated caches, is they scale inversely proportional to the number of nodes participating in the cache. i.e. their performance degrades as you add additional nodes. They work fine when there is a small number of nodes. If data is to be replicated between N nodes (or you need to send eviction messages to N nodes), then every write requires 1 write to the cache on the originating node, and N-1 writes to the other nodes.
In consistent hashing, you instead define a hashing function, which takes the key of the data you want to store or retrieve as input, and it returns the id of the server in the cluster which is responsible for caching the data for that key. So each caching server is responsible for a fraction of the overall keys, the client can determine which server will contain the sought data without any lookup, and data and eviction messages do not need to be replicated between caching servers.
The "consistent" part of consistent hashing, refers to how your hashing function handles new servers being added to or removed from the cluster: some re-distribution of keys between servers is required, but the function is designed to minimize the amount of such disruption.
In practice, you do not actually need a dedicated caching cluster, as your caches could run in-process in your web servers; each web server being able to determine the other webserver which should store cache data for a key.
Consistent hashing is used at large scale. It might be overkill for you at this stage. But just be aware of the scalability bottleneck inherent in O(N) messaging architectures. A replicated cache is possibly a good idea to start with.
EDIT: Take a look at Infinispan, a distributed cache which indeed uses consistent hashing out of box.
|
This may be a dumb question, but i am not getting what to google even.
I have a server which fetches the some data from DB, caches this data and when ever any request involves this data, then data is fetched from cache instead of from DB.There by reducing the time taken to serve the request.
This cache can be modified, i.e may be some key can get added to it or deleted or updated.
Any change which occurs in cache will also happen on DB.
The Problem is now due to heavy rush in traffic we want to add a load balancer infront of my server. Lets say i add one more server. Then the two servers will have two different cache. if some thing gets added in the first server cache, how should i inform the second server cache to get it refreshed??
|
maintaining cache state in different servers
|
Take a look at the assets_version parameter, so every asset get a version string without doing extra things in the template
|
I'd like to force client's cache refresh for modified assets.
Is there already a native way to do it with asset() like
<script src="{{ asset('js/main.js')|autoversion }}"></script>
?
If not, I found this really elegant solution (based on file timestamp & url rewrite) to manage it.
Did someone already faced this question and would know how to extend asset() for example?
|
Symfony - Assets cache auto versioning
|
It is not necessary.
It is true that following code would not be thread-safe as a result of cache.get() can be invalidate by another thread.
VALUE ret = cache.get(key);
if (ret == null) {...}
However, the code is there just for an optimization (atomic operations are more expensive). Atomicity is ensured by map.putIfAbsent() which is atomic and therefore thread-safe. Nevertheless, if cache.get() returns something else then null, expensive atomic operation does not perform.
|
if a ConcurrentHashMap is used as map I ask myself what is the correct way to achieve thread safety?
In a book I found someting like this:
private ConcurrentHashMap<KEY, VALUE> cache = new ConcurrentHashMap<>();
public V put(KEY key, VALUE value) {
VALUE ret = cache.get(key);
if (ret == null) {
ret = cache.putIfAbsent(key, value);
if (ret == null) {
ret = value;
}
}
return ret;
}
Now I ask myself isn't it necessary to make the the get and possible put atomic like this:
public V put(KEY key, VALUE value) {
synchronized(cache) {
VALUE ret = cache.get(key);
if (ret == null) {
ret = cache.putIfAbsent(key, value);
if (ret == null) {
ret = value;
}
}
}
return ret;
}
Because when cache.get() returns null, another thread could invalidate the cache.get() result for the 1st thread?
Cheers
Oliver
|
ConcurrentHashMap as cache
|
Caching the big array only makes helpful if you're planning to retrieve it always as a whole. However cache invalidation will be a very "heavy" operation as anytime when you change something you have to invalidate the whole array and reread it from the DB.
10k in redis is not much at all. You can have millions of entries without problem.
I would go with the b) version. Cache every entry individually. Easier to maintain, simpler application code and smaller memory footprint from application side which gets more and more important when you want to scale your application.
|
Assume, that I have a big (MySQL-)table (>10k rows) with id -> string. I can put them all in an array and cache this array. But the question ist: How to cache it efficiently?
a) Cache it as one big item. So I will execute
$redis->set("array", $array);
Quite short and easy. But for every entry I need, I have to fetch the whole thing. Absolutely inefficient.
b) Cache every entry itself:
foreach( $array as $id => $str )
$redis->set( "array:$id", $str );
Using this way, I will have >10k entries in Redis. That doesn't feel good. If I have 10 of these tables, i will have 100k entries....
So what's your proposal? How to cache a big array?
|
PHP: How to cache a big table in redis?
|
3
Things can work with only one line of code
Response.CacheControl = "no-cache";
But it is good practice to delete the existing page from cache.
Response.ExpiresAbsolute=DateTime.Now.AddDays(-1d);
Response.Expires =-1500;
Response.CacheControl = "no-cache";
you can check that page is expired or not on page load
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (pageIsExpired()){
Response.Redirect("/Some_error_page.htm");
}
else {
var now = Now;
Session("TimeStamp") = now.ToString();
ViewState("TimeStamp") = now.ToString();
}
}
}
private boolean pageIsExpired()
{
if (Session("TimeStamp") == null || ViewState("TimeStamp") == null)
return false;
if (Session("TimeStamp") == ViewState("TimeStamp"))
return true;
return false;
}
Source :http://www.codeproject.com/Articles/11225/Disabling-browser-s-back-functionality-on-sign-out
Share
Improve this answer
Follow
edited Aug 12, 2013 at 9:41
answered Aug 12, 2013 at 9:18
Sain PradeepSain Pradeep
3,12911 gold badge2222 silver badges3333 bronze badges
3
I tried this code and put it on my master page and click back. The page is still there.
– Luke Villanueva
Aug 12, 2013 at 9:25
yes mate, page will be there you are only disabling the cache not the stoping the page to be render again.
– Sain Pradeep
Aug 12, 2013 at 9:39
So placing them on the master page on load is fine? Thanks!
– Luke Villanueva
Aug 12, 2013 at 9:39
Add a comment
|
|
I'm using ASP.Net VB. I'm trying to disable caching throught the website because my client is having an issue that he needs to clear his cache in order to make the system work.
I put this bunch of code in my master's page page_load.
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache)
Response.Cache.SetNoStore()
Response.Cache.SetAllowResponseInBrowserHistory(True)
And access my cache in chrome here. chrome://cache/
The first question is, is this the right way of disbaling caching? Next is, I assumed that putting it on master page will have all pages be affected by this, is this a correct assumption? Lastly, how do I know if this code is working/if my browser is still storing cache to check if the code is right. Any ideas? Thanks!
|
Disabling cache on all browser
|
The most comprehensive profiling tool for linux is oprofile, which can profile single applications or your entire system, and can give you detailed information about cache misses (and where they are occurring) on processors that support performance counters for events like cache misses (pretty much all x86 processors made for the past 20 years support such counters)
Page faults have nothing to do with cache misses, though they are also a potential source of performance problems.
|
I want to find how much cache efficient my C++ code is. I am running it on UBUNTU. How to find the number of cache hits or cache miss ?
Another Question is: I found using time command: one part of my code is giving 2133 (minor) page faults and another one is giving 2361 (minor) page faults. Is (minor) page faults is related to cache miss? If so how it is related. I have to perform some I/O is that can cause (minor) page faults ?
|
number of cache hits/miss vs page faults - C++ code - UBUNTU
|
I found a solution to this "problem" actually.
I ended up modifying the source-code to Leaflet (thank you for Open Source), in such a way that the engine creates a leaflet-layer container for each layer. Instead of clearing the bgBuffer and foreground all the time.
And then when it zooms out, it positions the target layer behind the current active one. What this does, is that it covers all the gray area around the current one. And thus, creating the illusion that the tiles "outside" the viewport are actually loaded.
This might be a dodgy description of how I made it. But the idea is simple; just keep all the layers, and position the target layer behind the current one when zooming out.
|
I'm experiencing a issue with the tiles cache in leaflet.
If I start at point A, pan to point B, and then look at the tiles inbetween; they are cached and such. No problem.
But if i pan from A to B, zoom in, and zoom out, and pan back to A, the tiles are cleared!
By other words, the cached tiles seems to be cleared when altering the zoom-levels.
Is this a common behaviour, and can it be prevented? i.e. can I force leaflet to keep ALL loaded tiles in memory? I have tried playing around with the various options for the map and layers, without success. The option unloadInvisibleTiles is false by default, which implies that tiles are kept in memory..
I'm trying to create some sort of navigation on a map, where you can pan, zoom, back and forth.
Therefore I need all the loaded tiles to be kept in memory, for a smooth experience.
Thank you in advance.
|
Leaflet clears tile cache on zoom
|
In the front controller (web/app.php) you can define a prefix to prevent cache conflicts. Make sure this prefix is unique for each application.
// web/app.php
...
// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
....
|
I ran into a very bizarre problem today, I had created a cms like site with symfony2 today I created a new directory and copied the site here because I wanted to work on a project base on that, after doing some editing I realized when I open the first site it also shows the second one, they even share the session !!!
To summarize :
I had site A
copied site A and renamed it to B
edited B
whenever I open either one of A or B it shows the same thing ( the
first one I open after xampp starts )
P.S : I have changed the database and global secret parameters for the new site with no luck
Has anyone faced a similar problem before ?
thank you :)
Edit : the problem is with APC caching is there any way to make APC realize these are two different apps ?
|
APC can not differentiate multiple symfony sites
|
Declare three new env variables for your heroku app
BIG_MEMCACHIER_SERVERS
BIG_MEMCACHIER_USERNAME
BIG_MEMCACHIER_PASSWORD
Add a file called big_cache.rb in the config\initializers directory:
module Rails
def self.big_cache
@big_cache ||= ActiveSupport::Cache::DalliStore.new(
(ENV["BIG_MEMCACHIER_SERVERS"] || "").split(","),
:username => ENV["BIG_MEMCACHIER_USERNAME"],
:password => ENV["BIG_MEMCACHIER_PASSWORD"])
end
end
Now you can access the 2nd cache as follows:
Rails.big_cache.fetch(..)
|
I am storing database query results in memcache on heroku. I am using memcachier addon on heroku. For example if I have a cache User's tasks in memcache. I do something like this:
def cached_tasks
Rails.cache.fetch([:users, id, :tasks], :expires_in => 12.hours) { tasks.to_a }
end
This works perfectly fine but I want to use two different memcache instances to store data.
Why?
One that is used very frequently, basically data changes frequently and another for those which are big data objects and those will never change or very rarely.
How can I use two different instances and specify that cached_tasks should be stored in memcache_instance_1 and other like cached_images should be stored in memcache_instance_2
Why not to use the same one:
Because sometimes I need to flush the whole cache and that will flush the big data too which I don't want to.
Any suggestions?
|
How to use two different memcache instances on heroku
|
The two code snippets should be identical if we assume that img.getVal(x,y) returns the same value every time. Which of course, without knowing exactly how img.getVal(x,y) is implemented, we can't say.
As to how many hits and misses this line of code generates will be entirely dependent on what the state of the cache is at the entry of the code, and if the code gets interrupted, etc, etc. But one would assume, if this line is run in isolation, with empty caches and no interrupts, that it's one miss (for the read operation) and one hit (for the write back of the updated value). But that doesn't take into account wnatever img.getVal(x,y) does - which I don't know, since you don't show that code.
|
I was practicing with exercises on caches when I got stucked and I started wondering about differences between a unary increment ++ and the +1 operation.
I have this line of code(let's call it CODE1):
h[img.getVal(x,y)]++;
Is this the same of coding the following?(let's call it CODE2)
h[img.getVal(x,y)]=h[img.getVal(x,y)]+1;
It is obvious that they are the same, speaking about the macroscopic effect(they both increment by 1 h[img.getVal(x,y)]), but, are they really the same?
I am wondering this because of caches.
Let's say we have a direct-mapped cache and that the first pixel(0,0) is allocated in RAM at address 0xA0000000, while the first h[0] at 0xB0000000.
Assuming a 6-bit offset, 10-bit index, and 16-bit tag, we have this situation:
0xA0000000 in binary is:
--------TAG---------|---INDEX----|-OFFSET
1010 0000 0000 0000 |0000 0000 00|00 0000
as well as 0xB0000000 in binary is:
h[img.getVal(x,y)]=h[img.getVal(x,y)]+1;
0
How many misses and hits(AND WHY) are there using the 2 codes, assuming that we are accessing pixel(0,0), so x=0, y=0, and that pixel(0,0) has a value of 0(it's black, this is a grayscale image)? Are there differences using those 2 different codes?
I would say there are at least 2 misses, because, in both cases, first the program has to do h[img.getVal(x,y)]=h[img.getVal(x,y)]+1;
1, which results in a miss, fills a line in the cache and returns the value 0 to the CPU, and then h[img.getVal(x,y)]=h[img.getVal(x,y)]+1;
2 which returns a miss as well, because the cache does not contain any information related to the h array yet.
But then, what happens?
We now have in cache the value of h[img.getVal(x,y)]=h[img.getVal(x,y)]+1;
3 and we need to increment it. I think there are differences here using the 2 codes above.
Cheers,
Marco
EDIT: This is not referred to any particular compiler. I am wondering how this works. (The exercise is on paper)
|
Increment challenge: ++ vs. +1
|
Why not simply use the stdio facility? You can use fdopen to create a FILE* that will read/write to a given file descriptor, and then set the buffer size you want with setvbuf.
fdpipe = open(PIPE_NAME,O_RDONLY);
......
fd = open(filename,O_CREAT|O_WRONLY|O_TRUNC|O_LARGEFILE,S_IREAD|S_IWRITE);
FILE* outf = fdopen(fd, "wb");
char obuffer[1024];
setvbuf(outf, obuffer, _IOFBF, sizeof(obuffer));
....
while((len = read(fdpipe,buffer,sizeof(buffer))) > 0) {
....
ret = fwrite(buffer,1,length = strlen(buffer),outf);
}
|
My purpose is to decrease the file-write operations to the kernel therefore looking for a caching/buffering mechanism on POSIX. I believe standard-C library setbuf does that but is there a similar call in POSIX?
E.g. I'd like to set a buffer size of 1Kbytes and do not want my program to initiate the actual write operation to the disk before buffer size is exceeded.
fdpipe= open(PIPE_NAME,O_RDONLY);
......
fd = open(filename,O_CREAT|O_WRONLY|O_TRUNC|O_LARGEFILE,S_IREAD|S_IWRITE);
....
while((len = read(fdpipe,buffer,sizeof(buffer))) > 0) {
....
ret = write(fd,buffer,length = strlen(buffer));
}
|
How to cache/buffer the data before write operation
|
I have resolved this question.
follow is my solution.
first add map in nginx.conf's http scope:
map $http_user_agent $device_type {
default 'pc';
~(iPhone|Android|IEMobile|Balckberry) 'mobile';
}
than you need edit fastcgi cache key, as follow:
#fast cgi cache def
fastcgi_cache_path /data0/nginx-1.2.6/cache levels=1:2 keys_zone=nginx_webpy_cache:30m inactive=1d;
fastcgi_temp_path /data0/nginx-1.2.6/cache/temp;
fastcgi_cache_key "$scheme$request_method$host/$device_type$request_uri$is_args$args";
#end
I place variable $device_type into the cache key. now pc and mobile has different cache version.
notice: if you need purge cache, you should purge tow version.
if you are chinese, please see follow article:
nginx cache with different user agent
|
a page has tow cache. one for pc web browser, another for mobile browser.
nginx can do this perfect. follow is part of nginx conf content:
map $http_user_agent $device_type {
default 'pc';
~(iPhone|Android|IEMobile|Balckberry) 'mobile';
}
#fast cgi cache def
fastcgi_cache_path /data0/nginx-1.2.6/cache levels=1:2 keys_zone=nginx_webpy_cache:30m inactive=1d;
fastcgi_temp_path /data0/nginx-1.2.6/cache/temp;
fastcgi_cache_key "$request_method$scheme$host$request_uri$device_type$is_args$args";
#end
as you see, i place $device_type into cache key for tow cache versions.
but i found with this conf, i can't purge nginx cache. how to purge these tow cache versions?
thanks a lot.
|
how to purge nginx cache which vary by user agent
|
Storing large items in SessionState is generally a bad idea - it will limit the scalability of your application due to usage of server memory. Even if you move SessionState to SQL, it will add to the IO and storage requirements of your app.
Below, I'm assuming you have a dynamic image generation action on a controller which is then referenced, e.g. <img src='http://myserver/image/generate/wmAvatar' >, i.e. the reason that you are rendering dynamic images is for the consumption of a browser?
If the dynamic images are specific 'per user', or per session:
Instead of using session state, generate and deliver the images dynamically with appropriate Http Caching headers, and they should then be cached by the browser. You may still need to handle the case for If-Modified-Since requests
If the images can be shared between multiple users, or at least re-used by the same user across sessions then yes, you could store them to disk (e.g. SSD) in a folder configured for appropriate caching (and even precompute the images if you can) and then your img links will no longer be dynamic (http://myserver/images/123456.jpg ). You will however need to handle cleanup of expired images, and also handle 404 type errors for deleted images. As above, use Http caching headers to reduce unnecessary I/O. However nowadays, caching in memory with a key value / NoSql database is also common, e.g. Redis, which can then scale in the cloud, e.g. Elasticache
|
I store a number of large bitmaps that I make dynamically, using session variables using the following:
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
Would using disk caching is better, and if so is there a good example or documentation. Thanks in advance.
|
MVC session variables storage Memory vs disk caching
|
You can use below code to check if url is present in templatecache
$templateCache.get('stringurl');
|
Is there a way to check if a given url is already present in AngularJS' $templateCache ?
To provide a bit of context : I made a directive that inserts a loader while waiting for ngInclude templateUrl to be loaded, then plays an animation, and I'd like that animation not to play if the content was simply retrieved from the cache and not fetched from the server.
|
how to check if a spcific url is alreayd in the $templateCache in angular
|
3
The <mvc:resources> tag was included in Spring 3.0.4. So it's not available in previous versions.
Share
Improve this answer
Follow
edited Apr 6, 2017 at 8:39
answered Oct 16, 2013 at 6:10
aaguileraaaguilera
1,09011 gold badge1010 silver badges2828 bronze badges
Add a comment
|
|
I am trying the resolve browser cache problem by using buildnumber-maven-plugin. And when i try to enter tag in application-context.xml file and try to deploy its not working and its undeploy whole war automatically (do not understand why it has happened.).
So, is there any way to achieve or i can use buildnumber-maven-plugin to solve my cache problem. I am using spring 2.5 version.
any help would be appreciated.
|
In Spring 2.5 <mvc:resources mapping="/xyz/**" location="/xyz/"/> is not working
|
Document-stores are made for this. I highly recommend Redis for this specific problem. It is a "key-value" store, meaning it does not have relations, it does not have schemas, all it does is map keys to values. Which sounds like just what you need.
Alternatives are MongoDB and CouchDB. Look around and see what suites you best. My recommendation stays with Redis though.
Reading: http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis
|
I have to implement caching for a function that processes strings of varying lenghts (a couple of bytes up to a few kilobytes). My intention is to use a database for this - basically one big table with input and output columns and an index on the input column. The cache would try to find the string in the input column and get the output column - probably one of the simplest database applications imaginable.
What database would be best for this application? A fully-featured database like mysql or a simple one like sqlite3? Or is there even a better way by not using a database?
|
Best practice to implement cache
|
I ended up writing a Filter to add the HTTP header based on the URL of the requested resource. Here's a simplified version:
CacheFilter.java
public class CacheFilter implements Filter {
private static long maxAge = 86400 * 30; // 30 days in seconds
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "max-age=" + maxAge);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
web.xml
<filter>
<filter-name>cache</filter-name>
<filter-class>com.example.CacheFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cache</filter-name>
<url-pattern>*.png</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>cache</filter-name>
<url-pattern>*.jpg</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>cache</filter-name>
<url-pattern>*.gif</url-pattern>
</filter-mapping>
|
I'm using the <enable-file-serving value="true" /> feature of WebSphere Application Server v7.0 to serve static content (images, CSS, JavaScripts) for my Java web app.
How can I modify the HTTP headers for this static content (e.g., add a Cache-Control or Expires header)?
|
WebSphere 7: Modify HTTP headers for static content file serving
|
I don't recommend handling DOS attacks at a grails layer. I always recommend putting a server like nginx or apache in front of a java web application. The web server can then be configured to proxy your web appplication. A firewall in front of the web server creates another layer of security. If you try to address DOS attacks at a web application layer you are most likely too late.
A quick reference on DOS is here: http://en.wikipedia.org/wiki/Denial-of-service_attack
Caching is not meant to fix DOS attacks btw. It is meant to improve application performance. A lot of DOS attacks occur on the socket level.
Again I would not recommend preventing DOS at a web application level. Regardless of the language you are writing in.
The other question that I have is have you load tested your application? You may be running into base performance issues. I would recommend looking at a commercial tool or web based load tuning services. I am guessing that you are actually seeing a custom web app performance issue, not an issue with DOS.
|
I have a Grails application running on Tomcat, with MySQL as the database server.
I've found through testing that it's very easy to create a Denial of Service attack on the site simply by refreshing a page multiple times (i.e., holding down F5). This causes load on the server to increase rapidly along with the number of connections to the MySQL database.
Eventually, the site becomes unresponsive, and it can take several minutes for things to return to normal.
Can anyone recommend ways to debug this?
Should I be looking at caching?
|
Grails / Tomcat: Avoiding denial of service attacks
|
What you are looking for (in Doctrine ORM) is only supported in the resultset cache, and only applies to results of SQL queries produced by DQL queries.
The exact name for the feature you are looking for is "second-level cache", which is not yet supported by Doctrine ORM, but is currently being developed (will hopefully be available in version 2.5) at https://github.com/doctrine/doctrine2/pull/580
For now, you will have to handle this kind of caching in your own service layer if it is really needed.
|
I'm using doctrine 2 without caching anything at the moment. I'd like to enable some caching system within Doctrine but it looks like you have to manage it manually everywhere:
$memcache = new Memcache();
$memcache->connect('memcache_host', 11211);
$cacheDriver = new \Doctrine\Common\Cache\MemcacheCache();
$cacheDriver->setMemcache($memcache);
$cacheDriver->save('cache_id', 'my_data');
...
$cacheDriver->delete('cache_id');
I'd like to know if Doctrine could manage this automatically. For instance:
The cache is enable, I request a User entity by id, Doctrine search in its cache, cannot find the user, fetch it, set it into the cache, return it.
I fetch a second time, Doctrine return me the cached User.
I update the User (or any of its relations) Doctrine detect it and break the cache for this object
I request the same User by id, Doctrine doesn't have it in cache anymore, fetch it and set the cache back with the updated user before to return it
Is that possible?
Cheers,
Maxime
|
Doctrine - Break query cache when entity is modified (second-level cache)
|
You should use write_fragment
def update
render :nothing => true
expire_action :action => :all
cache_path = ActionCachePath.new(self, {:action => :all}, false).path
write_fragment(cache_path, render_to_string(:json => Vendor.all))
end
Source that may help:
ActionCacheFilter
expire_action
|
I'm looking to expire and then refresh the cache for a controller action using a publicly accessible endpoint.
In my app currently, /all returns cached json, and /update expires the cache.
You can see the existing relevant code below.
What I'd like to do is not only expire the cache but force a refresh.
So, my question is:
Is there is a way to initiate the refresh of an action cache after expiring it, without hitting the action?
If the answer to that is no (as I'm beginning to suspect), then what would be the best way to do this? I require the update action to return an HTTP 200 status, not a 301 redirect so just redirecting to /all isn't an option.
VendorsController
caches_action :all, :expires_in=>2.weeks
....
def all
respond_to do |format|
format.json { render :json => Vendor.all }
format.html { render :json => Vendor.all }
end
end
....
def update
render :nothing => true
expire_action :action => :all
end
|
Rails action caching refresh after expire
|
2
You can use event adminhtml_cache_refresh_type.
Add to event section in global.
<global>
<events>
<adminhtml_cache_refresh_type>
<observers>
<module_alias>
<class>COMPNAME_MODULENAME_Model_Observer</class>
<type>singleton</type>
<method>cleanCacheType</method>
</module_alias>
</observers>
</adminhtml_cache_refresh_type>
</events>
</global>
Add this code to observer COMP_NAME_module_name_Model_Observer:
public function cleanCacheType(Varien_Event_Observer $observer)
{
if ($observer->getData('type') == "your_cache_type"){
//CUSTOM CODE
}
}
Share
Improve this answer
Follow
edited Nov 19, 2015 at 9:44
CommunityBot
111 silver badge
answered Oct 31, 2014 at 9:40
Ilia RachkulikIlia Rachkulik
2122 bronze badges
1
i am not getting all selected cache tags on "adminhtml_cache_refresh_type" event
– user13120736
Jul 10, 2020 at 9:00
Add a comment
|
|
In this Stackoverflow question the answer shows how to add a custom cache status: Magento Custom Caching with admin switch
Now my question is: Where is this triggered?
UPDATE:
I've followed the steps as mentioned above. Now I have this code in Abstract/Service.php
final class COMP_NAME_Abstract_Service
{
static private $_instance;
private $_licenseHelpers = array();
public function clearCache( $custom = false )
{
//DO SOMETHING
}
public function getCache()
{
//DO SOMETHING
}
}
But I have to 'call' the clearCache function somewhere, but where and how?
|
Magento: where is the trigger of the custom cache?
|
You want to save it in the app's Documents directory:
NSData *imageData = UIImagePNGRepresentation(newImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];
NSLog((@"pre writing to file"));
if (![imageData writeToFile:imagePath atomically:NO])
{
NSLog((@"Failed to cache image data to disk"));
}
else
{
NSLog((@"the cachedImagedPath is %@",imagePath));
}
Then just save the path in your NSMutableDictionary with:
[yourMutableDictionary setObject:theIMagePath forKey:@"CachedImagePath"];
Then retrieve it with something like:
NSString *theImagePath = [yourMutableDictionary objectForKey:@"cachedImagePath"];
UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];
I recommend saving the dictionary inside NSUserDefaults.
|
I have the following code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//P1
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell Identifier"] autorelease];
cell.textLabel.text = [photoNames objectAtIndex:indexPath.row];
//Check if object for key exists, load from cache, otherwise, load
id cachedObject = [_cache objectForKey:[photoURLs objectAtIndex:indexPath.row]];
if (cachedObject == nil) {
//IF OBJECT IS NIL, SET IT TO PLACEHOLDERS
cell.imageView.image = cachedObject;
[self setImage:[UIImage imageNamed:@"loading.png"] forKey:[photoURLs objectAtIndex:indexPath.row]];
[cell setNeedsLayout];
} else {
//fetch imageData
dispatch_async(kfetchQueue, ^{
//P1
NSData *imageData = [NSData dataWithContentsOfURL:[photoURLs objectAtIndex:indexPath.row]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:imageData];
[self setImage:cell.imageView.image forKey:cell.textLabel.text];
[cell setNeedsLayout];
});
});
}
return cell;
}
Other than this, the viewDidLoad method fetches from the web, the json result from flickr, to populate a photoNames and photoURLs. Im trying to cache already downloaded images into a local NSDictionary. The problem is that the images arent loaded. Not even the loading.png placeholder image.
|
How to cache images for a tableview?
|
While it is hard to give you a "definitive answer" the easiest thing you could do (next to doing optimizations mentioned at Yii's Definitive Guide: Performance) is to use page caching
As you can't use APC or memcached I suggest you to use a file cache via CFileCache to cache the whole page. As soon as it is updated you should then invalidate the cache via a proper CacheDependency. I've used the Flushable cache dependency extension for invalidating a cache using CActiveRecord's afterSave hook. It is easy to implement and does the job.
EDIT: Just took a look at your site and judging from the menu you are using Bootstrap (maybe using Yii-Booster?). The site is extremely slow indeed, but that might actually be due to an extension publishing its assets on every request. I once had this exact problem with Yii-Booster publishing assets when in DEBUG mode (back then it even happened when DEBUG mode was disabled)(https://github.com/clevertech/YiiBooster/pull/229).
|
I have a site that have its pages stored in Database as html strings (generated with CKEditor) to enable user to edit them with no HTML knowledge. The site also makes extensive use of images galleries (user requirement so I have no control over it) each page with its gallery. This makes the site very slow. I have read of Yii optimization in Guide and did some query caching which improved load time a bit but it is still slow.
Since it might take as long as month for page to be updated (only when things change) is there a site-wide Yii caching technique to emulate static pages until page have been changed?
I have no control over installing APC or other extensions as I am not admin.
Any optimization idea is welcomed too.
you can see a site here
|
Yii Optimization of Semi-static site
|
The default behaviour of the REST server is to store entries indefinitely, regardless of the cache settings. If you want to use the default expiration settings of the cache, you have to specify timeToLiveSeconds=0 and maxIdleTimeSeconds=0.
This may change in future releases, see https://community.jboss.org/message/796785#796785.
|
I am using infinispan-5.1.6.FINAL as a remote-cache server and hot-rod protocol to access it. but found the is not working as intended, i.e cached value of a key is not evicted after 1ms as per the config below
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:infinispan="urn:infinispan:config:5.1"
xsi:schemaLocation="urn:config:5.1 http://www.infinispan.org/schemas/infinispan-config-5.1.xsd">
<global >
<globalJmxStatistics enabled="true"/>
</global>
<namedCache name="my-cache">
<expiration lifespan="1" maxIdle="1" reaperEnabled="true" wakeUpInterval="1" />
</namedCache>
</infinispan>
I exploded war (infinispan-5.1.6.FINAL/modules/rest/infinispan-server-rest.war), saved the above config, changed web.xml to use it and deployed in tomcat 6.0.32
I was able to put into the cache and retrieve from it, by this resource
http://localhost:8080/infinispan-server-rest/rest/my-cache/1
but the entry is not evicted even after 10mins. btw the same config was working in embedded-cache mode.
did I miss something? how can I get this working?
|
infinispan cache server expiration failure
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.