Guava : Is Cache.asMap().remove() better? - guava

I want to get & remove an item from Cache
final Cache<String, PendingRequest> pendingRequest = CacheBuilder.newBuilder().build();
// get first
pendingCall = pendingRequest.getIfPresent(key);
pendingRequest.invalidate(key); // then remove.
I also found another way
pendingCall = pendingRequest.asMap().remove(key);
Does asMap method clone all the items? Is it a heavy call? Which manner is better if considering performance.

There's no real difference between those calls because Cache#asMap() is defined as:
Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.
Calling asMap() may be slightly less performant (because it's possible a view has to be created) but the time is constant (and negligible) and is an implementation detail (see internal Guava LocalCache and LocalManualCache classes for more details).
What's more important, Cache#invalidate(K) is more idiomatic and I'd recommend using it instead of map view methods (edit after #BenManes' comment below) if you don't need returned value associated with the key, otherwise use map view.

Related

Difference between getter and accessing it directly

For example I have a field that I want to access in my app view. I have this provider
class User with ChangeNotifier{
String userNick = "test";
String get getName() => userNick;
}
What will be the difference, if I access the nick this way in my app vs getter?
context.watch<User>().userNick;
vs
context.watch<User>().getName();
If I don't use the getter and my userNick changes, will I not see it refreshing in my app or?
Getters/setters are preferred for use the data properly. If you use the data directly, you can update it when you even don't wanna update it and this type of logical mistakes takes too much time to detect and fix. Also, it is safe way to manipulate the data.
Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
from: https://en.wikipedia.org/wiki/Object-oriented_programming
For more, you can search for encapsulation online.

Entity Framework - Referencing object properties that were just set

Assume I am populating an object's properties and I need to pass in one of the properties to another method, is it OK to reference a property from the new object or should I set a separate variable first and use it? Is one way better than the other? Keep in mind I have not called SaveChanges().
Method #1 (use property from new object)
=================================================
newObject.LegacyId = oldObject.Id;
newObject.NewId = GetNewIdFromLegacyId(newObject.LegacyId);
Method #2 (set separate variable)
=================================================
int legacyId = oldObject.Id;
newObject.LegacyId = legacyId;
newObject.NewId = GetNewIdFromLegacyId(legacyId);
I have to assume that both methods are equivalent.
The only thing that could make things different here is when there is more code in the getter or setter of newObject.LegacyId than just storing/returning a member variable, by which you'd return a different value than the set value. This would be highly insensible and unexpected. (And therefore unlikely you're actually doing this).
So it's really a matter of taste which method you prefer. I think personally I might prefer a third method:
int legacyId = oldObject.Id;
int newId = GetNewIdFromLegacyId(legacyId);
newObject.LegacyId = legacyId;
newObject.NewId = newId;
This is a micro-isolation of responsibilities: getting Id values and object initialization. This may seem nitpicking, but Single Responsibility (the S of SOLID) is one of the most important design principles and it can be applied at any level to make code better maintainable. It might lead you to separating the code in two parts that you can (unit) test separately.

How to specify different cache keys on the same key object in simple-spring-memcached

I am trying to implement a distributed cache with spring-memcached. The docs suggest that
to use an object as the key I need to have a method in my domain class with #CacheKeyMethod
annotation on it.
But the problem is I am using the same domain class in different scenarios and the key to be generated in each case has different logic. For examples for a User class one of the scenarios requires the key to be unique in terms of city and gender and but in the other case it requires to be unique in terms of the user's email, it's essentially what your lookup is based on.
Although a user's email would determine the city and gender, so I can use email as the key in first case as well but that would mean separate cache entries for each user while the cached data would be same as long as the gender and city are same, which is expected to increase the hit ratio by a huge margin(just think how many users you can expect to be males from bangalore).
Is there a way I could define different keys. Also it would be great if the logic of
generating the key could be externalised from the domain class itself.
I read the docs and figured out that something called CacheKeyBuilder and/or CacheKeyBuilderImpl could do the trick but I couldn't understand how to proceed.
Edit..
ok.. I got one clue! What CacheKeyBuliderImpl does is, it calls the generateKey method on defaultKeyProvider instance which looks for #cachekeyannotation on the provided domain class's methods and executes the method found to obtain the key.
So replacing either the CacheKeyBuilderImpl with custom Impl or replacing KeyProvider's default implementation within CacheKeyBuilderImpl with yours might do the trick... but the keyprovider reference is hardwired to DefaultKeyProvider.
Can anybody help me implement CacheKeyBuilder(with respect to what different methods do;the documentation doesn't clarify it) and also how do I inject it to be used instead of ususal CacheKeyBuilderImpl
Simple Spring Memcached (SSM) hasn't be designed to allow such low level customization. As you wrote one of way is to replace CacheKeyBuilderImpl with own implementation. The default implementation is hardwired but it can be easily replaces using custom simplesm-context.xml configuration.
As I understand your question, you want to cache your User objects under different keys depends on use case. It's supported out of the box because by default SSM uses method argument to generate cache key not the result.
Example:
#ReadThroughMultiCache(namespace = "userslist.cityandgenre", expiration = 3600
public List<User> getByCityAndGenre(#ParameterValueKeyProvider(order = 0) String city, #ParameterValueKeyProvider(order = 1) String genre) {
// implementation
}
#ReadThroughSingleCache(namespace = "users", expiration = 3600)
public User getByEmail(#ParameterValueKeyProvider String email) {
// implementation
}
In general the #CacheKeyMethod is only used to generate cache key if object that contains the method is passed as a parameter to the method and the parameter is annotated by #ParameterValueKeyProvider

Are singletons automatically persisted between requests in ASP.NET MVC?

I have a lookup table (LUT) of thousands integers that I use on a fair amount of requests to compute stuff based on what was fetched from database.
If I simply create a standard singleton to hold the LUT, is it automatically persisted between requests or do I specifically need to push it to the Application state?
If they are automatically persisted, then what is the difference storing them with the Application state?
How would a correct singleton implementation look like? It doesn't need to be lazily initialized, but it needs to be thread-safe (thousands of theoretical users per server instance) and have good performance.
EDIT: Jon Skeet's 4th version looks promising http://csharpindepth.com/Articles/General/Singleton.aspx
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
// randomguy's specific stuff. Does this look good to you?
private int[] lut = new int[5000];
public int Compute(Product p) {
return lut[p.Goo];
}
}
Yes, static members persists (not the same thing as persisted - it's not "saved", it never goes away), which would include implementations of a singleton. You get a degree of lazy initialisation for free, as if it's created in a static assignment or static constructor, it won't be called until the relevant class is first used. That creation locks by default, but all other uses would have to be threadsafe as you say. Given the degree of concurrency involved, then unless the singleton was going to be immutable (your look-up table doesn't change for application lifetime) you would have to be very careful as to how you update it (one way is a fake singleton - on update you create a new object and then lock around assigning it to replace the current value; not strictly a singleton though it looks like one "from the outside").
The big danger is that anything introducing global state is suspect, and especially when dealing with a stateless protocol like the web. It can be used well though, especially as an in-memory cache of permanent or near-permanent data, particularly if it involves an object graph that cannot be easily obtained quickly from a database.
The pitfalls are considerable though, so be careful. In particular, the risk of locking issues cannot be understated.
Edit, to match the edit in the question:
My big concern would be how the array gets initialised. Clearly this example is incomplete as it'll only ever have 0 for each item. If it gets set at initialisation and is the read-only, then fine. If it's mutable, then be very, very careful about your threading.
Also be aware of the negative effect of too many such look-ups on scaling. While you save for mosts requests in having pre-calculation, the effect is to have a period of very heavy work when the singleton is updated. A long-ish start-up will likely be tolerable (as it won't be very often), but arbitrary slow downs happening afterwards can be tricky to trace to their source.
I wouldn't rely on a static being persisted between requests. [There is always the, albeit unlikely, chance that the process would be reset between requests.] I'd recommend HttpContext's Cache object for persisting shared resources between requests.
Edit: See Jon's comments about read-only locking.
It's been a while since I've dealt with singleton's (I prefer letting my IOC container deal with lifetimes), but here's how you can handle the thread-safety issues. You'll need to lock around anything that mutates the state of the singleton. Read only operations, like your Compute(int) won't need locking.
// I typically create one lock per collection, but you really need one per set of atomic operations; if you ever modify two collections together, use one lock.
private object lutLock = new object();
private int[] lut = new int[5000];
public int Compute(Product p) {
return lut[p.Goo];
}
public void SetValue(int index, int value)
{
//lock as little code as possible. since this step is read only we don't lock it.
if(index < 0 || index > lut.Length)
{
throw new ArgumentException("Index not in range", "index");
}
// going to mutate state so we need a lock now
lock(lutLock)
{
lut[index] = value;
}
}

Returning Array Fragments

I need to get array fragments from an array. I'm sick of using Array.Copy().
new ArraySegment(..).Array returns the original [full] array. The one below is what I came up with but I feel it's pretty lame. Is there a better way to do this?
class Program
{
static void Main(string[] args)
{
var arr = new ArraySegment<byte>(new byte[5] { 5, 4, 3, 2, 1 }, 0, 2).ArrayFragment();
for (int i = 0; i < arr.Length; i++)
Console.WriteLine(i);
Console.Read();
}
}
static class Extensions
{
public static T[] ArrayFragment<T>(this ArraySegment<T> segment)
{
var arr = new T[segment.Count];
Array.Copy(segment.Array, segment.Offset, arr, 0, segment.Count);
return arr;
}
}
Thanks in advance.
Update:
The above was just an example.
I have a method: byte [] CalculateXXX(byte [] key, byte [] message);
I do array manipulations inside this method. I want to return portion of an array.
ArraySegment does not implement IEnumerable and it does NOT return an array with just the segment new ArraySegment(arr...).Array returns the complete original array.
var rval = new byte[4];
//new ArraySegment(finalOutputBuffer, 0, 4).SegmentedArray();
Array.Copy(finalOutputBuffer, 0, rval, 0, 4);
I find I had to do the above to return a array fragment. Was just wondering if there's a better way of returning fragments of an array [as new array].
Vyas, I am truly sorry for having posted this useless pile of ****. It's been ages since I've actually used ArraySegment and I simply assumed that it implemented a (more or less) consistent interface. Someone (Jon?) please tell me which drugs were used during the implementation of this useless struct.
Finally, to make a long story short, the best solution is probably to implement your own version of ArraySegment, only doing it right.
I don't understand your problem with using ArraySegment. There's no additional overhead involved here, if that's what you mean, since no copying of the original data is done. Rather, ArraySegment offers a lightweight view on the data.
Th make this work, change your (return) type from T[] to IEnumerable<T>, or, if you need indexed access, to IList<T>. Generally prefer using interface types in method signatures, and completely avoid array types. The rationale is very simple: it makes problems such as yours go away and makes the interface more flexible and future-proof. It also provides better information hiding since it hides parts of the implementation which aren't relevant for the consumer of this method.
Define better. What is the downside with ArraySegment? What problem are you having that it doesn't solve?
Edit: Ok, I now understand your point of view, but this is wrong. It might be a bug in the sense that you feel it should do more, but it does exactly what it is supposed to do. It allows you to pass information to a piece of code about an array you wish to use, and which portion of the array to use.
It doesn't provide IEnumerable or anything that gives you a narrow view of the array, ie. x[0] doesn't give you the first element of the segment, nor can you foreach over it.
So yes, it's rather useless on its own, but you wouldn't be able to get something that is an array at heart, and yet is also a segment of a larger array.
You could easily make your own collection-like class that references an array and uses the array as storage, and provides indexing, enumeration, etc.
But that's not what this structure does. I guess the main problem here is that they made you expect more from it through its name.
Just another side-effect of poor iterator design in C# btw. There are many instances similar (just as 'lame') where it would just plain good design to be able to pass or point or control segments (aka concept called range) without all the archane shickanery.. copy semantics or not, array is also a well-defined concept.
Just use C++. :-)