Please explain the use of the interface Supplier(in Guava) with a suitable example .
The Supplier interface is simply an abstraction of a no-arg function that returns a value... it is a means of getting some instance or instances of an object. Since it is so general, it can be used as many things. Jared explained how the Multimaps factories utilize it as a factory for creating a new instance of a Collection of some type for values.
Given the simplicity of the interface, it also allows for some very powerful decoration of a Supplier's behavior by wrapping it in another Supplier that alters its behavior somehow. Memoization is one example of that. I've used the Suppliers.memoizeWithExpiration method myself as an easy way to make it so some data will only be read from a server at most once in a given period of time.
I'd also recommend taking a look at Guice and how the Provider interface is used in it. Provider is exactly equivalent to Supplier and is central to how Guice works.
Provider allows users to define a custom way of creating new objects of a given class. Users can write a get() method which can execute whatever code is needed to create a new object, so they aren't limited to having Guice use constructors alone to create objects. Here, they are using it to define a custom factory for new instance of an object.
Guice allows injection of a Provider of any dependency. This may return a new instance every time get() is called or it may always return a single instance or anything in between, depending on how the binding the Provider represents is scoped. This also allows for "lazy instantiation" of dependencies... the Provider gives a class a means of creating an object without needing to actually create the object ahead of time. An instance of the object does not need to be created until when, and if, get() is called.
As indicated above, Providers form the basis of scoping in Guice. If you take a look at the Scope interface, you'll notice its single method Provider<T> scope(Key<T> key, Provider<T> unscoped) is defined in terms of Providers. This method takes something that creates a new instance of an object (the Provider<T> unscoped) and returns a Provider<T> based on that which applies whatever policy the scope defines, potentially returning some cached instance of the object rather than creating a new one. The default NO_SCOPE scope simply passes along the unscoped provider, meaning a new instance will be created each time. The SINGLETON scope caches the result of the first call to unscoped.get() and thereafter returns that single instance, ensuring that everything that depends on the singleton-scoped object gets a reference to that single object. Note that the Provider returned by the SINGLETON scope's scope method does essentially the same thing as the Supplier returned by Suppliers.memoize (though it's a bit more complicated).
The main reason we included Supplier in Guava was to support the Multimaps methods that generate arbitrary Multimaps, such as
public static <K,V> Multimap<K,V> newMultimap(Map<K,Collection<V>> map,
Supplier<? extends Collection<V>> factory)
The Supplier creates a Collection that holds all of the values for a given key. The Multimap uses the Supplier whenever you store a key-value pair with a key that's not already in the Multimap.
It's a way to provide an indirect object. You may want to provide another object each time Supplier.get() is called.
For example, i have a singleton class called SmtpMailSender, which takes a hostname for the smtp server. However, the hostname can change at runtime, so instead of taking a String hostname, it takes a Supplier<String> hostname.
Another example use of Supplier:
http://javawayoflife.blogspot.com/2010/06/unit-test-and-new-date.html
Another great use of the class is decoupling - if a component only uses another to obtain a value, do not depend on the concrete implementation, but on this interface.
Anyway, there is some example code here: http://www.slideshare.net/tfnico/google-guava
See the Suppliers class and I guess the methods there will somehow answer your question.
Related
As per the book "Effecive java" what does the statement "The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written." means in following paragraph:
The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written. Such flexible static factory
methods form the basis of service provider frameworks, such as the Java Database
Connectivity API (JDBC). A service provider framework is a system in which
multiple service providers implement a service, and the system makes the implementations
available to its clients, decoupling them from the implementations
As per the book "Effecive java" what does the statement "The class of
the object returned by a static factory method need not even exist at
the time the class containing the method is written." means in
following paragraph:
A good way to explain what is meant by this sentence is to consider the EnumSet type, which is a class in the java.util package.
EnumSet is an abstract class without any accessible constructors. In order to get an EnumSet instance, the programmer uses one of its static factory methods, eg. EnumSet.of( ... ). For example:
Set<MyEnum> s = EnumSet.of(MyEnum.FIRST_CONSTANT);
The object returned by the of() method does not have an implementation type of EnumSet. Rather, the implementation type depends on the MyEnum class. If MyEnum has 64 or fewer constants, then the type of the object returned by of() is RegularEnumSet. If MyClass has more than 64 constants, the type of the object returned is JumboEnumSet. The actual type of the object returned, however, is of no interest to the programmer. All he or she cares about is getting some type of object that adheres to the EnumSet contract.
Now, let's say that, oh, five years later the Java language architects decide that it would be important to have another EnumSet implementation type, say, just for example, a cached enum implementation for classes with very large numbers of constants (more than 1024). They write this class to follow the EnumSet contract and call it:
final CachedEnumSet extends EnumSet {
:
:
}
Even though CachedEnumSet didn't exist when EnumSet was written, the fact that the use of static factories enabled a contract-based implementation system enabled the Java architects to add this new implementation years later.
Now, when a client invokes EnumSet.of(), he or she could get a RegularEnumSet object, a JumboEnumSet object, or the new CachedEnumSet object, but they wouldn't care because the object they get is still a subtype of EnumSet and is governed by its contract.
A factory method is generally going to be returning a class that implements an interface (or extends a class, same result either way). But the actual class to be returned may be defined dynamically. In that case, the class to be returned doesn't need to exist when the factory method is written.
May be easiest by example. The JDBC example is something like DriverManager - you provide a database connection URL. From that URL, the DriverManager needs to figure out which class to return. If you're using an Oracle database, it creates an Oracle driver class (which implements the JDBC APIs), even though DriverManager doesn't know anything about Oracle specifically.
As a general case, let's say our factory method returns interface AA. The implementation of the factory method might read a configuration file that defines the class to create, then use reflection to create that class at runtime. The defined class just needs to exist in the CLASSPATH. The factory method knows how to create it, but the implementation hadn't existed at the time the factory method was written.
There are lots of everyday examples where this sort of thing occurs: JDBC providers, custom logging appenders, XML providers.
We suffix "Factory" when the class/interface is used to create numerous objects. What do we suffix an interface that always vends the same object everytime.
If I still use the word factory, am I not overloading the real meaning of Factory, inspite the class always vends the same thing.
(I am new to Business Applications Development)
What about *Singleton with getInstance method? For example, CustomerDatabaseSingleton with getInstance method that returns the single, global instance of CustomerDatabaseSingleton.
We all know state of an Object is value of it's attributes (instance variables), but if class doesn't has any attribute (no inherited attributes), what would be the state of an Object of such class.
There is a word for such objects - stateless.
There is no such thing as a Java class without a parent class. The default parent would be used, e.g. java.lang.Object.
At a minimum every instance of a class has two attributes: a reference address and a Class type. Note, not every class can be instantiated. There is also some space used in the ClassLoader and any String(s) may (or may not) be interned. This actual implementation might vary slightly on the specific version of the JDK and run-time platform, and additional optimizations can be added by the JIT. However, as a Java developer you are not responsible for this memory management and I would be wary of premature optimization.
first thing
any class we write in java will extend Object class by default if there is no extends written by the developer.
so each and every class will definitely have a parent with no doubt atleast Object class.
second
if you dont put any attributes in your class , obviously it will get all the instance variables except private gets inherited to your class.
so it will have atleast object state but it will not serve any purpose
An object with no data members and links to other objects is a stateless object and in this form can hardly be of any use.
This kind of classes can nevertheless be usefull, because of its methods. It can be...
a base for a further inheritance. It declares/defines some methods, that could be inherited by derived classes. This class will probably be an abstract class, having no objects at all (although not a condition)
a service class. It can define some methods, which in nature do not belong to concrete objects but are used by other objects. Like some all-purpose mathematical operations, a service that returns a current time or similar. These methods can be static, so again no instances are needed.
We call those object stateless. As the name suggests, they have no state.
Referring to other answers/comments, even though every Java object implicitly extends Object, mind that Object has no fields. So even though every object has a runtime address and class attributes, for all practical purposes you can still consider some objects stateless.
Next, it is definitely not true that stateless objects serve no purpose! You can use stateless object for:
1) Grouping functions with similar functionality, similar to java.lang.Math, which groups mathematical functions.
2) Passing functionality as a parameter, e.g. Comparator<T> can be used to sort objects that do not implement Comparable<T>, and it definitely needs no state.
Stateless objects are somehow similar to immutable objects: their state can never be changed and therefore they are always thread-safe.
You may also want to see JEE Stateless Session Beans which differentiate between a converstional state and an instance state.
I have read several articles and tutorials on Guice (3.0), and now have a few lingering questions before I can "tie it all together".
// 1. Binds via public, no-arg "ServiceImpl()" ctor?
bind(Service.class).to(ServiceImpl.class);
// 2. Every client-side request for a Service instance returns the same
// ServiceImpl instance?
ServiceImpl impl = new ServiceImpl(...);
bind(Service.class).toInstance(impl);
// 3. Every client-side request for a Service instance returns the same
// SINGLETON ServiceImpl instance?
ServiceImpl impl = new ServiceImpl(...);
bind(Service.class).in(Scopes.SINGLETON).toInstance(impl);
// 4. Should this be a call too bindConstant() instead of toInstance()
// instead? If so, how/why?
Integer timeout = 1000 * 60; // 60 seconds
bind(Integer.class).named(Names.named("TIMEOUT")).toInstance(timeout);
So my questions, as implied by the code snippet above:
When using to(...), I assume the public no-arg ctor is used, and a new instance is returned every time?
Per #2 above, is the same impl instance used for ever Service.class request, or is a new one returned?
Same as #3 above, but now with Scopes.SINGLETON specified.
Is the above code OK or should I be using bindConstant()? If so, how/why?
Under what circumstances should I be using so-called provider methods? I sort of understand the example on that page, but am now choking when it comes to finding a real-world use case for them in my code.
Either the public no-argument constructor is used, or an #Inject-annotated constructor (that would be recommended). A new instance is returned every time, unless you specify a scope on ServiceImpl (either by a later bind(ServiceImpl.class).in(...) line or an #Singleton annotation on ServiceImpl.
In this case, the same impl instance is used for every injection of Service
That is a compile error, for good reason -- you can't specify a scope on a toInstance binding.
bindConstant() should be used for things like configuration parameters that are primitive or String types. For more information, see this answer.
#Provides methods are simply a shorter way of writing Provider<>s. If you don't have a need for them, don't use them. They should generally be used if creating an object is more complicated than a simple constructor call.
My current IVR app uses a wrapper class with several methods to call a web service and then parse its results. Each class has a single "invoke" method which calls the web service, and then calls subsequent submethods to break up the parsing into logical chunks.
Whenever a new input argument is needed in one or more of the submethods, the previous developer would add it as an argument on the invoke, and then add it as an argument on the submethods.
Is this the proper way to do this, or would it be better to set a field on the class, and then reference that whenever necessary?
Instead of:
invoke (oldField1, oldField2, newField1)
submethod1 (results, oldField1, oldField2, newField1)
submethod2 (results, oldField1, oldField2, newField1)
Should it be:
invoke(oldField1, oldField2, newField1){
OldField1=oldField1
OldField2=oldField2
NewField1=newField1
}
submethod1(results)
submethod2(results)
Or even:
new (oldField1, oldField2, newField1){
OldField1=oldField1
OldField2=oldField2
NewField1=newField1
}
invoke()
submethod1(results)
submethod2(results)
Thanks!
The first solution allows making the object stateless, and allows using a unique instance for all the invocations, even in parallel.
The third one allows making the object stateful but immutable. It could be used for several invocations using the same set of fields, even in parallel (if made immutable).
Both of these solutions are acceptable. The less state an object has, the easiest it is to use it, particularly in a multi-thread environment.
The less mutable an object is, the easiest it is to use it.
The second one makes it a stateful mutable object, which can't be used by several threads (without synchronization). It looks less clean than the other two to me.
My general rule is to avoid statefulness in a service-oriented class whenever possible. Although Java doesn't really support functional programming per-se, the simplest and most scalable implementation is your first approach, which uses no member variables.
If your goal is to avoid frequent changes to method signatures, you could try to use a more generic field encapsulation:
public class Invoker {
public static void invoke(ResultContainer result, List<String> parameters) {
submethod1(result, parameters);
submethod2(result, parameters);
}
}
I would also recommend that you take a look at the Decorator design pattern for more ideas.
It depends on if your argument is data or identifying a mode/switch.
I suggest one argument for the data structure type and another argument that contains the enum types of different operations.
And then based on your enum type or mode of operation you can choose a strategy on which class to execute.
To restrict this increasing argument approach, you could provide an interface. And force the implementation to adhere to that.