Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
1 After trying all the solutions proposed by various links online, we found that none of those solutions worked for us. Finally, after couple of hours of head banging, we realized that the issue in our case is not related to permissions. In fact it was because the system has used up 100% of the allocated disk space. Removing files and freeing up some space from our disk actually resolved the issue. Share Improve this answer Follow answered Jun 13, 2014 at 8:19 didiFaridididiFaridi 46111 gold badge66 silver badges1212 bronze badges 1 If there was no free space it's hard to believe this was the only problem encountered =) – AD7six Jun 13, 2014 at 9:34 Add a comment  | 
I am having a problem with troubleshooting this: I am getting this kind of warning on my website suddenly, it never happened and I tried to solve it by following various methods i found over the internet. Warning (512): _cake_core_ cache was unable to write 'cake_dev_en-us' to File cache [CORE/Cake/Cache/Cache.php, line 325] Warning (512): _cake_core_ cache was unable to write 'debug_kit_en-us' to File cache [CORE/Cake/Cache/Cache.php, line 325] I have tried: chmod -R 777 tmp Delete the tmp folder and then recreate it with its subdirectories. Delete the tmp folder and upload a fresh tmp folder from a fresh cakephp folder. Already run whoami php script and already made sure the folder belong to that user. I tried to reboot the server. Cakephp version : 2.4.5 Server OS: Centos 6.5 PHP Version 5.3.3 Apache version: Apache/2.2.15 I have tried most of the solutions from stack overflow and other places but no luck so far. Could it be an issue with my server configuration or from cakephp it self? If my question is still unclear, please feel free to request more clarification. Thanks for any help.
Cakephp Warning 512 cache folder unable to write
1 Download the video when you load it first time, and store it in your app's data folder. After that intercept the video url request in your webview and stream the video from local. @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { //Here check whether /request.getUrl().toString()/ is video url, if Yes, then Get the locally saved video and convert it as inputstream and return as follows, return new WebResourceResponse(getMimeType(request.getUrl().toString()), "UTF-8", 200, "OK", responseHeaders, inputStream); Share Improve this answer Follow answered May 10, 2017 at 13:34 RaguRagu 23322 silver badges66 bronze badges Add a comment  | 
I have a webview in android that goes to website that has a video tag in it. What would be the best way to either download the video or cache it so that it won't download every time it's being played. Couldn't find anything that works.
Webview download/cache video
1 Etags are not currently implemented in Varnish (see the wiki). Share Improve this answer Follow answered May 15, 2014 at 11:53 Brandon - Free PalestineBrandon - Free Palestine 16.6k1212 gold badges5656 silver badges9090 bronze badges Add a comment  | 
Is there some way to have Varnish generate a ETag for a backend response it recieves and add it to the response? I would prefer to have all ETag logic in Varnish instead of configuring this for all my backend nodes individually. I'm using Varnish 4.0.0.
Can Varnish generate ETags?
1 AFAIK, on bullets 1 and 2, you are correct. For your bullet 3, the data in L1 does not have to be written back to L2 after the block (by block, I believe you meant threadblock) finishes. The reason is, all write accesses always go to L2, invalidating the possibly present data in L1. For your bullet 4. No, I don't think there is any difference. Share Improve this answer Follow answered Dec 16, 2014 at 16:37 user2030440user2030440 8111 silver badge11 bronze badge 1 About 3: Why do you claim all write accesses always go to L2? Aren't you assuming all writes are st.cg instructions? – einpoklum Mar 19, 2017 at 17:39 Add a comment  | 
Suppose I have below CUDA kernel, launched with 256 blocks each having 256 threads. nElem is 256*256, and elems is allocated in device global memory. The device is cache-enabled (Fermi or above), and UVA is in effect. As you can see elems is NOT volatile. __global__ void simpleGPUKernel(int* elems, int nElem) { unsigned int tid = (blockIdx.x * blockDim.x) + threadIdx.x; for ( unsigned int i = tid; i < nElem; i += blockDim.x*gridDim.x){ elems[ i ] = i; } } Based on my understanding, at the end of each block, because there's no data dependency, syncing or fencing, the time when L2 updates the device memory cannot be determined, and mostly depends on cache size (because of LRU policy) and the memory access frequency caused by other threads. Am I correct? Because there's no necessity to wait for the actual memory address to be updated quickly, after elems[ i ] = i; instruction, SM warp scheduler, without being concerned about the actual device memory updated or not, runs further instructions from the warps in the block (in above case addition and comparison in the for loop), ends the block, and allocates another block for recently-freed resources. During described procedure, SM is enjoying Instruction Level Parallelism, and there's no guaranty that elems[ i ] in device memory is updated. Am I correct about this? If Anything is cached in L1, it has to be updated in L2 before the life-span of the block finishes. Is this correct? Apart from the speed associated with updating the actual memory from L2, is there any difference in above described procedures if the allocated memory is in the host memory or in a peer device global memory?
CUDA cache mechanism behavior for stores with a simple mem-filling kernel
Model TFmStation is best place to have the above logic. Components are there for generic functionality like UploadComponent, EmailComponent, RecaptchaComponent etc. If your logic part have something to do with model, then it should go into that model. A Model can be called from AppController.php in a similar fashion as you calling your Component.
I am using Cakephp 2.3 , i want to perform lots of common calculation in my several controllers. so i write those functions in my appcontroller and i cached some datas.. but what happens is my appController will become fatty.. so i create some component to perform these actions.. i dont know my approach is right or not..? please suggest.. i want to use cache in my component, i tried this code. but nothing is cached.. public $helpers =array('Cache'); and $result = Cache::read('fm_data', 'long'); if (!$result) { $result = $this->TFmStation->find('all',array('contain'=>array('TLocation', 'TLanguage','TMediaOrg','TContactPerson', 'TAddress','TFmProgram'=>array('TTargetGroup')))); Cache::write('fm_data', $result, 'long'); } return $result; please help me to how to use cache in component how to effectively use component class in cakephp in the case of more common functions in the application.. when i write these functions in appController it load all the functions so according to memory prespective, how to effectively use component
Cakephp using Cache in Component
It turns out that CFInclude actually compiles the (already rendered in this case) content into a class, which itself has overhead. The classes aren't unloaded (according to CFTracker) and as such, too many of these can cause permgen errors. FileRead() seems to be orders of magnitude more efficient, as all we're doing is inserting content into the output buffer.
While I've always cached database calls and placed commonly used data into memory for faster access, I've been finding of late that simple processing and output of data can add a significant amount of time to page load and thus I've been working on a template caching component that will save parsed HTML to either a file, or in memory, for quicker inclusion on pages. This is all working very well, reducing some page loads down to 10% of the uncached equivalent - however I find myself wondering what would be the most efficient way to output the content. Currently I'm using fileRead to pull in the parsed HTML and save to a variable, which is output on the page. This seems very fast, but I'm noticing the memory used by the Tomcat service gradually increasing - presumably because the fileRead operation is reading the contents into memory, and quite possibly, Tomcat isn't removing that data when its finished. (Side question: Anyone know a way that I can interrogate the JVM memory and find details/stack traces of the objects that CF has created??) Alternatively, I could use cfinclude to simply include the parsed HTML file. From all the information I can find it seems that the speed would be about the same - so would this method be more memory efficient? I've had issues on the server before with memory usage crashing Tomcat, so keeping it down is quite important. Is there anyone doing something similar that can give me the benefit of their experience?
Coldfusion/Railo: What's the most efficient way to output file contents - fileRead or include?
The biggest difference between a Java app and a PHP app is that Java is typically a constantly running program handling several incoming connections at once, while PHP instances are started and torn down by the hosting web server for every single individual request. That means any class you load or object you instantiate or variable you assign only has a lifetime of a number of milliseconds (in a decently fast application). Static class properties work the same as in Java, however, the entire application is torn down after a few milliseconds, so this doesn't work as a long-term cache. And more importantly, each individual HTTP request is its own independent thread, so assigning something in one thread doesn't make it visible in any other simultaneous or subsequent threads. To cache something cross-request, you need an external data store. For this you have many options, depending on what suites you best: serialize to a file APC memcached Redis sessions (for per-user data storage) many more
The code below is how I used to cache objects in Java. class Account{ private static ArrayList<Account> accounts = new ArrayList<Account>(); //Array that holds Account objects private String username; //Unique Name or Username public Account(String username) { // constructor this.username = username; Account.accounts.add(this); //Add object to accounts Array } public String getUsername() { return this.username; // Return username } public Account getAccount(String username) { //Get object "Account" with username for (Account acc: Account.accounts) { //Foreach loop that loop over all accounts from the Array if (acc.getUsername() == username) return acc; // Return Account object if given username == object's username } return null; } } I commented it so it will make sense if you don't understand Java but Java OOP is similar to PHP OOP. From the Java code above I can hold all objects on an Array, So it doesn't query the Database all the time. 1) I'm wondering if I can do something similar with PHP to speed up code and cache classes. If this is possible can you please show me an example. If not what would be the best way to achieve this? 2) What are some good practices to use when object oriented programming to keep memory usage low? Thanks in advance
PHP - static classes and caching classes
You could add the spring aspect for caching using the maven aspectj plugin, by identifying the aspect class and applying it manually to the classes you want (check inside spring-aspects and spring-cache jars for the aspect). This mechanism is not directly linked to spring, it could be done with any aspect, not only spring aspects. The reason why it's not used is that it's not very convenient, because we need to know the classes we want to advise at compile time and cannot rely on spring annotation scanning mechanism. Load time weaving solves the problem you mention of making reentrant calls work in a more transparent way, without the inconveniences of compile time weaving. Load time weaving is the recommended way spring has put in place for using aspectJ weaving, enabled by annotation @EnableLoadTimeWeaving. For the concrete use case that you mentioned, there does not seem to be a good case to introduce compile-time weaving, in general there is no good use case for compile time weaving, which explains the lack of documentation available online. I believe your best option for the use case you mention would be to use load time weaving instead.
Currently i am using cache abstraction using proxy. Problem with proxy is that internal method calls don't work . Now, I want to use the compile time weaving instead of proxy as internal method calls works it. I have searched on google, but i didn't find any substantial link which explains how to use compile time weaving. There are many links for load time weaving. Can anyone give any example for compile time weaving with cache abstraction or some relevant link ?? Thanks in Advance.
Compile time weaving with Cache Abstraction in Spring
One possible solution is to assign a timestamp to the retrieved token. Time timestamp does not have to be "real", a sequence number suffices. When a thread retrieves the token from the token cache, it also retrieves the sequence number associated with the token. When a thread fails to login, it first has to check the local cache again to see if the cache has been refreshed since it retrieved its token. If the sequence number of the current token is different from the one it currently has, it can try again with the token from the cache. Updating the token cache is necessary only when login fails and the cache has not been refreshed either since the retrieval of the failing token. There is a slight chance that the sequence number goes a full cycle wrapping around, and a task is mislead to think that the cache has not been refreshed when in fact it has a great number of times, but this is more of a theoretical possibility than a practical concern.
I am trying to implement a simple cache where my cache will consist of just a latest token returned by authentication server to my application. There are different worker threads which try to login simultaneously to authentication server.This increases load on authentication server and also my application becomes slow as for each authentication thread there is a round trip involved with the server. Hence by implementing a simple token cache, a token will be cached at client side and will be updated only when one of the authentication thread fails to login. Whoever fails will go and fetch a new token from authentication server. The problem I am getting is when any authentication thread fails and updates the token cache, there might be some threads who already have read the old token and will fail eventually and they also will try to update the cache. How can I stop these threads from updating the cache once it is already updated?
Implementing a token cache
1 Here's how I would go about achieving such a caching system: On a JSON request, I would use the file_exists() function to see if my cache.json file exists, if not, create one. (Good practice but only really relevant for the first run). Proceed to generate the JSON and write the result to the file before outputting to the HTTP stream. If the file exists, use PHP's filemtime() function to determine how old the file is, if it's older than 6 hours (or whatever you choose), re-open the file for writing and re-generate the JSON data for storage before outputting it to the HTTP stream. If the file exists but is was last modified in the last 6 hours, simply output the file contents and don't bother generating any JSON this time around. I hope this helps get you on the right path! That's probably how I would approach it, without employing the use of MySQL or anything like that. Good luck. Share Improve this answer Follow answered Mar 27, 2014 at 13:12 Shane ReevesShane Reeves 21811 silver badge77 bronze badges Add a comment  | 
I'm using PHP to create a JSON file that is then queried as part of an AJAX request. At the moment this is taking a good few seconds, which is far too long, especially given that this is in closed development so there are no simultaneous requests right now. I've noticed the delay is similar to the one when I try to load the JSON directly in the address bar. The data doesn't need to be constantly updated - even once every 12 hours would do. My question is: is it possible to cache this data on the server side to speed up the AJAX requests? If so, how would I go about it? Happy to post any relevant code, but I figured this question was quite abstract.
Caching a dynamic JSON file on the server
I'm not 100% on this but, I believe that because HttpClient uses the WinInet proxy for caching purposes, it will not work when running as a service. I.e. under IIS. See http://support.microsoft.com/kb/238425 for more details.
I have an HttpClient being used in an MVC application created as below: new HttpClient(new WebRequestHandler() { CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable) }); I'm sending out a request, and getting a response back as below: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Cache-Control: must-revalidate, max-age=3600 Date: Thu, 13 Mar 2014 10:26:41 GMT Location: <snip!>/api/customers/TEST X-AspNet-Version: 4.0.30319 Content-Length: 246 Content-Type: application/json; charset=utf-8 Expires: Thu, 13 Mar 2014 11:26:42 GMT } On my local it works fine, but on the staging server when calling the same urls the service is still getting hit; the cache is not being used. The MVC site using the service is hosted on IIS7, when developing I'm using IIS Express. Why would there be a difference between running it on my local machine (where caching works) and the staging server (where caching does not work), and how can I fix it so caching works in both cases?
HttpClient not using cache on staging server
1 I had the same problem. Just add Request::enableHttpMethodParameterOverride(); after $kernel = new AppCache($kernel); and then DELETE methods will work. Share Improve this answer Follow answered Apr 11, 2017 at 5:15 adamsafradamsafr 33533 silver badges1212 bronze badges Add a comment  | 
I have an issue with Sonata Admin Bundle that deleting (and maybe something else??) doesn't work when caching is on. It only works properly if I remove $kernel = new AppCache($kernel); from app.php. How can I deactivate caching for Sonata Admin?
Symfony2 disable cache for a specific bundle or route
1 There are three ways to save/persist data on clientside. These being: SharedPreferences (not ideal with requirements) File I/O SQLLite database As far as I know there isn't a big difference is performance between file-I/O and SQLLite. But SQLLite has a lot of other advantages. You can query the database, this is more easy then writing it yourself with file-I/O Manipulation of data is for more easy and less painful (delete/update records etc) Supports relations between data! Bottom line, go for SQLLite, it seems more work to setup but you will benefit from this in the future. Share Improve this answer Follow answered Feb 24, 2014 at 10:50 TobrunTobrun 18.3k1010 gold badges6666 silver badges8181 bronze badges 2 For my specific requirement, saving a file does the job. But what i would like to know is about 'Cache' Technique in HTTP Responses. Is it enabled by default,how does it work actually? Any tutorials about that? – zee Feb 26, 2014 at 4:58 1 All depends on architecture of your backend system. E.g. If they follow the REST conventions then they would have implemented the 304 - NOT MODIFIED header when you perform a GET request with If-Modified-Since. The best way to learn about these techniques is reading books and learning by hand, and most of the time you should implement these yourself, sometimes you can use a library (all depending on your backend interaction/architecture) – Tobrun Feb 26, 2014 at 8:02 Add a comment  | 
In Twitter Android App, Once the listview is populated with tweets/items downloaded from server, it never again talks to server to fetch them again. Even if you kill the app and start it again, it still retrieves the same old data.How does twitter store this much of data. Is it using database, storing all downloaded data in a file or caching. In my app , i have a similar requirement.For now i store the downloaded listview data in a file and then read it whenever the app is started afresh.Is there a better approach or a followed patter for this. Thank You.
How does Twitter App in Android cache/store tweets in the listview?
Redis doesn't provide that out of the box. However, it is open source so you could add your own logic to it if you really want... go http://github.com/antirez/redis, fork and start coding.
New to redis and it's full abilities. Currently I have a small web front-end that can determine if the item is in redis cache or not -- if it's not, it fetches the item from S3 and adds to redis cache. Is there a way I can have Redis actually perform an action (or run a script) on a cache-miss? Ideally I remove this web front-end and have the client (which is actually a REST server) connect directly to redis to retrieve the data (and redis would load the missing data from S3 on a miss) ... TIA
Redis cache-miss behavior
1 HttpContext.Current.Cache and HttpRuntime.Cache are the same, the context cache prop just returns the runtime Cache. HttpRuntime and HttpContext just return handles to this object. HttpRuntime.Cache is recommended but likely won't make a difference in most applications. HttpContext.Current.Application is not a cache, its a global named value collection. if you add an object to Application it will stay until a an appdomain recycle. If you put an object in cache, it not guaranteed to be there when you fetch it. The cache is free to throw it away if the cache get too large, or the object has fetched often enough. Share Improve this answer Follow edited Feb 5, 2014 at 10:18 answered Feb 5, 2014 at 10:13 Suhaib JanjuaSuhaib Janjua 3,5481616 gold badges6262 silver badges7474 bronze badges Add a comment  | 
What's the difference between: HttpRuntime.Cache["key"] HttpContext.Current.Cache["key"] HttpContext.Current.Application["key"] are there any major differences between these memories?
Difference between ASP.NET caches
The Pragma header is implementation specific and secondary to the Cache-Control header (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32). Better to not use it. Setting the cache to "private" prevents caching on proxies, you might want to set it to "public" for faster client response--this change is especially recommended if your content is served over HTTP rather than HTTPS ("public" is ignored in that case, unless SSL is cracked within for instance a corporate fire-wall).
What's the difference between <caching enabled="true" enableKernelCache="true"> <profiles> <add extension="*" location="Any" policy="CacheForTimePeriod" duration="00:30:00" varyByQueryString="*" varyByHeaders="Accept-Language" kernelCachePolicy="CacheUntilChange" /> </profiles> </caching> and <httpProtocol> <customHeaders> <add name="Cache-Control" value="private, max-age=1800, must-revalidate" /> <add name="Pragma" value="private, max-age=1800, must-revalidate" /> <add name="Expires" value="1800" /> </customHeaders> </httpProtocol> If I understand well, the first is for IIS (cache file on server, to answer quickly) and the second one is for proxy/client (ask a new version every 30 minutes) ? What do you think about my cache policies ? I want to improve performance but because I have important fresh information every 30min, I set to 30 min every cache...
IIS caching and HTTP caching
When setting the default memory-cache to false (so don't use .cacheInMemory(true)), the cache seems to be keeping itself to the set maximum. The computed cache is probably a combination of the on-disc cache and the memory cache. This does make the "cache" number from the Android OS somewhat less usable, but on the other hand, it is kinda fair. As it looks like the numbers are lineing up, it's just a matter of setting both maximums, and communicating this to the user.
I'm using the "Android universal image loader library (v 1.9.1)" and I'm trying to limit the amount of (disc) cache being used by using this line in a config builder: .discCache(new TotalSizeLimitedDiscCache(cacheDir, 25 * 1024 * 1024)) I might be doing something really stupid here, but this was supposed to limit my cache to 25MB and when I look at the current App info I'm already at 45+ MB, so it doesn't seem to be working. Have I missed something? added suspicion: what if the cache-number also includes the 'memorycache' that is set to true? I working under the assumption this is only a cache as far as the imageLoader is concerned, and from an application/os point of view just another thing using memory. if it isn't, it might explain the numbers? Complete code for initializing : private void initImageLoader() { DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisc(true) .build(); File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext()); cacheDir.mkdirs(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .defaultDisplayImageOptions(defaultOptions) .discCache(new TotalSizeLimitedDiscCache(cacheDir, 25 * 1024 * 1024)) .build(); ImageLoader.getInstance().init(config); } And for calling the code (showing imageUrl in imageView) ImageLoader.getInstance().displayImage(imageUrl, imageView);
How can I correctly configure limited cache for the android universal image loader?
We found the answer looking into this other stackoverflow question that was meant to show how to replace the KeyGenerator. The key was to comment out the <cache:annotation-driven /> from xml, and configure manually the interceptor for the annotations. It worked like a charm!
We're working on a multitenant application, and we need that the @Cacheable with custom key take into account an additional parameter, the tenantId. Spring Cache allows to customize the keg generator, implementing the interface org.springframework.cache.interceptor.KeyGenerator However that generator is not used by the Caching framework when the @Cacheable annotation is defined with a key (which indicates Spring Cache that they should not use the KeyGenerator, at least in Spring 3.2). This does not take into account the use case of multitenant applications, where all keys need to take into account the tenantId to avoid clashing keys between tenants. A solution for this problem is to replace the CacheInterceptor that comes with Spring Cache, by a custom version that do use the KeyGenerator in any case. The key part of code is in the superclass of CacheInterceptor, CacheAspectSupport: /** * Computes the key for the given caching operation. * @return generated key (null if none can be generated) */ protected Object generateKey() { if (StringUtils.hasText(this.operation.getKey())) { return evaluator.key(this.operation.getKey(), this.method, this.evalContext); } return keyGenerator.generate(this.target, this.method, this.args); } We handle a way of replacing that code for a version that takes into account the generation independently of the value of this.operation.getKey() by subclassing CacheInterceptor and overriding a couple of things. However, there is no easy way of replacing the interceptor in Spring Cache configuration. We're using xml configuration with <cache:annotation-driven /> tags The same question arisen in the Spring forums some time ago but there were no answers so far
How to register a custom CacheInterceptor instead of the one packaged in Spring?
1 Good news everyone, the latest mono alpha version (mono 4.3.2, available here: http://www.mono-project.com/download/alpha/ ) now supports ServicePointManager.DnsRefreshTimeout! Share Improve this answer Follow answered Feb 26, 2016 at 5:36 Brett ChristensenBrett Christensen 15122 silver badges44 bronze badges Add a comment  | 
I'm developing a software with C# + Mono in Ubuntu which makes use of network classes like WebRequest or Dns. During development phase, I used my code to connect to a local webserver 192.168.1.101 and after a while I had to move it to 102.168.1.20, and I used a local DNS server giving the mentioned IPs readable names (to simulate the real world scenario). But now, no matter what I do, I can not connect to the new server in my C# code! Here are things as they are: $ ping myurl.local => 192.168.1.20 $ nslookup myurl.local => 192.168.1.20 Log from my code: Dns.GetHostAddresses("myurl.local")[0].ToString() => 192.168.1.101 It seems to me that Mono has cached the DNS' resolved results from before and it won't let go of them. So I searched the Internet for it and I found this question. It has the same problem as mine but in Windows and .Net and also a solution. Unfortunately, its solution does not apply to mine, since ServicePointManager.DnsRefreshTimeout is not implemented in Mono! The worst part is that the cache is persistent even if I restart the software and/or hardware thus I'm unable to proceed with my development! So I wonder if there is a way I can reset Mono's cache, other than using DnsRefreshTimeout? Even a manual solution will do for now (something I can do in shell!? Like removing a file perhaps!?). I'm using Ubuntu 12.04 and Mono 3.2.3.
Resetting DNS cache in C# + Mono
I used grunt js library to minify the JS and CSS in my application. To begin with prepare a gruntexe.js file. Create build.sh file to install and run grunt. Sample gruntfile.js will as below module.exports = function (grunt) { grunt.initConfig({ bower: { install: { options: { targetDir: './src', cleanBowerDir: true } } }, exec: { buildUI: { command: 'chmod 755 ./build.sh && chmod 755 ./build.sh && ./build.sh' } }, replace: { replaceHtmlCacheTag: { src: ['./*.html', './cache.manifest'], dist: ['../'], // Minify all js file in dist folder replacements: [{ from: /\$\{timestamp\}/g, to: "<%= grunt.template.today('ddmmyyyyhMMss') %>" }] } }
The dojo and jquery libraries are downloaded from google CDNS and used in our project. I am looking for a java tool which can cache and minify these tools. The cache should happen inside the ROOT project of tomcat.I know YUI compressor is great minifier but looking for a open source tool which can do both caching and minify.
Best java tool to cache and minify the dojo, jquery js and CSS
just run sudo service varnish start or if it is already running sudo service varnish restart
I tried to service varnish start but it won't start. /etc/init.d/varnish: 33: ulimit: error setting limit (operation not permitted) /etc/init.d/varnish: 36: ulimit: error setting limit (operation not permitted) * Starting HTTP accelerator varnishd [fail] /var/run/varnishd.pid: permission denied
Varnish http accelerator failed
1 The solution I went with in the end was to run npm install and then zip up the entire Node.js application folder. Share Improve this answer Follow answered Jul 31, 2014 at 10:30 Thomas BrattThomas Bratt 49.3k3636 gold badges123123 silver badges140140 bronze badges Add a comment  | 
I need to install a Node.js application in a strictly controlled production environment that does not allow an Internet connection. Is this possible, for instance by populating a Node.js module cache somewhere? Many thanks!
How do I install Node.js modules on machines without an Internet connection?
1 If you could save also your class type into the database along with the object, you could infer the right class using something like: if (cursor.hasNext()) { Gson gson = new Gson(); DBObject dbobj = cursor.next(); Class type = Class.forName(dbobj.get("class").toString()); result = (V) gson.fromJson(dbobj.get("obj").toString(), type); } you can get the proper string with code like this: SomeClass object = ... Class c = object.getClass(); String cn = c.toString(); Edit Pay attention that when you want to store on database the class type and you are dealing with generics, due to type erasure, you cannot do something like this: ArrayList<Long> l = new ArrayList<Long>(); String clazz = l.getClass since clazz will store: java.util.ArrayList instead you need to do something like this Type listType = new TypeToken<ArrayList<Long>>() {}.getType(); String clazz = l.getClass(); that will return you: java.util.ArrayList<java.lang.Long> Share Improve this answer Follow edited Oct 22, 2013 at 21:05 answered Oct 18, 2013 at 22:18 giampaologiampaolo 6,92655 gold badges4545 silver badges7474 bronze badges 1 I like the idea of storing the class in the DB, which we will do, but as the put method is: public void put(K key, V value) { } I still don't think there is anyway to get the exact type from V? i.e. ArrayList<Long> ? – AlanW Oct 22, 2013 at 9:37 Add a comment  | 
I'm new to Mongo, and am trying to use it to implement a cache internally in our application. We have a defined cache interface (public Cache(K, V) ) with several alternative implementations (HashTable, JCS etc). I need to create a MongoDB implementation for some hard (i.e. expensive) to calculate data. The cache data will either be a POJO or a List of POJO's. My problem is getting the Mongo response back into a POJO or (the bit that's eluded me so far), into a List of POJOs. Code so far: public class MongoDBCache<K, V> implements Cache<K, V> { private String name = null; public MongoDBCache(String name) { this.name = name; } public V get(K key) { V result = null; try { DB mdb = getMongoDB(); DBCollection mcol = mdb.getCollection(name); BasicDBObject query = new BasicDBObject("_id", key.toString()); DBCursor cursor = mcol.find(query); if (cursor.hasNext()) { Gson gson = new Gson(); DBObject dbobj = cursor.next(); Class type = ????; result = (V) gson.fromJson(dbobj.get("obj").toString(), type); } } catch (Exception e) { e.printStackTrace(); } return result; } } I can kind of make this work if the value is just a POJO (can get the type on the put method, not ideal but works), but I can't figure out how to make it work for a List. As an example, a ArrayList<Long> ends up as ArrayList<Double>. Any suggestions? Something I can do in GSON? Something I can do with reflection? (I'm not tied into GSON, or any other library, this is just my current attempt). Thanks, Alan
How to retrieve a POJO from MongoDB via a Generic Class
For @Anwar : Download the whole html page of that particular memory-cache entry, then run this function on it (groovy) : function groovy { sed -n '/<pre>/,/<\/pre>/p' "$1" | replace '<pre>' '' '</pre>' '' | hex2mp3 - "$2" } function hex2mp3 { echo "in $1" echo "out $2" echo "cut -c10-74 $1 | xxd -r -p - $2" cut -c10-74 "$1" | xxd -r -p - "$2" } Groovy will extract the hexdump from the <pre> </pre> tags, and hex2mp3 will reverse the hexdump to its original binary form so that it in the end you get your mp3 back ;) cut will discard extra columns from the hexdump and xxd will do the actual reversing operation.
OS : Linux. So suppose I just streamed an mp3 file, the file is there in firefox's memory (I can see it in about:cache?device=memory). I tried a memory dump of the whole browser and searching (with hexedit) a string that is present in the mp3 file. Firefox has a nice about:cache?device=memory page that lists all files that are put in memory cache, I selected the mp3 in question and firefox displays a nice hexdump of it. So I've picked up a string from that dump and searched for it in the core. I could find it, but unfortunately the bytes the follow it are not the same as those that are shown in the about:cache hexdump page, it all seems like the file is scattered. How could I locate the file in memory and write it to disk ? thanks for any tips. EDIT A network-level solution is possible using wireshark
How can one get an mp3 file cached in firefox's memory?
1 When you make an ajax call , it is possible that, you are passing it as cache: false. When you call like that, ajax call will pass the URL with an extra parameter and value will be a random unique number. Since asp.net method receive this extra parameter and you configure outputcache with varyByParam="*" , this method will never cache. The solutions are set cache: true in ajax call - (not good when you are calling a dynamic method ) or set outputcache varyByParam="none" (use only when your method need cache irrespective of parameters) or set outputcache varyByParam="parameter1;parameter2" (this is the ideal solution if you have multiple parameters) . For single parameter use varyByParam="parameter1" Sorry for the late reply. I saw this question just now. Share Improve this answer Follow edited Mar 27, 2014 at 11:01 answered Mar 26, 2014 at 13:31 Jomy JohnJomy John 6,39844 gold badges2828 silver badges3232 bronze badges Add a comment  | 
I have an endpoint for a WCF web service which is not getting output cache hits in the performance monitor for AJAX requests, it does get an output cache for non AJAX requests to endpoint. Web config: <caching> <outputCacheSettings > <outputCacheProfiles> <add location="Any" name="myCache" duration="3600" varyByParam="*" /> </outputCacheProfiles> </outputCacheSettings> </caching> Is there an option I'm missing in the config? I've not included Javascript because I doubt the problem lies there since the server shouldn't have to check any headers to determine cache worthiness. The endpoint: [AspNetCacheProfileAttribute("myCache")] [WebGet(ResponseFormat= WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "suburb?name={name}&state={state}&category={category}&bedrooms={bedrooms}&country={country}")]
Output cache not working for AJAX varyByParam
To set-up APC in magento, you need to install php_apc.dll to your extension directory, and then need to do setting to php.ini files, after then need define in local.xml file for APC calling. Please follow below few links which will help you. http://www.magentocommerce.com/boards/viewthread/8937/P0/ http://www.aitoc.com/en/blog/apc_speeds_up_Magento.html http://magebase.com/magento-tutorials/speeding-up-magento-with-apc-or-memcached/ http://www.magecorner.com/magento-apc-cache/
I am new in magento and i had created 1 magento website.i want to setup APC cache for my magento website. My hosting provider installed apc catch in server,i check using php_info().now i want to setup that in my magento website. I read somany blog and forum but did not get proper solution. Still i don't nor from where i can start. Can you please help me and give me 100 % solution for that. Please please give me proper solution from starting to end. Thanks in advance
how to install apc cache for magento
There is a port of Polipo caching proxy for Android called Polipoid.
My Internet bandwidth is low and I share it with 4 devices on my WLAN, so I got an idea to implement a caching proxy, which will cache frequently downloaded resources. The most energy efficient device, which is always on, is a rooted Android tablet. So is there any web caching proxy server for Android? If not, how can I easily implement one? Thanks!
Is there any caching proxy server for Android?
1 Put the function in a package, and also add a PLSQL table in the package, index by VARCHAR2. At first execution, check the table using "tab_name || '.' || col_name" combined as the index (hash). If empty, run the query and write the dat to the PLSQL table, using the tab_name || '.' || col_name as the index. When the query runs which calls this fucntion within each session, the first call will be longer as it builds the table, subsequent ones will be much quicker. Things to watch out for with this approach is memory management (large data, number of sessions), stale data - not suitable for volatile data tables. You should consider a "free" fucntion in the package too to clear the cache. Share Improve this answer Follow answered Jul 22, 2014 at 17:01 TenGTenG 3,91233 gold badges2525 silver badges4444 bronze badges Add a comment  | 
I am using oracle 10g. I have following function in a package and it will be invoked within the package for many times. Instead, i want to maintain "function result cache"(available with 11g) and i will look up in cache first before executing the query. Is this possible with 10g or i have to choose some other option to achieve it? function f_get_col_data_type(tab_name varchar, col_name varchar ) return varchar is v_col_data_type user_tab_columns.data_type%type; begin select data_type into v_col_data_type from user_tab_columns where upper(table_name) = upper(tab_name) and upper(column_name) = upper(col_name); return v_col_data_type; end f_get_col_data_type;
How to cache the query result of a function in oracle 10g?
I think I would first take a look closely at your database commits. Client vars are retrieved at the "beginning" of a request and then updated at the "end" of the request with any changes. Consider the case where a cflocation happens at the end of a request. Is it possible that the "next" request draws pages from the DB before the update is committed? In a complex system with replication etc situations like this can happen. 6 clustered web servers is a significant number. As for caching in memory - CF caches the client var in memory and only "reads" from the store (the database) if the client var is changed (if an update has taken place). So you could be onto something there as well. Still, theoretically the client var cached in memory should be identical to the vars in the data store. Since it stores changes - which are also written to the datastore. This is done in real time (as I understand it) i.e. at the end of the request. All the Changes to the client vars are flushed to the DB. So theoretically even with round robin, if your browser showed up on a new server that did NOT have your client vars in memory it would just go get them out of the DB. That's why I think the DB might be the key here. NOTE: the update behavior might changed based on whether global vars are enabled or disabled. Take a look at each server to see if there is any differences in how this setting is used. As for sticky sessions: if you are using a hardware based load balancer make sure and explore it's balancing options. What you want is to use sticky sessions and for the LB to divide load among the servers. You want it to be smart enough to know about the actual load (CPU usage usually) not just the gross number of requests that have been divided among the servers. good luck. I love problems like this :)
We have a legacy ColdFusion application using 150 client variables to manage session state. The client variables are centrally stored in a SQL Server database within a 6 application server clustered environment using a round-robin load balancer. The problem is when the code updates a client variable with a new value, the old value is still being used and displayed even though the new value is updated appropriately in the CData table. This only happens intermittently in an average of 1 out of 1000 updates being made to the client variable using the cfset tag. Race conditions and caching issues are possible explanations. We “suspect” that the old value is still being cached on one of the 6 application servers. Adobe's documentation clearly states that client variables are cached into memory but does not go into further details. 1) Has anyone also experienced this issue and found a good resolution? 2) What are the implications of moving to a sticky session while we keep using the client variables?
ColdFusion Client Variable Showing Outdated Value Intermittently
1 Pro of xmemcached: - supports failover - the configuration "host1:port,host2:port". The client goes into "host1:port" until this memcached is aliave. After this memcached fails, it goes into "host2:port". Cons of xmemcached: - setWithNoReply() operation is not stable. We had to use set() instead: http://code.google.com/p/xmemcached/issues/detail?id=194 - partitioning/sharding is heavy. The configuration "host1:port,host2:port host3:port,host4:port" is much heavier for the client than the configuration "host1:port,host2:port" - There is only one contributor to xmemcached, while there are a lot of contributors in spymemcached Share Improve this answer Follow answered Nov 27, 2013 at 14:54 NeighbourNeighbour 971010 bronze badges Add a comment  | 
For your project chose memcached. Found two implementations for Java xmemcached and spymemcached. Very little information about the difference between these products. What is the essential difference? What is the advantage of one over the other? How do you use in your projects?
Difference xmemcached vs spymemcached
If you are using Gevent you can have your read-only data structures in the global scope of your process and they will be shared by all the greenlets. With Gevent your server will be contained in a single process, so the data can be loaded once and shared among all the worker greenlets. A good way to encapsulate access to the data is by putting access function(s) or class(es) in a module. You can do the unpicliking of the data when the module is imported, or you can trigger this task the first time someone calls a function into the module. You will need to make sure there is no possibility of introducing a race condition, but if the data is strictly read-only you should be fine.
I am building a python based web service that provides natural language processing support to our main app API. Since it's so NLP heavy, it requires unpickling a few very large (50-300MB) corpus files from the disk before it can do any kind of analyses. How can I load these files into memory so that they are available to every request? I experimented with memcached and redis but they seem designed for much smaller objects. I have also been trying to use the Flask g object, but this only persists throughout one request. Is there any way to do this while using a gevent (or other) server to allow concurrent connections? The corpora are completely read-only so there ought to be a safe way to expose the memory to multiple greenlets/threads/processes. Thanks so much and sorry if it's a stupid question - I've been working with python for quite a while but I'm relatively new to web programming.
Caching large objects in a python Flask/Gevent web service
You can find more answers to what you might desire on the Stackoverflow question: How to display the content of asp.net cache? Basically you can create a page to view all cached items from your application. After that, it can customize and UI pump it to your needs and objectives. If you just need to debug, then you can use Ringer's solution displayed on your comments.
Is there any third party tool or something in visual studio that lets you see the cached objects? For example, an action is caching data (varied by parameters) and I want to see the cached objects and the attributes (like which parameter values were sent to the action when this data was cached).
View cached data in ASP.NET MVC
It makes very little sense to use a cache in front of MongoDB if you are using it for reads only. An extra cache is just going to take up more memory. MongoDB uses memory-mapped files and the Operating System will keep the most requested data in memory. If all of your data fits in memory, then MongoDB will returns all the documents straight from it - just like an additional cache would.
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 10 years ago. Improve this question What I am trying to do is cache all the data that I have written into mongodb. So that all client requests are served from the cache. Should I consider ehcache or memcache. Note the mongodb data is queried a lot, that is why I have thought to cache all of it at server start time, no writes are permitted to this data. I am using java for the application.
How to cache all the data files of mongodb? [closed]
The problem is that the process is running in the same thread, so the form doesn't actually get disabled before the process starts running. The easy thing to do would be use Application.DoEvents() to force it to set everything to disabled before starting the process, but the more professional (and probably safer) method is to run the time-consuming process in another thread. NOTE: After running into another hitch in my own programming I found that you may have to run Application.DoEvents() before enabling everything again--it will fire any clicks the user made on the disabled controls, instead of waiting for the process to complete--enabling the controls--and THEN firing the click. Obviously DoEvents is messy and I should be using threads.
I have a problem while doing this in the code-behind file of a winform : // Waiting Cursor + disabling form Cursor = Cursors.WaitCursor; this.Enabled = false; // Synchronous method SomeWork(); // Re-enabling form Cursor = Cursors.Default; this.Enabled = true; Current Behaviour Clicking on a button for example during Somework() will execute the method associated to the button after re-enabling the form. Expected Behaviour I don't expect from the form to store the clicking events of the user while the form is disabled. Question Is there a way to empty the Clicking cache of the form (So that I'd do it before re-enabling the form) ? IMPORTANT EDIT A possible easy solution would be implementing the IMessageFilter interface in the code behind of the form. Disabling the left seems easy using this PreFilterMessage : public bool PreFilterMessage(ref Message m) { // Blocks all the messages relating to the left mouse button. return (m.Msg >= 513 && m.Msg <= 515) ; } But once again, disabling and re-enabling the mouse's left clicks DOES NOT EMPTY THE MOUSE BUFFER ...
Clearing mouse buffer in C#
here are some approaches that might work for you. Extend your existing Webpart with a cache. So the first User who visit the Site will wait as long as with the existing Solution. But he will fill the cache, so every other call of the Site will be much faster http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.webpart.partcachewrite(v=office.15).aspx Create a Timer-Job that fill up da extra SharePoint- List with the fields you need. So you render your Webpart using this data. To fetch the needed data from the List will be much faster than iterating some SPWeb or SPSite Objects. A lot of data already can be fetched from the Search-Service, and you can extend the Attributes the search engine will crawl. Once the search attributes are extended you can create a search driven Webpart http://technet.microsoft.com/de-de/library/jj679900(v=office.15).aspx Each of this Solutions should work at SP 2007/10/13 If you need a quick-win than mybee Solution 1 is the best for you. Regards
We have this page in SharePoint that list all the sites, the person who manages that site, their contact info, and the last modified date. Currently, we are using a custom webpart that crawls through the sites and reads through the metadata, and then it displays all these in a list. Opening this page takes about 10+ seconds. We're looking at ways to cut this time to less than 3 seconds. I'm thinking about some sort of timer job that caches the page, say every half hour, and when the page is requested, simply display the cached version. The data in the page itself doesn't change that often so caching isn't really a big issue. Is this idea feasible? I'm fairly new in SharePoint so what would be the steps to implement this? Or if there are any other options/suggestions on how to reduce the load time, I'm all ears.
SharePoint loading time optimization and caching
1 Not the most elegant solution, but I ended up just removing caching from my artisan commands. These were just background tasks that did not need the same speed boost as the front end does. Share Improve this answer Follow answered Mar 12, 2014 at 17:57 John VeldboomJohn Veldboom 2,1292727 silver badges3030 bronze badges 2 Good point, I would like my artisan commands to work fast since they are a core part of my product...but at least a user doesn't need to wait on them to finish. – Sam Mar 12, 2014 at 18:00 1 Just as a heads up to you, I'm personally moving away from file storage cache to a Redis DB. Takes more RAM obviously, since its in-memory storage, but I like it a lot. – Sam Mar 12, 2014 at 18:03 Add a comment  | 
I am using Laravel's file caching system (at least temporarily) to cache numerous smaller, mainly static objects from the database. However, if I use artisan to run some functions (which add/call from the cache) and then try to load a webpage, I get permission errors while trying to access the cache. Same error when done the other way around (view web page and then run artisan). This is because the cache is owned by me when I run an artisan command, but is owned by apache when run through the webpage. I have thought of 2 solutions. One, delete all the cache at the beginning and end of all artisan calls (not ideal, loses most of the performance boosts). Or, run all my artisan commands as the apache user (not convenient, and maybe not even possible). Is there a way to modify the permissions automatically of Laravel's file caching? Or set artisan's caching to use the apache user maybe?
Laravel artisan cache permission issues
you can use .unload() it doesn't specifically intercepts back button but any event that unloads current page. It can be anything clicking on link, forward button or back button based on the browser. $(window).unload( function () { $('#SWITCHING_SCREENS').hide(); }); The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.
I am posting a form at the end of a JQUERY fadeIn. When the user hits submit - a DIV 'SWITCHING_SCREENS' - with a message in it, is faded in via JQUERY and covers the form page. Once that div is fully faded in - javascript then posts the form to another page. Javascript: Theform = document.getElementById('customers_form'); $('#SWITCHING_SCREENS').fadeIn('slow', function(){ Theform.submit(); }); This is all working well, and I have no problem with the submitting or anything else. But on the chance that the user then hits the browser back button (firefox) - the SWITCHING_SCREENS is still visible. I have seen back-button caching of form elements - but expected the JQUERY to reset on back-button. Or I just didn't expect it to cache. It seems as though it has cached? Has the JQUERY cached this state of the DIV? I have tried: Javascript: Theform = document.getElementById('customers_form'); $('#SWITCHING_SCREENS').fadeIn('slow', function(){ Theform.submit(); $('#SWITCHING_SCREENS').hide(); }); and this does remedy the caching of the DIV in the 'fadeIn' state when the browser back-button is used... But it also removes the DIV before the page actually switches to the posted page. I want the div to remain visible while the page is posting to the next page - and to be gone if the visitor hits the back button. This seems to only be happening in Firefox. Thank you. Regards.
JQUERY caching if Back-button after posting to form - JQUERY fadeIn still visable
1 Cache files are not deleted before they expire. Cache files are saved in application/cache folder. you can manually delete it from there. Additionally, you can better manage your cache(programatically), by either adding cache helper or extending your output class with clear page cache Share Improve this answer Follow answered May 31, 2013 at 4:33 sakibmoonsakibmoon 2,03633 gold badges2222 silver badges3232 bronze badges 5 In my Config file I have set: $config['cache_path'] = ''; And I do not have nither a application/cache or system/cache folder. – Martin Overgaard May 31, 2013 at 7:04 Thanks for your suggestions. So I can't delete them, because the folder is not there. As far as I know, the cache helper and extending of the output class with clear page cache will look into the folder, that I don't have. Or am I wrong? Thanks for any help. – Martin Overgaard May 31, 2013 at 7:13 Yes. it would try to delete the file from there. It's odd that you don't have cache folder. Take a look at your config file to see if your $config['cache_path'] has been changed. – sakibmoon May 31, 2013 at 7:16 Thanks. The Config['cache_path'] has not been changed, it is left blank, default pointing to application/cache. – Martin Overgaard May 31, 2013 at 7:42 Thanks. I solved the question by inspecting af following question no. 11745368I. – Martin Overgaard May 31, 2013 at 10:07 Add a comment  | 
After a couple of years with no cache problems in Codeigniter, I discovered one. I have see the problem described other places, but with no solution that works for me. If I for example change some plain html text in a view and upload a new file and press F5 the old cached file is shown. If I afterwards press ctrlF5 the new is shown, and F5 again gives me back the old cached file. I have tried to flush the browser cache manually, but we no effect. After a couple of minutes the old cached file gets replaced with the new one. This issue gives me problems with login and logout. I have without luck placed the following code in both the login and logout controller; $this->output->cache(0); $this->output->set_header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT'); $this->output->set_header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate, post-check=0, pre-check=0'); $this->output->set_header('Pragma: no-cache'); $this->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); I have not activated output cache in any controller ($this->output->cache(n)) or have a cache folder (application/cache or system/cache/(beore 2.0.0)) or use db cache (['cache_on'] = FALSE) in the config file. I am using: Codeigniter 2.0.0 Firefox 21.0 I think that the cache files are stored somewhere on the Linux server, but where and how to flush, I don't know. Any help or pointing in the right direction will be fine. Thx! Best regards Martin
Codeigniter - cache - server?
After thinking about it, in your example, you are updating it regardless, so AddOrGetExisting isn't the best, as you mentioned, you are setting it later anyway. Below it a simple implementation that I think fits what you are asking for. If I am wrong, please let me know! public class MemoryCacheWithEvents { private static MemoryCache _cache = new MemoryCache("myCache"); private static object _syncLock = new object(); public EventHandler<CacheChangeEventArgs> AddingCacheItem; public EventHandler<CacheChangeEventArgs> UpdatingCacheItem; public object GetAndSetExisting(string key, object value, CacheItemPolicy policy, string regionName = null) { lock (_syncLock) { var cacheItem = new CacheItem(key, value, regionName); var existing = _cache.GetCacheItem(key, null); if (existing == null) { OnAddingCacheItem(new CacheChangeEventArgs(null, cacheItem)); } else { OnUpdatingCacheItem(new CacheChangeEventArgs(existing, cacheItem)); } _cache.Set(cacheItem, policy); return existing; } } public virtual void OnAddingCacheItem(CacheChangeEventArgs eventArgs){ var handler = AddingCacheItem; if (handler != null) { handler(this, eventArgs); } } public virtual void OnUpdatingCacheItem(CacheChangeEventArgs eventArgs){ var handler = UpdatingCacheItem; if (handler != null) { handler(this, eventArgs); } } } public class CacheChangeEventArgs : EventArgs { public object OldCacheItem { get; set; } public object NewCacheItem { get; set; } public CacheChangeEventArgs(object oldCacheItem, object newCacheItem) { this.OldCacheItem = oldCacheItem; this.NewCacheItem = newCacheItem; } }
I am using the .NET 4.0 MemoryCache class, and I want to add or replace an existing item in the cache in a thread-safe manner, but I also want to know whether I have replaced an existing item or added a new one. From what I can tell, the Set method is intended for the purpose of atomically replacing an item in the cache if it exists, whereas the AddOrGetExisting method will atomically get me the existing item without replacing it. However, the Set method doesn't return the item that was replaced, it just replaces it. It is possible to hook up a removed event to the CacheItemPolicy for items, but hard to match that up with the new item that replaced it. I can approximate it with the following method, but it seems a bit heavy (because of asking the cache to essentially add an item twice) and I wanted to ask if someone knows an easier way to do it. public object SetAndGetExisting(string key, object value, CacheItemPolicy policy, string regionName = null) { lock (_cacheLock) { var existing = _cache.AddOrGetExisting(key, value, policy, regionName); if (existing != null) { _cache.Set(key, value, policy, regionName); return existing; } return null; } }
MemoryCache.Set return removed cache item
1 From what it looks, this is not caching because the response file has Cache-Control:max-age=0 Share Improve this answer Follow answered Mar 13, 2013 at 20:02 Alon BurgAlon Burg 2,51022 gold badges2727 silver badges3333 bronze badges 1 I wonder if Cache-Control max-stale in the request would suffice to override that: stackoverflow.com/a/11714075/56285 – Jonik Oct 31, 2013 at 16:56 Add a comment  | 
I am trying to cache this file: http://media.admob.com/sdk-core-v40.js with HttpResponseCache. Basically i am calling the getFileFromUrl function two times, so that the first time it gets the resource from the internet and the second time it gets it from the cache. However, for both methods it gives this error: "The resource was not cached!java.io.FileNotFoundException: http://media.admob.com/sdk-core-v40.js". Does this mean that the file was not cached and it can not access it? What is wrong with the code? enableHttpCaching(); getFileFromURL(url); getFileFromURL(url); public static void getFileFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection=(HttpURLConnection)url.openConnection(); connection.setUseCaches(true); connection.addRequestProperty("Cache-Control", "only-if-cached" ); InputStream input = connection.getInputStream(); System.out.println("The resource was cached!"); }catch (FileNotFoundException e) { System.out.println("The resource was not cached!" + e); }catch (IOException e) { e.printStackTrace(); } }
HttpResponseCache does not cache files
Caching Razor/HTML views in ServiceStack is done in the same way as every other format by using ToOptimizedResultUsingCache e.g: public object Any(CachedAllReqstars request) { if (request.Aged <= 0) throw new ArgumentException("Invalid Age"); var cacheKey = typeof(CachedAllReqstars).Name; return RequestContext.ToOptimizedResultUsingCache(Cache, cacheKey, () => new ReqstarsResponse { Aged = request.Aged, Total = Db.GetScalar<int>("select count(*) from Reqstar"), Results = Db.Select<Reqstar>(q => q.Age == request.Aged) }); } This service caches the output of any requested format, inc. HTML Razor Views.
I'm new to Service Stack, just discovered and looks very interesting to use. I'd like my future websites to be quite backbone heavy but still ensure they can mostly be indexed by Google and seen by people with JavaScript (more for Google indexing) I know there is content caching, such as lists etc which can be retrieved and severed the a razor page. But I didn't see any methods of docs covering caching the entire razor page after being rendered, which is what I believe OutputCache attribute does on normal ASP.NET MVC 3. So if anyone could direct me to possible examples of entire razor pages being cached using Service Stack, or a possible method of doing it would be greatly appreciated. Thanks
Is there a method to cache Razor page in Service Stack?
Here is the solution I've used for css files, but should work fine for JS: In the htaccess have a rule: RewriteRule ^(.*)_ver_.*(\..*)$ $1$2 [NC,L] That takes a file name such as "Style_ver_12345.css" and rewrites it to Style.css. Then when when you include the file append the LastWriteTime of the actual file (File.GetLastWriteTime(filePath).Ticks.ToString() is how I do it) as the version number. An example file name that I would have is Style_ver_634909902200823172.css This will ensure that any change in the file will immediately cause a new version number, while the physical files does not need to have a different name, and the file will be cached by the browser. The user would still have to refresh the page, but they wouldn't have to clear their cache. If you needed to, maybe you could force a refresh by having an ajax call that would compare the version number of the script loaded with the version number on the server. A newer version on the server could then force a refresh.
I know this question was asked quite a few times and the most common answers were: Auto versioning using the .htaaccess file. Although this is not at all recommended, using a version number as a query parameter For example: '/scripts/script1?v=1.0.0'. This will cause the browser not to cache the file but does the job. I am handling some post release issues and since we don't follow a software project life cycle as such, we update the site as and when the issues are tested and fixed. So, we may have to update the site several times a day sometimes versus no updates for a week. I am not sure if there is a way I can still take the benefit of caching and at the same time don't need to have the users to refresh the page/clear cache to see latest changes. Is there a way I can implement the .htaaccess solution in asp.net if that's what I need to do? I really appreciate any help.
Javascript and css caching in asp.net
There is JSR-107, standardising a Java Cache API. This was scheduled to be included in Java EE 7, but will not make it in time according to the latest announcements. Anyway, I tried the reference implementation in Dec. 2012, and it worked fine for me after applying two minor pull requests and building it locally. I didn't try it with ehCache, though. There are annotations that work with CDI.
Spring framework has a very nice @Cacheable annotation. Is there a way to reproduce this functionality in a Java EE application by using @Interceptors and ehCache?
@Cacheable in Java EE
1 ActionController::Base.perform_caching = true Rails.cache.clear load 'app/controllers/name_controller.rb' Share Improve this answer Follow answered Apr 22, 2013 at 13:44 Alexander RevutskyAlexander Revutsky 1,32311 gold badge99 silver badges44 bronze badges 1 Is there a way to reload all controllers? Also how would this work for caching in models? – lulalala Apr 25, 2013 at 2:45 Add a comment  | 
I want to control whether to perform caching at runtime. I wrote an admin action like the following to test the idea (trying to set it to true): def togglecache Rails.configuration.action_controller.perform_caching = true render :index end However after setting it, caching is still not taking effect. How to achieve this, if it is possible at all?
How to set perform_caching dynamically in Rails
Interesting question... As a tip, you can use cache_option attribute so you can simply set not to cache you applet as... <html> <head> <title>Test Applet</title> </head> <body> Test applet... <script src="http://www.java.com/js/deployJava.js"></script> <script> var attributes = {code:'Test.class', archive:'aTest.jar', width:10, height:10}; var parameters = {cache_option:'no'}; var version = '1.6'; deployJava.runApplet(attributes, parameters, version); </script> </body> </html> As an additional tip, try to use object tag instead of applet tag with the same parameters as: <PARAM name="cache_option" value="no"> Report if it helped
I have an applet shown in a webpage with <applet code="foo.class"></applet> When i change the foo.class file in the server and access the page, it shows the older version. If I empty both browser and jvm caches, and then reload the page, it shows the current version. How can I tell the browser/jvm that this is another version of the same class? And, if I access the html file locally, without any webserver, it shows always the current version even without cache refresh. What am I missing? update: when loading the applet with js, the generated html is: <applet code="abcSynth.class" archive="miglayout-4.0-swing.jar" height="500" width="800"> <param name="cache_option" value="no"><param name="codebase_lookup" value="false"> Now, I found in java docs that codebase_lookup it's used when the main class is not provided with the .jar archive, just like this case. With false value, it throws ClassNotFoundException, with true value it starts (the old version). The code folder contains main class and other few .class files, the only .jar is the miglayout.jar, but since javadocs says "Typically applets are deployed with all the needed classes and resources stored in the applet JAR files." I wonder if I'm doing something wrong about .class/.jar depolying. SOLVED Thanks it worked! Browser is still holding the older version in cache but after restart it shows the current version! Final code I used is: <object classid="java:myClass.class" type="application/x-java-applet" archive="myJar.jar" height="500" width="800" > <param name="code" value="myClass.class" /> <param name="persistState" value="false" /> <param name="cache_option" value="no"/> <param name="codebase_lookup" value="true"/></object>
Java applet and cache issue
1 i suggest you to search trough your ide in the library for "The session cookie data did not match what was expected. This could be a possible hacking attempt." usually IDE has a ctrl+f find option just search and you'll be able to understand what is causing this message, then if you didn't catched post the code snippet ;) NB : usually if you are using an encryption key for the session in your config.php , and you change that it will throwns exactly the same error, cause the old session has a different encryption key (the old one you used) Share Improve this answer Follow edited Aug 4, 2013 at 9:48 answered Dec 31, 2012 at 21:55 itsmeitsme 49.4k9696 gold badges226226 silver badges349349 bronze badges Add a comment  | 
I am using Phil Sturgeon's cache library -- http://getsparks.org/packages/cache/show. This works nicely - the only thing is that now I notice that each time a cached page is loaded, I get this message in my log: The session cookie data did not match what was expected. This could be a possible hacking attempt. My sessions are stored in the database. Does anyone have any pointer on what I should look into to solve this problem?
CodeIgniter - log error about sessions while using output cache
1 I would say you have look at php application as a web application and implement several levels of caching. IMMUTABLE methods - I don't think is good approach. Usage of caching on db level, application level (memcached) is good start. Then I would suggest caching on view level Smarty caching and caching proxy like Squid or Varnish Share Improve this answer Follow edited Nov 19, 2012 at 13:10 answered Nov 19, 2012 at 13:05 Zdenek MachekZdenek Machek 1,74611 gold badge2020 silver badges3030 bronze badges 2 Ok, thanks I've changed it, editor wasn't doing exactly what I wanted. – Zdenek Machek Nov 19, 2012 at 13:11 I've already implemented caching on the data- and viewlayers with memcached (and additionally an APC opcode-cache). But as the application is using a large library of code that is shared between multiple applications, i'm trying to improve that one. Memcached is perfectly capable of this ofcourse, however i would have to introduce a bit of memcached code into a hundred different methods in order to apply the effect across the board. If it was possible to indicate the volatility of a method instead then the code itself wouldn't need modification and the backend (PHP ext) can do all the work. – Staex Nov 19, 2012 at 13:54 Add a comment  | 
BACKSTORY I maintain a spectrum of (web-)applications that all use a large homegrown PHP library. Some of these applications are traditional desktop applications that are used by employees, but others (which are also more relevant to this question), are PHP websites for which performance is becoming a more important issue as the popularity continues to grow. CURRENT PHP CACHING METHODS To speed up one of our websites (it's a shop, think of it as thinkgeek.com), i employ memcached to cache certain segments of the website that don't require constantly being dynamicly build (such as the product listing for a certain category). We also use a pretty much factory-default installation of APC as an OPCode cache. Both of these methods bring significant improvements to the website's performance, but i'm very much looking to go further down the road of optimisation. Function Volatility in PHP Coming from a Database background myself, i'm very fond of how PostgreSQL for example, uses function volatility to get massive performance gains while maintaining reliable and accurate results. My question is, is there any extension to PHP that allows the developer to mark certain functions (or class methods) as IMMUTABLE? (meaning the result of that function is always the same, when given the same input arguments). This caching extension could then cache the result of that function which should result in massive performance gains when using big libraries of code. A simple example would be a method such as SomeClass::getWebsiteFooter(); which returns some HTML code that's always the same, unless the website has been altered (in which case the cache would be flushed). Does something like this exist ? I haven't been able to find anything remotely similar on the market. Are there any other methods of performance improvement that might benefit my situation ?
PHP performance (Opcode caching / function volatility)
You may use HttpClient Cache. HttpClient Cache provides an HTTP/1.1-compliant caching layer to be used with HttpClient--the Java equivalent of a browser cache.
I have a pretty simple use case: Cache the content of a URL with correct and automatic reloading when the content on the remote side changes (for example when "last modified" changes). How can I do that in Java? Note: I have spring, guava and commons-lang3 on the classpath but I couldn't find any support for this. Guava supports cache eviction but there is no way to implement per-access checks.
Caching content of URL
Try amino cluster, it has support for sticky sessions through amino gateway. https://npmjs.org/package/amino https://npmjs.org/package/amino-gateway
Is it possible to change strategy of assigning worker to request on nodejs cluster? I mean on first client access select worker and later keep client on this worker by session id. I'm using memory cache as a storage for large structure of objects. Every client (session) has own data in this storage. All stored objects are configured and referenced (with cycles). This was solution to complicated serialization to redis/memcached. Now on cluster, every request could be processed by different worker, so data for same session will be created, in worst case, under every worker. Is it about some setting of cluster, or is it possible to write method? which helps select worker for client session. When worker dies, it will select new one and session data will be recreated from permanent storage (mysql).
nodejs cluster - keep client session on one worker
Although it might be a good idea to cache the whole website on the client side there are a lot of things that can cause issues: Memory Unnecessary load on the webserver Loading uneeded pages into memory Some users have a limit to their internet so loading the entire website is not smart in those cases Once the user naviagets away or refreshes the entire "cache" is gone What I would do is first try to optimize the server side. Add a bunch of caching mechanisms from the database to the user, the "Expires" header can really help you. And if that doesn't help I would then think about caching some pages(which ones are for you to decide) in the offline cache, see (HTML 5 Offline Features) That way you are safe even on page reload, keep the memory to a minimum and only load what you need. PS: Don't try to reinvent stuff that the browser already has :P
I'm currently building a portfolio-website for an architect that has a whole lot of images on its pages. Navigation is done with history.js (=AJAX). In order to save loading time and make the whole thing more "snappy", I wrote a script that crawls the page body for links to other pages and fetches these automatically in the background. So far, it works like a charm. It basically keeps a queue-Array that holds all the links. A setTimeout()-Function works through them and fetches each page using jQuery $.ajax(). The resulting HTML is stored in a Javascript Object. Now, here's my question: What are possible problems that might occur when using this on different machines/browsers/operation systems? I'm thinking about: max. javascript object/variable size (The fetched HTML is stored in an javascript object) possible performance problems max. number of asynchronous requests? … anything you can think of? Thanks a lot in advance, a hobby programmer
Preloading (=Caching) a full Website with Ajax – Possible Problems?
This seems to answer all of my questions and provides a more elegant solution than django-nginx-memcache, that is patching the django cache system: http://www.willmcgugan.com/blog/tech/2009/3/1/fast-caching-with-django-and-nginx/ Benchmarks from comment on page: Static content is almost 4x faster than serving from memcache with nginx. Request rate: 6243.8 req/s (0.2 ms/req) (static html) Request rate: 2285.5 req/s (0.4 ms/req) (same html in memcache) I think I'll go with staticgenerator but please feel free to post your thoughts. Edit: I realized that I'm running two webservers in parallel and I would need a way to sync the cached data if I go with staticgenerator. I guess I could fork it and have it write the files on both servers through network. Any thoughts on this?
What I'm doing is avoiding having requests hit Django and serving cached data straight from nginx. Related question: Django staticgenerator vs CACHE_BACKEND There seem to be two choices when it comes to this: https://github.com/torchbox/django-nginx-memcache https://github.com/mrj0/staticgenerator - This one seems easier to use After trying django-nginx-memcache I found some downsides: No fallback to serve cached content from django (can be fixed). nginx has to be recompiled for md5 sum generation of urls (I don't think this can be fixed). Edit: After looking at other solutions (such as: http://soyrex.com/articles/django-nginx-memcached/) I find that there seems no need to use md5 cache_keys. Maybe this should be an option. It would be nice to be able to define a list of url patters that should be cached. So far, only decorators are available (can be fixed). The code should in my opinion be modelled more after the standard django cache backend with UpdateCacheMiddleware and FetchFromCacheMiddleware. This would make it easier to implement nginx cache where standard django cache solutions exist. It would also solve problem #1 (can be fixed). Strange naming of module. While the project is named django-nginx-memcache, the package is named Django-Memcache-for-Nginx and the app nginx_memcache for inclusion in django installed_apps (can be fixed). Which is faster? Which one would you use and why? Should I fix the issues that I have with django-nginx-memcache or is staticgenerator just better anyway?
nginx cache, staticgenerator vs memcached
Please check the version of mysql that you are using. It seems Before MySQL 5.1.17, prepared statements do not use the query cache. http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html It also mentions some conditions under which query cache will not work. I think the alternative to that is to use memcache, but I don't know how good it is. But one thing for sure all these caching methods donot work well if you have frequent updates. You don't really have much control on the cache I guess, it gets invalidated when ever there is an update on actual table(to avoid dirty reads) So I suppose yours is not so frequently updated table while in production. And if that is the case you can very well think of using application level caching with ofcourse cache invalidation service/criteria in place.
I am creating a java desktop application. I am using mysql database as back end. In my application some query was get executed more than one time, so i want to cache the query result and use it for the next time. For caching i try prepared statement but i don't get any positive result. Is any other way to cache the query and query result set?
Cache database query and result set
And the answer is... mysql executes the calculation once per row. Due to lack of credible answers, I ran a definitive test on sqlfiddle that orders by the result of a not deterministic function (that must be called every time it's compared) that also records in another table when it has been called. It shows that the number of times called = number of rows.
Suppose we have a query that orders by a calculated value that is not selected, for example: select * from table order by col1 * col2 - col3 During typical sorting operations in most languages, it is common for the sort value to be used multiple times during the sort, as a given record is compared to potentially many other records. It is possible that mysql has such an implementation. Can anyone say definitively if mysql calculates such values once per row and stores them temporarily while the sort completes, or if the values are recalculated whenever a comparison is made (which may be 1-n times)? I have tagged this mysql, but I would welcome comments/answers regarding/including other popular databases
Are calculated values used in ORDER BY ever recalculated during sorting?
The new Appfabric 1.1 has read-through and write-behind features which has guaranteed persistence of your cache. Read through - If a requested item doesn't exist in the cache, the data can be loaded from backend store and then inserted into cache. With a read-through provider, the cache detects the missing item and calls the provider to perform the data load. The item is then seamlessly returned to the cache client. Write behind - In the same way, items that are added or updated in the cache can be periodically written to the backend store using a write-through provider. This happens asynchronously and on an interval defined by the cache. You can check out my blog post for implementation details here http://blogs.msdn.com/b/prathul/archive/2011/12/06/appfabric-cache-read-from-amp-write-to-database-read-through-write-behind.aspx
I have some objects and classes that I'm currently saving into HttpContext.Cache but I want to make these persistent even when the app pool is recycled or even when the machine has been restarted. I tried looking into using AppFabric or Memcached but they seemed focused on distributed cache and not so much local cache. Also the EF STE in combination with AppFabric seem to be depending on serializable classes and some properties in my classes is for example references to .NET classes that is not serializable (For example I have a reference to an instance of System.Net.WebSockets.WebSocket as a property). So my question is: Can anyone give me any good ideas or point me to a framework that will allow me to save classes into some sort of local cache that is persistent to disk (Or database if it will allow me to save anyhting into it)?
What framework should I use to get a persistent cache?
1 Have you looked into Redis? Its fast, and plays well with Python. Also, what about multiple threads/processes that are initiated at a fork to do the searching faster? redis-py Share Improve this answer Follow answered Aug 2, 2012 at 17:34 reptilicusreptilicus 10.4k66 gold badges5757 silver badges7979 bronze badges 4 Redis: Looks like a database solution. I'm familiar with SQLite and use that frequently, but I don't need any persistence when the application is closed, only during. An example would be if a user looked at the disk space for /path/to/sub/subsub and then afterwards looked at /path/to/sub, subsub would have already been calculated so it would only need to find the rest. Going deeper after a broad result would not need to find anything, cause it'd all be cached. – STH Aug 2, 2012 at 17:55 Threads: Would this actually be faster? I can test it myself, but wouldn't the GIL cause this to not have a big improvement? Also, it wouldn't solve the problem of saving the results in an efficient manner to read later. – STH Aug 2, 2012 at 17:58 I'm not well versed in threading so I won't comment there, but multiprocessing is NOT affected by the GIL. If you have a multicore machine you could probably speed it up by spawning multiple processes. I'm just not sure about the same thing with threads. – reptilicus Aug 3, 2012 at 18:14 As for redis, you can cache anything you want to memory as far as I know, and delete the keys when you are done with the program to release the memory. It is often used with database applications to speed up common queries, which would take a long time if the database was getting hit. It acts somewhat like a database, but things are stored directly in memory instead of on disk. – reptilicus Aug 3, 2012 at 18:18 Add a comment  | 
I'm writing a disk space usage program in Python and I already have the functionality I want, but it is slow. The filesystems I will be analyzing can be hundreds of GBs, with thousands of files in many depth-heavy folders. I am showing the data with a Tree Map based off of the "Split" layout in the paper linked ahead. The creation and solving of the layout are both very fast operations. http://www.nada.kth.se/utbildning/grukth/exjobb/rapportlistor/2005/rapporter05/engdahl_bjorn_05033.pdf I am walking the given path with os.walk and adding the folders and files to this Tree Map along with their sizes. I get the size of every file and that is stored in a dictionary cache (where cache[filePath] = size) so I can easily retrieve it again. All of this is quick, except for os.walk. Running os.walk alone can take 30+ seconds, sometimes minutes. I understand that I can't make it walk the structure any faster, but I would like to cache the results somehow so that in the future it is much faster. This is because the application allows navigation the tree map, where you can click on any section (which is a folder) and it will make that the 'root' of the tree map. So, I am in need of a caching solution that would allow easy access to any file/folder, along with easy navigation in the hierarchy, so that if I started on the 'root' node, I could jump down to any specified child in any depth, and then from there I could move up (or down) in the structure. I would rather not incorporate the data structure and navigation into the tree map. It would be best if the solution was in the walking and sizing part of the program. In the end, I really only need a walkable recreation of the file/folder structure with their sizes. Any good libraries for this kind of structure? Or how easy would it be to write this myself? I haven't used a structure like this before, so I don't know the best way to create it so that I have the type of access I need.
Python efficient structure for caching folders, files, and sizes
1 If you are using require.js, then you have to set the "bust" urlArgs befre using the require object. Like so: <script> var require = { urlArgs : "bust=" + releaseVersion }; </script> I was in a similar situation for CSS and images. If your web app is behind Apache, you can set the cache-control header to http response in the mod_headers module. In my case, my web app is not behind Apache. I directly hit Glassfish. So I ended up adding a Servlet filter and manually added the cache-control header to each CSS and image response before forwarding it to the filter chain. After that, when ever there is a CSS change, I just add a url parameter in the HTML like so: <... "main.css?version=release10" /> The browser sees this URL change and fetches the CSS from server. The same goes for images. For JS you have to update the "Bust" value. Share Improve this answer Follow answered Oct 19, 2012 at 18:55 motivermotiver 2,29244 gold badges1919 silver badges2020 bronze badges Add a comment  | 
I have a web app that uses require.js throughout (apart from a couple of CDN provided resources). I am using the optimize tool to create a 'published' site. My concern is that when a new version of the web app is published users will not get updated js files, as they will be cached by the browser. The problem is very evident when developing the app unless the 'urlArgs' config option is used. The usual solution is to append a querystring of ?v=1.0 to the script references, but as they are all handled via require.js there is no way of doing this. So, my question is how can I ensure clients download new versions of the js/css files when a new version is published?
Cache busting a web site optimized by Require.js
To avoid this issue ehcache web caching can be used: http://www.ehcache.org/documentation/user-guide/web-caching It works by simply adding filter to web.xml and provides caching of HTTP responses. <filter> <filter-name>SimpleCachingHeadersPageCachingFilter</filter-name> <filter-class>net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilter </filter-class> <init-param> <param-name>suppressStackTrace</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>cacheName</param-name> <param-value>CachedPage2Cache</param-value> </init-param> </filter> <filter-mapping> <filter-name>SimpleCachingHeadersPageCachingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
lets say I have two methods in my controller to support both json and xml. @RequestMapping(value = "/get/response.json", method = RequestMethod.GET) @Cacheable(JSON_CACHE) public @ResponseBody JSONResponse getJsonResponse(){ return responseService.getJsonResponse(); } @RequestMapping(value = "/get/response.xml", method = RequestMethod.GET) @Cacheable(XML_CACHE) public @ResponseBody XMLResponse getXmlResponse(){ return responseService.getXmlResponse(); } And two message converters, marshalling my objects into suitable response. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonConverter"/> <ref bean="xmlConverter" /> </list> </property> </bean> The problem is that Spring 3.1, even though method is annotated with @Cachable, still invokes marshaller for every call. It caches state of the object before marshalling. This is not acceptable because performance is crucial here and marshalling is too expensive for me. I expected Spring to cache the final response in such case. Am I doing something wrong here?
Why Spring message converters still being invoked in @Cachable methods
Your browser is keeping the javascript compiled by GWT for you application in cache. Easy solution, do a hard refresh of your page a couple of times (ctrl + F5, or cmd + shift + R). If you want to prevent this, see this question
I am using AppEngine with Restlet to serve my data to a GWT app in the browser as client. The Restlet-GWT edition uses GWT-RPC serialization as the transport format underneath. GWT-RPC serialization relies on the shared source between client and server to serialize/deserialize. Now, after adding a new property to one of the shared source classes, de-serialization started failing. The AppEngine server processed the request correctly with response HTTP 200 / OK and was sending out a correctly serialized object. The client choked each time. After awhile I figured out that the browser was trying to deserialize a cached copy of my object (without the newly added property) and so de-serialization in the browswer failed. Now the question : why is the browser using a cached copy if the server is being hit anyhow ? IMO, this defeats the purpose/advantages of caching, the server and network resources are being consumed and the fresh result is not used ? In case the browswer decides to use a cached copy, I would expect no round-trip to the server. thx !
After hitting the server, browser still uses a cached version
1 From the cache sweeper docs: Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change. They do this by being half-observers, half-filters and implementing callbacks for both roles. Sweeper uses controller to expire cache, to get caching settings, etc. Take a look at the source code. So, cache sweepers allow us to control cache from the controller side. And I think this is good, because we can expire cache on any event - change in the DB or user sign in, or anything else. I think, if you don't want to call cache_sweeper method in the controllers, you can define controller method in your sweeper. I didn't test following code, but it should work, because I do the same thing in my sweeper specs. class MySweeper < ActionController::Caching::Sweeper observe MyModel def after_update(my_model) expire_page(...) end def controller @controller ||= ActionController::Base.new end end Share Improve this answer Follow answered May 9, 2012 at 21:57 cutalioncutalion 4,36411 gold badge3939 silver badges4848 bronze badges 3 1 what does observe MyModel do? – John Bachir May 10, 2012 at 1:48 it tells MySweeper to observe MyModel :) api.rubyonrails.org/classes/ActiveModel/… – cutalion May 10, 2012 at 10:29 1 what does that mean, in this case? – John Bachir May 10, 2012 at 17:06 Add a comment  | 
A cache sweeper is an observer with some hooks on the model it is observing: class MySweeper < ActionController::Caching::Sweeper observe MyModel def after_update(my_model) expire_page(...) end end But documentation and guides also say to declare the sweeper in the controller: class ApplicationController < ActionController::Base cache_sweeper :my_sweeper end Why is this? Isn't the point of an observer that it observers the model and takes action? Shouldn't the controller not have to be aware of when the cache is expiring or what is causing it? clarification my understanding of setting up the sweeper to be an observer is that it means "in all cases, when a MyModel is updated, run this cleanup code" Is that accurate? If so, then why does cache_sweeper :my_sweeper also need to be declared in a controller? What does that do?
Why do cache sweepers need to be declared in controllers?
Setting the expiration date to the current date/time forced it to always check with the server. Response.Cache.SetExpires(DateTime.Now);
I am using the code from this article: http://weblogs.asp.net/jeff/archive/2009/07/01/304-your-images-from-a-database.aspx to cache the images I am returning from the database but I am having a problem when the user changes the image the browser is not going back to the server to check the timestamp. I have tested this in Chrome and IE9 and chrome almost always goes back to the server to check the timestamp and if it has been edited it returns the new image, IE9 never does unless I ctrl+F5 to refresh the page. Is there a cross browser solution that anyone knows of to make sure the browser always makes a call to the server so I can check the timestamp? Many thanks for any help.
Asp.NET MVC Caching Images
1 Well the most reliable way to do that it to tell the browser to reload all the css and javascript resources afresh ignoring the cache and in order to do this you should change the names of your css and javascript resources so that browser knows that it needs to reload them. Though it might be tedious/impractical task for you to rename all the css and javascript resources every time you deploy a new build on production, you can use the ui-performance-plugin for this purpose. It plugin, if configured correctly, makes sure when ever you create a new war it will append the current revision number from the repository to the file name and hence file names are changed. Limitation with this will be you will have to update all the references to your css and javascript files in gsp's to include them using the plugin's tablib rather than directly (so that while renaming the files it also replaces the corresponding references in the gsp files). Also, this plugin can provide you a number of other features which might help you increasing the speed of web application. For more detailed features of plugin click here Hope that helps. Share Improve this answer Follow answered Apr 8, 2012 at 23:49 BagiraBagira 2,21155 gold badges2929 silver badges6060 bronze badges Add a comment  | 
I'm running a website using Grails on a Tomcat server. When I update the website pages, Firefox applies the updates correctly, but Internet Explorer seems to keep the cached values until I explicitly delete the temporary internet files. How do I make sure Internet Explorer users have the up-to-date web pages when the site gets updated? Edit: I tested on Internet Explorer 9, but I assume previous versions have the same issue. Edit 2: The problem is only happening with css and javascript includes.
Ensure web site cache is cleared on Internet Explorer when site is updated
If you mean "with the same key", then use the indexer: cache[key] = value; If you mean with different keys, then: no
I'd like to know if I can implement a method on MemoryCache that removes an item from it and add a new one before any other thread tries to reach it. I can't seem to find anything that would let me control the lock(maybe for a good reason) so I can perform these two operations at once.
Can I add an atomic operation to MemoryCache?
theres an easy little trick you can use for this. just append a random string to the end of the image file source like a $_GET parameter. better than a random string is a timestamp, since your won't risk using the same number twice. use it like this in your img tag src='img.jpg?rand=1234'
I've a php page with some forms used to upload images. Each form upload one image. Uploaded images replace images yet loaded in the page. Here is a snippet: <?php // NO CACHING CODE header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // FORM SUBMIT CODE if (isset($_POST['submit_img1'])) { // used for some photo manipulation and checks require_once('WideImage/WideImage.php'); //... some code ... unlink("path/" . $img1); $img_name = "path/" . $img1; $wideImage->saveToFile($img_name, 80); // ... some code ... } // PRINT IMAGE IN THE PAGE echo '<p><img src="path/' . $img1 . '" width="100" height="100" class="prof_img" /></p>'; ?> //FORM FOR CHANGE THE IMAGE <form id="form_img1" name="form_img1" method="post" onSubmit="return checkFormImg1()" action="" enctype="multipart/form-data"> <input class="prof_input" type="file" name="img1" id="img1" /> <input name="submit_img1" type="submit" class="prof_submit" value="Inserisci Immagine 1" /> </form> The problem is that on reload (after submit button is pressed) the old images are displayed. But the new images have been properly uploaded replacing the old ones. Excuse my english.
Problems with no caching solutions and images
1 What we did eventually is what most websites including SO does: cache the page with ZERO info about current user. Using AJAX, get who's the current user and manipulate the page according to them. Example: follow/unfollow button on a member profile. Render the cached page with no logic of who's the current user implemented. Once the page loads, hit the server with an AJAX checking whether the current user is following or not and accordingly change the button state. Share Improve this answer Follow answered Apr 2, 2012 at 20:42 KorayemKorayem 12.3k55 gold badges7070 silver badges5757 bronze badges Add a comment  | 
I did a GetVaryByCustomString that returns: context.User.Identity.IsAuthenticated.ToString(); But I have a big problem, imagine this flow: The user(or anyone) access the home page. GetVaryByCustomString will return "false" and cache that. Every time that somebody ask if home page changed, will return 304. I login at site and go to Home Page, GetVaryByCustomString returns "true" then cache isn´t used. Every time that I go to Home Page, ASP.NET returns me 304. I logout, and go to Home Page, now GetVaryByCustomString returns 304, because of step one, but the OutputCache don´t know that the cache that I have, is from logged user. If I press Ctrl+F5, it works, since that the problem is in browser/server, the server side cache is OK. But it return 304, and I have a logged page cached. There is any solution? Or do I need to stop caching authenticated users? UPDATE: I think that cache for mutable values just doesn´t work. It need that browsers do they cache by this values too....And don´t exists Vary by Cookies...
OutputCache by user. Bug when I logout
1 You can use Redis as a database for this. It is very very fast, does queuing amazingly well, and it can save its state to disk in a few manners, depending on the fault tolerance level you want. being an external process, you might not need to have it use a very strict saving policy, since if your program crashes, everything is saved externally. see here http://redis.io/documentation , and if you want more detailed info on how to do this in redis, I'd be glad to elaborate. Share Improve this answer Follow answered Mar 10, 2012 at 18:28 Not_a_GolferNot_a_Golfer 48k1414 gold badges128128 silver badges9292 bronze badges 1 2 Thank you for your opinion and sorry for the late answer. I was looking at your proposed solution but I finally realized I wanted something more standard. I mean using preferably Python standard modules because of portability of the application. I ended up using sqlite and I'm pretty satisfied with this. I just had to set some PRAGMA settings (such as synchronous to OFF or journal_mode to OFF) to improve database performance. – samuelg0rd0n Apr 10, 2012 at 9:23 Add a comment  | 
I am creating an application (app A) in Python that listens on a port, receives NetFlow records, encapsulates them and securely sends them to another application (app B). App A also checks if the record was successfully sent. If not, it has to be saved. App A waits few seconds and then tries to send it again etc. This is the important part. If the sending was unsuccessful, records must be stored, but meanwhile many more records can arrive and they need to be stored too. The ideal way to do that is a queue. However I need this queue to be in file (on the disk). I found for example this code http://code.activestate.com/recipes/576642/ but it "On open, loads full file into memory" and that's exactly what I want to avoid. I must assume that this file with records will have up to couple of GBs. So my question is, what would you recommend to store these records in? It needs to handle a lot of data, on the other hand it would be great if it wasn't too slow because during normal activity only one record is saved at a time and it's read and removed immediately. So the basic state is an empty queue. And it should be thread safe. Should I use a database (dbm, sqlite3..) or something like pickle, shelve or something else? I am a little consfused in this... thank you.
Python: file-based thread-safe queue
1 There is no built-in support for retrieving all named regions within cache. We can only get list of system (default) regions using DataCache.GetSystemRegions method. The only workaround I can think of is to maintain list of names of cache's named regions in cache itself. Share Improve this answer Follow answered Mar 17, 2014 at 8:49 Eugene D. GubenkovEugene D. Gubenkov 5,19766 gold badges3939 silver badges7272 bronze badges Add a comment  | 
I'm trying to create a monitoring tool for the appfabric cache servers. These servers accept "Put" and "Get" calls from multiple enrironments, each to it's own distinct "named" Region.(In order for data not to get mixed between environments like QA/DEV/PROD and lots more) The tool should give me at least a clue of how many and what "named" regions are active. from the appfabric cache servers point of view I have no clue what named regions are there and therefore I'm stuck foreach (string regionName in dataCache.GetSystemRegions()) gives me just the defauld unnamed regions which are now empty....
DataCache get all named regions
1 You're looking for an ActionController Sweeper. You can find the official Rails documentation on how to implement them here, but likely you want something like this: class MyModelSweeper < ActionController::Caching::Sweeper observe MyModel def after_update(my_model) expire_action :controller => :my_models, :action => :show, :id => my_model end end Share Improve this answer Follow answered Feb 28, 2012 at 16:41 VeraticusVeraticus 16k33 gold badges4242 silver badges4545 bronze badges 4 My understanding is Sweepers hook into a controller action, and this wouldn't work because the model isn't updated as part of an action. Is that not true? – phillee Feb 28, 2012 at 19:54 Sweepers observe models but also are hooked into controllers (allowing you to expire pages, for example). By doing observe MyModel the sweeper will watch for changes on the model, and then can expire pages based on those changes, all outside the response stack. – Veraticus Feb 28, 2012 at 20:04 So if the rails server is running, it will detect changes in the model that's done by a separate offline rake task? – phillee Feb 29, 2012 at 0:10 No, the rake task will perform the changes itself. Because of this you'll need to run the task on the server that Rails is running on, so that it can correctly access the same cache. – Veraticus Feb 29, 2012 at 0:14 Add a comment  | 
I have an offline rake job that updates my models. When that happens, I want to expire the :show action for that model. # in lib/models/my_model.rb after_update :expire_cache def expire_cache expire_action :controller => :my_models, :action => :show, :id => self end This doesn't work because expire_action isn't available in the model. Calling ActionController.new.expire_action gives me a lot of weird route issues, which is reasonable since none of the route logic is hooked up. I think the common way to expire_action is with a sweeper, but that doesn't work because my model is not updated through controller actions. NOTE: I feel like I may be using caching the wrong way since I can't find an answer to this anywhere.
expire_action from model
1 usually there is none detection. when you enter a page, new request is done (REST) and most recent data for that page are displayed. google says 'about x results in total'. if you really insist on having the counter fixed, you have to stop calling your service 'a rest', take a snapshot from the first search and display disabled entries when user browse pages Share Improve this answer Follow answered Mar 12, 2014 at 0:52 piotrekpiotrek 14.3k1414 gold badges8585 silver badges173173 bronze badges Add a comment  | 
Let's say we have a REST API for search: /items?querystring=foo&pagesize=20&page=3 As the search results are fetched page after page, the search total results might change and items of each page might vary while browsing through pages. What kind of approaches there are to detect changes in data? Total number of result is one indication but not really fool proof.
How to detect stale data in search result with paging?
1 I have been using direct memory in production for a few years. It was first introduced in Java 1.4 in 2002. I have also been using memory mapped files more recently to support shared memory between processes and data sizes much larger than the swap space. Direct memory is often more limited to the physical memory size as many systems don't have much swap space these days. The underlying calls used are very old and use in most C and C++ applications, possibly dating back as far as the 70's. I didn't know there was a direct memory mailing list. I couldn't find it using google. Perhaps its hard to find so that why people don't use it so much. Share Improve this answer Follow answered Jan 20, 2012 at 8:00 Peter LawreyPeter Lawrey 529k8181 gold badges762762 silver badges1.1k1.1k bronze badges 2 I think the OP's talking about this particular incubating Apache project which uses what you're talking about and has a mailing-list – Grooveek Jan 20, 2012 at 8:40 In that case, I would ask the question on the mailing list for that product. The fact its still in the incubator section and is version 0.5.5-SNAPSHOT suggests its not quite production ready. – Peter Lawrey Jan 20, 2012 at 9:08 Add a comment  | 
DirectMemory seems to be the only open source off-heap cache for Java. Is it ready for production? Is it an active, viable project? I looked at its mailing list archive and it's very low volume.
Is off-heap cache DirectMemory ready for production? Is it active?
Assuming there's a set value of things you're caching and that they come from a table, use not exists: select v.e from vals v where v.fk = x and v.e in (a,b,c) and not exists ( select 1 from cache c where c.fk = v.fk and c.e = v.e ) If you don't have a table of available values and are just throwing some set back, you'd go with a dynamic table, like this: select v.e from ( select a as e union all select b as e union all select c as e ) v where not exists ( select 1 from cache c where c.fk = x and c.e = v.e )
I have a table in SQlite that I'm using to cache some data. I'm totally hung up on writing an SQL query that when given a list of x strings will return a subset y that are not in the table. I understand I could just query one by one and check for an empty result but I'd like to know if there's a way to do this that returns a nice, neat list of the strings not cached (not in the table). FWIW I'm using sqlite3 and Python. The query I've got so far is something like select e from cache where cache.fk = x and e in (a, b, c); which is close but gives the opposite behavior from what I want (it returns values that would be a cache hit). I also understand that in this case it is slightly inappropriate to use a relational database over a key/value store but even if I were to switch away I'm still interested in seeing how this would be done.
How can I get cache misses in an SQL query?
Different caches for different caching policies. You may want to cache small, static bits of data for a long time, in memory. Where as larger objects may have a shorter lifespan to limit memory overhead, maybe even caching to disk locally if fetching the data takes more time than reading from disk. I believe EhCache is the interface you should program against, where as Cache happens to be an implementation of EhCache. For me, I pronounce it E H Cache. Say the letters. By no means an definitive answer. :)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago. New to caching in general and am enjoying the EhCache (2.4) User's Manual (I couldn't find 2.5). Right off the bat there are some fundamental concepts that I'm just not finding the answer to anywhere in the manual or their website. Why should there ever be any more than 1 cache for an application? Are cache's like log4j loggers, where each class in your application should get its own logger? Using EhCache lingo, what's the difference between a Cache (<cache>), and an Ehcache (<ehcache>)? Here's a fun one: how do you pronounce EhCache?!? "Ay-cache"? "Ee-cache"? Thanks in advance!
EhCache: Cache Architecture [closed]
1 This is available with the Azure Cache (Preview) release that is part of Azure SDK 1.7 You can look at my blog for more info: http://blogs.msdn.com/b/jagan_peri/archive/2012/08/23/custom-serializer.aspx Jagan Peri - Microsoft Share Improve this answer Follow answered Aug 24, 2012 at 4:55 Jagan PeriJagan Peri 1111 bronze badge Add a comment  | 
The documentation on MSDN says you can inherit from the IDataCacheObjectSerializer interface and update the configuration used to use custom serialization. I can't find the IDataCacheObjectSerializer or the SerializationProperties element of the Configuration class in any DLL I've looked at, has anybody found these? Which version of the SDK are you using? Thanks
Using a custom cache serializer with Azure App Fabric
Yes in general though it can depend on how one handles the caching. First, you should move that tracking stuff to where it belongs -- a HttpModule. Page need not concern itself. Second, what you probably want to look into is some sort of fire and forget service call or message queueing. This makes the database write a non-blocking operation rather than a blocking operation. Some options for making the operation non-blocking: if you are actually writing to a web service, there is an underappreciated [OperationContract(IsOneWay = true)] decoration. Tells the generated proxy to fire and forget the call, will not wait for a response. Another option would be to use the Asynchronous ADO.NET bits, especially BeginExecuteNonQuery. If you don't handle the callback this should just execute off your thread. You could always just spawn a thread and deal with it in a non-blocking manner yourself. Just be real careful about handling errors on this thread -- unhandled exceptions will take out the app domain.
Is it possible to cache a page render on an iis web server, but still receive and write query string values (that don't affect output) to the database? So that the page render does not have to wait for the database trip to execute in order to serve the page? If possible, how do I implement? For example, we track various affiliate and search marketing data via query strings, and in the master page code behind, we write the given query string data to the database. The output of the page doesn't change at all for the user (however we may set a cookie based off the qs parameter). My understanding is that the page render has to wait for the database trip to fully execute in order to render the page. Is that even true?
.NET page caching but still receive query string
1 For some reason I've never trusted the way ASP.NET handles cache using markup settings or using "injected" server tags on the aspx files. I know it works but it's only easy to control on simple scenarios. I always implement cache control, when using user controls, at code behind level and taking into consideration that page life cycle that may have some catches base on the level of controls I have a certain page. We can have: ascx > aspx or ascx > aspx > master. In your case you need to guarantee that CurrentUser is set prior to the load of your user control. Check that using debug. Share Improve this answer Follow edited Nov 24, 2011 at 18:49 answered Nov 22, 2011 at 11:18 Rui MarquesRui Marques 3,45711 gold badge2222 silver badges2626 bronze badges 1 If solved please mark as the right answer. Glad I could help. – Rui Marques Nov 24, 2011 at 18:52 Add a comment  | 
I have a user control in my asp.net application that load it's data from cache. i want it's cache be updated when the value of a variable be changed so i put this code on page directive <%@ OutputCache Duration="1000" VaryByParam="none" VaryByControl="visitIsAu" %> it works fine when i change the value of variable in markup like this visitIsAu="true" but it doesn't work when the value is changed through code behind like this visitIsAu="<%=this.CurentUser.IsAuthorizedToVisitFiltered%>" the value of variable does not change so its cache is not updated. does anyone know why this happen?
using Caching in user control and VaryByControl
The Ehcache documentation on web caching should be a good start. For a quick start they also have a code sample / recipe on that. EDIT: (how to see if it's working) enable logging for package net.sf.ehcache.constructs.web.filter (e.g. DEBUG level) and look at the log entries SimplePageCachingFilter is gzipping the response; look for Content-Encoding: gzip in HTTP response headers - Content-Length should be smaller than before ehcache.xml: configure cache to overflowToDisk="true" and set <diskStore path="target/ehcache-diskStore"/> - a (at first empty) file named SimplePageCachingFilter.data should have been created there JMX / cache statistics (more complicated; see JMX-Tutorial) ...
I am trying to make my web application faster by using caching of web pages for faster access next time so can anyone provide me guideline how to use Ehcache for the same?
Web page caching using Ehcache
1 A good article on asp.net sessions from wcf I don't have any problems with System.Web.HttpRuntime.Cache in WCF (I am only hosting the WCF in IIS - for sure). MemCache is very popular otherwise. Share Improve this answer Follow answered Nov 1, 2011 at 12:59 Neil ThompsonNeil Thompson 6,37622 gold badges3131 silver badges5555 bronze badges 2 Hi Neil and thank's for your answer, the problème with the asp.net session from wcf is that ower WCF service is a REST service, wich means I think that there is no cookies communicated to the service by its clients? and the second problem is that wcf service client is a JQuery client. – Samir Chakour Nov 2, 2011 at 9:48 "AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script." - stackoverflow.com/questions/2870371/… – Neil Thompson Nov 3, 2011 at 19:01 Add a comment  | 
We are developing an ASP.NET web application, this application will generate pages base on meta data (automatic page and controls generation), after this generation a javascript framework will load data for every control found on the generated page by invoking the WCF Rest service my first question is : is it possible to share session data between the ASP.NET web application and WCF Rest service and how to do that? for the first uses we will deploy the ASP.NET web application and its service on the same machin to reduce complexity my second question is : wich cache-framework you recommend to cache data on the WCF Rest services? we will not cache the output responses of the wcf service instead we will cache the modified user data on the service to simulate a user session I would appreciate any help on how to deal with this problem Thanks in advance Regards
how to cache data on wcf rest service depending on ASP.NET Membership token
I've had confirmation from Apple that there is no way to do this at all without a complete reset/wipe of the iPad between 'events'. I logged Bug ID# 10328043 and in the reply was told that they already knew about this 'problem' as the original bug ID # is 5389647 If anyone else would like to help raise this as an issue requiring a sooner rather than never solution, please bug it and reference the two above ID's. Thanks
I am using the iOS MFMailComposeView method of sending emails - its all working fine, except that as a Kiosk app, I don't want each new user to see the auto complete list of previous email addresses that this app / iPad has used. Is there a programmatical way to clear that cache after each email has been sent? I can't see from the Dev docs, but I'm sure I'm not the only one that's butted up against this problem. Thanks
iOS Kiosk App - In-App Email - Clear past / autocomplete email addresses
1 The reason you are having trouble finding these answers is because the traditional protocols were not defined for hierarchical cache architectures so the MESI protocol by itself doesn't define what will happen when you have an L1 and an L2 cache. It depends on three other system attributes. If the L2 is designed to be exclusive of the L1 (i.e., it is guaranteed that L2 and L1 can never have common cache lines), then any line in the L1 will be invalid state (basically not present) in the L2. If the L2 is inclusive of the L1, i.e., every line in the L1 must have an entry in the L2 as well, the entry in the L2 will contain a descriptor stating which L1 cache has the line in E state. Whether or not the value is written out to L2 or memory on a read from E or W stage depends on whether your system supports cache-to-cache transfers or not. In old day, when each chip was a single core, and core-to-core communication was as expensive as read/write to memory, systems would write the data to memory and make the other processor read it (this allowed them to not support cache-to-cache transfers). In multi-core, talking via memory is insanely expensive compared to talking to other cores on-chip, so almost all multi-core chips today support cache-to-cache transfer. Thus, a read from E or W stage is not serviced by writing to memory. I hope this helps. Share Improve this answer Follow answered Nov 8, 2011 at 19:53 Aater SulemanAater Suleman 2,3041818 silver badges1111 bronze badges Add a comment  | 
The details of the MESI protocol for multicore processors would be really important for me, but I can't find them anywhere. Even http://www.intel.com/content/dam/doc/manual/64-ia-32-architectures-software-developer-vol-3a-part-1-manual.pdf doesn't contain enough detail. For instance: assume a private L1 and shared L2 cache. If the state of a line is exclusive in L1, then is it exclusive in L2 too (or invalid, because only in one cache could be the state of a line exclusive)? And clearly, if another core writes this line, the state of the previously exclusive line in L1 becomes invalid, but how is changing the state of the L2 cache line? If a modified line in L1 is read by another core, will be the new state of that line shared and is it written back to the main memory through the L2 cache, or stay modified in L2 too? etc.
details of MESI protocol for multicore processors
1 Indeed the performance gain become less and less significant after 64KB of cache size. Here is graph from wikipedia showing that regardless of the scheme of set-associativity the miss-rate decrease only slightly as the cache size increases pass 64KB Share Improve this answer Follow answered May 5, 2015 at 5:19 IliassIliass 53722 gold badges66 silver badges1313 bronze badges Add a comment  | 
I knew that cache memory stores the frequently used data to speed up process execution instead fetching them from main memory -which is slower- every time , and it's size always small in comparison with main memory because it's expensive technology and because always the real data are being processed at a time is very smaller than the whole data process held by main memory . But is there any limitations or constrains regarding cache memory size at a some CPU speed or a some main memory size ? theoretically , if we increased the cache memory much .. will that affect in an opposite way ? or just it will be a waste increase ?
cache memory size limitations
What you really need is to be reminded at specific intervals to refresh the Appfabric cache items. You could try using the AppFabric cache in conjunction with the Caching block from the Microsoft Enterprise Library. The caching block provides you with the ability to be notified when the item is about to expire. This though will create two caches. Store an object identifier in the cache provided by the application block with the necessary timeout interval, while you can "Put" the actual data in the AppFabric cache without a timeout interval. Use the "Put" instead of the "Add" to ensure that you replace the object if it exists else create it.
I have enabled notification on AppFabric and I'm trying to get notified when an item is removed from the cache after the timeout specified during the Add. Ex : TimeSpan timeout = new TimeSpan(0,0,10); m_cache.Add(OrderId.Text, order, timeout); m_cache.AddItemLevelCallback(OrderId.Text,DataCacheOperations.RemoveItem,myCacheLvlDelegate); I put a breakpoint in the "myCacheLvlDelegate" method but it is never reached even after the 10s timeout (test). For test purpose, I have called explicitly m_cache.Remove(OrderId.Text); after and then the delegate was called ! So the delegate method is only called if I explicitly call the Remove function but not if the timeout expire... Do you have a solution to get notify after the timeout (the one specified during the add) ? I need it because I would like to call a webservice after the timeout to refresh data and cache the result again. Thank you, Fabrice
AppFabric Notification on timeout
1 I would recommend looking through this post on caching in Rails, it's a tremendously thorough post that goes through various strategies that may provide the outcome that you're looking for in this situation. Though he doesn't mention it in the post, adding some sort of cache busting parameter (like a cache version id) to the arguments list might provide you with a way to expire the cache in a more universal way. For example: cache(:version => Posts.cache_version, :direction => params[:direction], :sort => params[:sort], :page => params[:page]) do # Later on to bust the cache Posts.cache_version = 2 The details of how you would want to implement cache_version and cache_version= could vary depending on how you're handling other data in the application. There may also be a more elegant solution than this, but it's what came to mind. Share Improve this answer Follow answered Nov 18, 2012 at 5:23 joshhepworthjoshhepworth 3,03611 gold badge1616 silver badges1818 bronze badges Add a comment  | 
I have a page where on the where the index action shows a list of Posts, with custom sort columns, pagination, etc. Although I can cache every individual page / sort option with cache(:direction => params[:direction], :sort => params[:sort], :page => params[:page]) do I can't expire all of these at once using a single call to expire_action (which is a problem). I know expire_action has a regex option, but that is messy (using a regex to search for keys created with a hash), and I am using memcached which will not work. How can I expire all the cache members of an action with a single call to expire_action? If this is not possible, are there any other caching options you could recommend?
Rails 3.1 wildcard expire cache for action with query string
The have_query_cache server system variable indicates whether the query cache is available: mysql> SHOW VARIABLES LIKE 'have_query_cache'; | Variable_name | Value | | have_query_cache | YES | When using a standard MySQL binary, this value is always YES, even if query caching is disabled. Several other system variables control query cache operation. These can be set in an option file or on the command line when starting mysqld. The query cache system variables all have names that begin with query_cache_. They are described briefly in Section 5.1.3, “Server System Variables”, with additional configuration information given here. To set the size of the query cache, set the query_cache_size system variable. Setting it to 0 disables the query cache. The default size is 0, so the query cache is disabled by default. Be careful not to set the size of the cache too large. Due to the need for threads to lock the cache during updates, you may see lock contention issues with a very large cache. Quote taken from the MySQL Site http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html
Does MySQL cache queries by default or does it only cache when the SQL_CACHE keyword is used in the query? What other things should I keep in mind when using MySQL caching?
Does MySQL cache by default
like florian h says most browsers will cache the content (unless development tools are being used). if you only use the slideshow javascript on one page I would recommend putting it in a separate file. There is a downside to this, most often the http requests take the longest time with loading a file. So if you for example have one javascript file of 1mb and you need all the javascript on most pages its better then using 4 smaller files of 250kb each. Because your browser needs to do 4 separate requests. Ofcourse this maybe is a difference of a couple of milliseconds of performance profit, so you might want to choose to do it in separate files anyway to increase maintainability.
Usually, the javascripts of the main page is heavier than other pages. For example, we put jQuery slideshow in the main page which is not used in other pages. Is it necessary to create different s for the main and individual pages to include only in-action javacript files? Or all javascript files read on the first page will be cached for browsing the website, and in loading an indivitual page, browser will not read the javascript of slideshow? Another form of this question is: if I put slideshow on each individual page, will the browser load the slideshow javascript file each time, or it will read from its cache (saved on the visitor's computer)?
Using separate javascript file for each html page?
Output caching stores a rendered page/control and spits back the stored HTML instead of having to generate it again for each request. Typically you do output caching for a specified period of time, for example 60 seconds. On the first request, the output is cached, subsequent requests for the 60 second duration use the cached page instead of generating the html again. If this control is database intensive, then all subsequent requests for the 60 second duration saved database calls, etc, and the page load for the subsequent requests should be much faster. Information on Output Caching is readily available on google. Other caching techniques would include, but is definitely not limited to: Browser Caching Object Caching Query Caching
What is output caching for a web application, is it always good to use output caching to improve web app's performance. Besides output caching, are there some other caching techniques?
What is output caching, is it always good to use output caching to improve web app's performance?
In IIS you can define HTTP Headers. Within IIS click your images folder. Then click HTTP Response Headers. Then Set Common Headers... From here you can check Expire Web Content and after how much time you choose. You can also do this for JS and CSS. Be careful which files you apply this too. Also if you set a very far out expiration and you plan to change these files you could cause problems for your site. If you have 1 month expiration on a JS file and then you change it while using the same name then when a user visits your site they will see the content has not expired and will not request the changed file from the web server. You can cope with this by setting modest expiration times while you think the content is subject to change or you can apply version numbers to your javascript and CSS files.
I have the report from YSlow: (no expires) http://static3.scirra.net/avatars/128/40cfdcbd1b1ec1842e199c97c4b85a4a.png (And a lot more similar). In my web.config though, I have: <system.webServer> <staticContent> <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" /> </staticContent> <caching> <profiles> <add extension=".ashx" policy="CacheForTimePeriod" kernelCachePolicy="DontCache" duration="01:00:00" /> <add extension=".png" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" location="Any" /> </profiles> </caching> <rewrite> <rules> <rule name="Avatar"> <match url="avatars/([0-9]+)/(.*).png" /> <action type="Rewrite" url="gravatar.ashx?hash={R:2}&amp;size={R:1}" appendQueryString="false" /> </rule> </rules> </rewrite> Should this not be adding the expires header correctly? My objectives are: Gravatar.ashx fetches image from Gravatar server Server caches result for 1 hour (similar to SO) Expires header is added so client doesn't keep fetching it from my server
No expires header
You might expect the browser to enforce a single limit for all storage an origin can use, but the major browsers are actually enforcing limits separately for each storage mechanism. Source: http://www.html5rocks.com/en/tutorials/offline/storage/#quotas That answers your question I think.
I am developing a web application for remote areas with little internet connectivity and was wondering if I can use HTML5 localStorage with a maximum size of 10MB and HTML5 local Database with a maximum size of 10MB for a total of 20MB of offline storage (Not including HTML5 Application Cache) or do browsers combine these quotas? Is HTML5 Application Cache a separate quota? Are there any other ways of getting more than 10MB of persistent storage?
Combining HTML5 localStorage and local Database for more space?
1 OSCache has not been abandoned; a lack of constant change only means that it fulfills the requirements the designers had, not that the project isn't useful any more. Share Improve this answer Follow answered Jun 25, 2011 at 11:45 Joseph OttingerJoseph Ottinger 4,93111 gold badge2323 silver badges2323 bronze badges 2 1 To me it seems the project is dead, at least the website says so opensymphony.com/oscache – Peter Szanto Jun 27, 2011 at 6:23 The project itself is still fully functional. YMMV. – Joseph Ottinger Jun 27, 2011 at 11:44 Add a comment  | 
I want to cache some portions of my JSP page because it is heavy to render. The whole page cannot be cached as it contains user specific content, but most of it can. I thought the best solution would be to create a JSP cache tag. It seems there are several solutions for that but most of these projects are dead or abandoned http://www.opensymphony.com/oscache/ http://jakarta.apache.org/taglibs/doc/cache-doc/ http://www.servletsuite.com/servlets/cachetag.htm I am wondering if there is any project that is alive, open source, or is there any better soltion that can work?
jsp caching tag library
1 isNotModified is a method on HttpFoundation\Response that takes a HttpFoundation\Request object and checks the lastModified and ETags on a Request. You should not use HttpCache directly but look at Response and Request classes to see their API. Also there is a Symfony dokumentation click here Share Improve this answer Follow answered Nov 3, 2011 at 11:35 Henrik BjørnskovHenrik Bjørnskov 1,58111 gold badge1212 silver badges99 bronze badges Add a comment  | 
What can I do to redeclare Contoroller function renderView function (without hardcoding)? How can I lookup twig cache (I think it's should be lookup function in HttpCache class , but it's says Fatal error: Call to a member function isNotModified() when I try redefine it ), and write it into memcache? Are there native memcache settings working with twig in Symfony2?
Symfony2 caching
Just one answer? Well 1.) No hardware implemented. They should be documented by the vendor, if not then microbenchmarking is an option. 2.) Hardware 3.) As pointed out above L1 cache has separate caches for data and instruction. There is also TLB for virtual memory. 4.) I attended a course last semester which covers these topics. The slides are available online: http://www.systems.ethz.ch/education/past-courses/hs09/mmdbms
Please bear with me , these questions may be very basic . I am just trying to understand the fundamentals. Are the cache eviction algorithms such as LRU are implemented by the OS ?? if so , how can we find out the current algorithm being used and is it possible for the programer to change it ? Since cache is along with processor , the read and write policies are hardcoded or the operating system decides it ? Are there separate caches for data and instructions ? or do they share the same cache ? What are the algorithms currently employed in operating systems to solve cache coherency problem ? Thanks for your patience in answering my questions. Sethu
Few basic doubts regarding caches
1 Check whether the UPDATE is actually executing: mysql_connect("localhost","mayankx_tt","111111"); mysql_select_db("mayankx_tt") or die(mysql_error()); # Checking PRE Value print_r(mysql_fetch_array(mysql_query("select visits from Orders"))); # Attempting to Modify if( !mysql_query("update Orders set visits=visits+1") ){ echo 'Error Occurred: #'.mysql_errno().' '.mysql_error(); }else{ echo 'UPDATE Processed OK'; } # Check POST Value print_r(mysql_fetch_array(mysql_query("select visits from Orders"))); Run that and let us (me) know what output it produced. Share Improve this answer Follow edited May 28, 2011 at 12:39 answered May 28, 2011 at 11:03 Luke StevensonLuke Stevenson 10.4k22 gold badges2626 silver badges4141 bronze badges Add a comment  | 
I am updating a value in a sql table and then printing the value, it is still showing old value. <? print_r(mysql_fetch_array(mysql_query("select visits from Orders"))); mysql_query("update Orders set visits=visits+1"); print_r(mysql_fetch_array(mysql_query("select visits from Orders"))); ?> It outputs 1 and then again 1. The second value should be 2. When I check in PhpMyAdmin it is 2 then why is it showing Old Value? Please help! Thanks in advance. Regards, Mike Edit: This is the code the OP tried: mysql_connect("localhost","mayankx_tt","111111"); mysql_select_db("mayankx_tt") or die(mysql_error()); print_r(mysql_fetch_array(mysql_query("select visits from Orders"))); mysql_query("update Orders set visits=visits+1"); print_r(mysql_fetch_array(mysql_query("select visits from Orders"))); And his output: Array ( [0] => 4 [visits] => 4 ) Array ( [0] => 4 [visits] => 4 )
PHP MySql Query is showing old value after update
I found out what was the problem. In some models i was using cattr_accessor and i find that everything in forms that was being cached was the same fields i used cattr_accessor. Classes would be cached so seems that cattr_accessor would be cached too. I just replaced it with attr_accessor and everything works fine. Thanks guys!
i developed a project using Ruby on Rails and i having a huge problem after putting it on production environment. All forms seems to being cached. If i fill a whole form and send it to the server, the next time i access that form to create a new object, all fields will be already filled with previous data. This only happens on production environment, and i found that when i set this line to false, everything works fine: config.cache_classes = true Seems that this cache_Classes is causing the problem but i think that maybe another thing is causing the problem because cache_classes would only cache classes and not forms and i think that i may have a great performance loss with this config setted to false. Please help!
Rails caching forms
Yes, when a web app is added to the home screen, it will no longer be opened using MobileSafari, but using WebSheet. Unless they share the same local storage, it makes sense that you would need to cache the app again after adding it to the home screen.
I need clarification. My webapp is cached in safari. With airplane mode on (wifi off) everything is working fine. When I say "add to homescreen" the app only works when I open it one time with wifi on. After that the app works perfectly well offline. Is that the expected behavior? Till now I understood that the cached data (including localStorage stuff) is transfered from safari to the webapp.
Do I have to open a iOS webapp before the app is cached (cache manifest)?
Well, in sighted article, author has created a custom handler to server the manifest with correct MIME type. This is indeed a good way in ASP.NET where you don't have to touch web server configuration. If you don't want to write such handler and wish to serve file directly such as "app.manifest" then you have to make sure to modify IIS configuration (for the web-site) map the correct MIME Type (text/cache-manifest) for manifest extension (see this and this for how to register a new MIME type in IIS)
When using a cache manifest file within ASP.NET can I just add a standard text file called something like app.manifest? (which is then referenced from the html in each relevant page). Or are there other considerations (such as mime type) that demand a more convoluted approach? In this approach: http://stephenwalther.com/blog/archive/2011/01/26/creating-html5-offline-web-applications-with-asp-net.aspx then Stephen Walther sets up the manifest as a handler. Do I really have to do it that way in ASP.NET, or is there a 'simpler' way in ASP.NET? Just striving for less code! Thanks.
Defining the Cache Manifest file within ASP.NET
After some "fun" code-spelunking I seem to have found something that works: mc.set(key, HashWithIndifferentAccess[o.attributes]) as_hash = mc.get(key) from_cache = Foo.load([as_hash], Foo.all.query).first The load method on the model seems to be what get uses and the query seems to be required in order to get the repository names and a few other things.
I'm working on on a caching layer in my Rails app and I'm having trouble caching original DataMapper objects. They seem to have a lot of stuff attached that make marshaling fail (I get an error about Marshal being unable to serialize a Proc object). So I am considering writing my own pre-serialization and post-deserialization methods for caching. Specifically I will turn the DataMapper object into a list of tuples with this: o = Foo.get(1234) as_list = o.model.properties.map { |p| [p.name, o.send(p.name)] } And then cache that list. My question is: How do I reconstruct the DataMapper object in a way that allows me to use it as it if were constructed by a normal DataMapper query? My naive approach of Foo.new(foo=bar, goo=baz) doesn't seem to connect it up with all of the foreign keys and stuff.
Alternative serialization for DataMapper objects in Rails
but what exactly am I suppose to cache? You're supposed to cache the data that doesn't change often and is read many times. For example, let's take a forum - you'd cache the initial page of the forum that displays forums available, forum description and forum IDs that allow you to see topics under various forum categories. Since it's not likely that you create, delete or update forums every second, it's safe to assume that the read:write ratio is in favor of read which allows you to cache that front page where you display forums and by doing so, you are alleviating the load on your database since it doesn't have to be accessed for most visits to your site. You can also take this caching one step further - you cache everything your site has to offer and you set your cache expiry time to 5 minutes. Assuming your database isn't huge (hundreds of gigabytes) and that it fits available RAM - you'd effectively query your database every 5 minutes. Assuming you have a lot of visits per day (let's say 20 000 unique visits) - you can calculate how much it attributes to saving resources when connecting to database and extracting data.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it. Closed 10 years ago. Improve this question There are a lot of tutorial on the Internet which claim to teach you how to use memcacheD, but most of them are about memcache (hence the emphasis on the d). In php, memcached doesn't even have a connect method. Also a lot of these tutorial just teach you how to connect and add values, but I can figure that out by reading the manual, so please help me to create a one stop reference for memcached. What strategies would you recommend, what are the best practices? How would you cache something like a forum, or a social site with ever-changing data? The trouble I seem to have is, I know how to connect, add and remove values, but what exactly am I suppose to cache? (I'm just experimenting, this is not for a project, so I can't really give an example).
A beginners guide to caching using memcacheD [closed]
1 I would probably use threading.Timer for this. A Timer object will call a specified function with given arguments after a period of time. So write a function that returns a JSON object to the pool, and start a timer that specifies the specific JSON object that has been reserved. Additionally, you can cancel a timer before it fires, which you will want to do if the client actually requests the object before the reservation expires. To keep track of the pool, I would probably use a dict where the JSON object is the key and the value is either None if the object is not checked out, or the Timer instance if it is checked out. A separate list could be used to keep track of what object should be given out next; pop() from the end of the list when taking an object out and append() it back on when it's returned. Beware of possible race conditions updating both of these structures! Share Improve this answer Follow edited Apr 5, 2011 at 18:01 answered Apr 5, 2011 at 16:56 kindallkindall 181k3535 gold badges283283 silver badges313313 bronze badges Add a comment  | 
I have a need to reserve an object (JSON) within my app for a period of time (typically 180 seconds) At some point the client may or may not come back and request this object by its key. The tricky part is that I need to be notified when this object expires so I can return it to the available pool if the client hasn't already requested it. The obvious solutions are to use something like a timestamp in the database and then a periodic script to check for expired items but this doesn't feel like the nicest solution. Ideally I'm looking for something like memcache that can call an event when an item expires, surely there is such a product out there? My current framework is based around python, cherrpy, mongo, memcachce but I'm happy to add to it.
Add 'object' to a stack with expiry timers and get notified when it expires
1 You need to create a descendant of Mage_Catalog_Block_Product_List and use it's alias for the block type, like "yourmodule/product_list" instead of "catalog/product_list". Follow these instructions to enable it's cache, the first example given is exactly what you need to display some product related data, but use a larger lifetime for more efficiency. Share Improve this answer Follow answered Mar 23, 2011 at 2:46 clockworkgeekclockworkgeek 37.7k99 gold badges9090 silver badges127127 bronze badges 1 I tried this method and I'm seeing some performance gain for this block for registered users so it seems to be a good solution. Thank you so much, clockworkgeek. – user672201 Mar 23, 2011 at 5:43 Add a comment  | 
For a Magento enterprise site, I have a CMS page (home page) which includes a certain block of code, 'my-products.phtml', using the following method within the CMS page content: {{block type="catalog/product_list" template="catalog/product/my-products.phtml"}} The problem is that this block is really really slow and needs to be cached. The containing CMS page is cached for non-sessioned visitors, but once a user logs in, the page and the included block don't seem to be cached at all. There's no session-specific code within the block so I'm wondering how to ensure that it is cached even when a user is logged in?
how to cache cms block in magento for sessioned and non-sessioned visits?
Yes - to ensure that browsers pick up the new image files in this scenario, you should change the image file names too.
I have relatively long cache expiry headers and am making some changes to my website. I'll be changing the filenames of the .css and .js files to prevent the old files being loaded from the user's cache. Do i need to also rename the background images (which have also changed) referenced in the css? I'm thinking yes, but thought I'd check...
Have long cache expires: need to rename background img files as well as css?
1 That is possible using Apache. It can parse cookie value and pass it to custom header, then you need to Vary by this header: # Set languageC cookie value to environment variable "siteLanguage" RewriteCond %{HTTP_COOKIE} ^.*lunetics_locale.*$ [NC] RewriteCond %{HTTP_COOKIE} (?:^|;\s*)lunetics_locale=([^;]*) [NC] RewriteRule ^(.*)$ - [env=siteLanguage:%1] # If no languageC cookie present. Set "siteLanguage" environment variable to "en" RewriteCond %{HTTP_COOKIE} !^.*lunetics_locale.*$ [NC] RewriteRule ^(.*)$ - [env=siteLanguage:en] # Set enviroment variable "siteLanguage" value to custom header "SiteLanguage" RequestHeader set X-Language "%{siteLanguage}e" env=siteLanguage and add Vary X-Language to your response headers. I'm not sure this is a best way, I have related question and problems with this: Is it possible to vary page caches (to have cache versions) with the same url and different cookie value (language)? Share Improve this answer Follow edited May 23, 2017 at 11:43 CommunityBot 111 silver badge answered Apr 27, 2015 at 23:23 borN_freeborN_free 1,4251212 silver badges2020 bronze badges Add a comment  | 
Currently, I am using mod_cache to cache the page details of a web application. I have the cache Vary based on User-Agent and Accept-Language, since there are different payloads for those situations. Vary: User-Agent, Accept-Language We have plans to have region-specific information on each page, but this is where we are trying to determine our caching strategy. We have a cookie that persists to indicate the region we geolocated for, but obviously the cache does not vary based on this cookie. It is possible to vary based on the value for certain cookies or headers in general? (Note I say certain cookies, as we wouldn't want the session identifier to collide with this) - something like a regex match to this: location=(.+?);
Apache mod_cache: Vary cache based on cookie values
You have nothing to worry about. The class is thread safe.
I’m using HttpContext.Current.Cache to cache data from the DB (.Net 4 web application). I want to make sure I don’t run into any threading synchronization problem. Scenario: 3 users pointing to the same Company Object: User A: Profile.Company.Name = “CompX”; Profile.Company.Desc = “CompXDesc”; Profile.Company.Update(); //Update DB User B: String Name = Profile.Company.Name; User C: Profile.Company.Name = “CompY”; Profile.Company.Update(); //Update DB Questions: Does the Cache provide any type of locking? Should I add Locks like ReaderWriterLockSlim (how exactly)? Existing Code: ProfileBLL: public CompanyBLL Company { get { return CompanyBLL.GetById(this.Company_ID); } } // HttpContext.Current.Cache public static CompanyBLL GetById(int Company_ID) { string key = "GetById_" + Company_ID.ToString(); CompanyBLL ret = null; if (Cache[key] != null) { ret = (CompanyBLL)Cache[key]; } else { ret = DAL_Company<CompanyBLL>.GetById(Company_ID); Cache[key] = ret; } return ret; } Another option is to add TransactionScope on any DB update: User A: using (TransactionScope Scope = new TransactionScope()){ Profile.Company.Name = “CompX”; Profile.Company.Desc = “CompXDesc”; Profile.Company.Update(); //Update DB Scope.Complete(); //COMMIT TRANS } User B: String Name = Profile.Company.Name; Will it solve any threading problem? Thanks
Should I add Locks or TransactionScope when using .Net Cache?