3. Before you start...
➢ Experience bulding software with Java
➢ Builder Pattern [Item 2 – Effective Java]
4. Annotations
➢ GwtCompatible – Type can be used with GWT
➢ Beta – A public API class,method or field is
subject to change
➢ GwtIncompatible – Cannot be used with GWT
➢ VisibleForTesting – Indicates the visibility of
the type or member has been relaxed to make
code testable
5. Guava – Introduction
➢ Google Guava is open source project released
by Google
➢ Actively used and maintained by google
engineers
➢ Used extensively in open source projects
➢ Not a replacement of Apache commons- you
can continue to use both
6. Why Guava?
➢ The goal is for you to write less code
➢ Make code more readable, cleaner and simpler
➢ Helps developers to focus on business logic
rather than writing java utilities
➢ Saves time, resources and improve productivity
➢ Extension for Java
7. Preconditions
➢ checkArgument(boolean)
➢ Thows IllegalArgumentException
➢ Used to validate argument
➢ checkState(boolean)
➢ Throws IllegalSateException
➢ Used to check Object state
➢ checkNotNull(T)
➢ Throws NullPointerException
➢ Returns the value directly if non null
8. Preconditions
public static boolean isTrue(Boolean value){
checkArgument(value,"You are not passing true.");
return true;
}
isTrue(false);
---
Exception in thread "main" java.lang.IllegalArgumentException:
You are not passing true.
At ...
isTrue(true);
---
Continues gracefully ....
9. Why Preconditions?
➢ Validation
➢ Defensive coding
➢ Each method has three variants
➢ No extra arguments
➢ An extra object for error message
➢ An extra String & Object. GWT compatible.
String.Format like ub only allows %s
➢ Recommned to be used with static imports
10. Preconditions
public static void argOneLessThanArgTwo(int i,int j){
checkArgument(i<j,"%s is not less than %s",i,j);
}
---
Exception in thread "main" java.lang.IllegalArgumentException:
10 is not less than 5
public static boolean checkIfNull(Object foo)
{
checkNotNull(foo);
return true;
}
---
Exception in thread "main" java.lang.NullPointerException
11. Strings
➢ Joiner
Joiner joiner = Joiner.on(" ").skipNulls();
String str = joiner.join("Harry",null,"Potter");
System.out.println(str);
---
Harry Potter
15. Strings
➢ Java inbuilt splitter has quirky behaviour
➢ Use Guava splitter instead
➢ Makes use of fluent pattern
Iterable<String>splitStr = Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.split("foo,bar,, qux");
---
foobarqux //splitStr if iterated will have foobarqux
16. Strings
➢ CharMatcher
– Utility methods to operate on occurence of
CharSequence type
//Remove digits from the string
CharMatcher.digit().removeFrom("123abc")
---
Abc
//Retain only numbers and upper and lower case characters
CharMatcher.digit()
.or(CharMatcher.javaLowerCase())
.or(CharMatcher.javaUpperCase())
.retainFrom(“@#$@#$@#$Mb:13232546595”);
17. Strings
➢ CharSets
– Similar to StandardCharSet in Java 7
try {
byte[] bytes= num.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Use this one instead
byte[] byteContainer= num.getBytes(Charsets.UTF_8);
18. Object Common Methods
➢ Objects.equals [Item9] – Compare in null
sensitive way
➢ Objects.hashCode – Hashing all fields of the
class
➢ toString – MoreObjects.toStringHelper [Item
10 Effective Java Always overide toString]
➢ compare/compareTo – Alternative to direct
implementation of Comparator/Comparable
interfaces
24. Caching
➢ Guava has on heap key value cache
➢ Implementation is thread safe
➢ No support for distributed caching – Consider
memcached instead
25. Caching
➢ When to consider Gauva cache? (guava wiki)
➢ You are willing to spend some memory to improve
speed.
➢ You expect that keys will sometimes get queried
more than once.
➢ Your cache will not need to store more data than
what would fit in RAM.
26. Caching
➢ Caching Verbs
➢ Populating
➢ Evicting
➢ Refreshing
➢ Types of Cache in Guava
➢ Loading Cache - knows how to load enteries when
a cache miss happens
➢ Cache – Does not automatically load enteries
27. Caching – Population
➢ From a cache Loader
➢ LoadingCache is a Cache built with CacheLoader
➢ CacheLoader knows how to get the keys if the key
is missing
➢ Using Callable
➢ get(K,Callable<K>)
➢ Inserted Directly
➢ Values are inserted directly using cache.put(K,V)
28. Caching
● CacheLoader
–
● CacheLoader
–
➢ CacheLoader
LoadingCache<Integer,Integer> cache =
CacheBuilder.newBuilder()
.maximumSize(20)
.build( new CacheLoader<Integer,Integer>(){
public Integer load(Integer key){
return fibonacii(key);
}
});
public static int fibonacii(int i){
if(i==0||i==1)
return 1;
else
return fibonacii(i-1)+fibonacii(i-2);
}
29. Caching
➢ Quiz
What will be the size of the cache?
LoadingCache<Integer,Integer> cache =
CacheBuilder.newBuilder()
.maximumSize(20)
.build( new CacheLoader<Integer,Integer>(){
public Integer load(Integer key){
return fibonacii(key);
}
});
Cache.get(0);
for(i=0;i<40;i++)
Cache.get(i);
30. Caching
➢ Eviction
➢ We will not have enough memory to cache
everything
➢ Hence eviction is inevitable
➢ Types
➢ Size Based Eviction CacheBuilder.maximumSize(long)
➢ Timed Eviction
➢ CacheBuilder.expireAfterAccess(long,TimeUnit)
➢ CacheBuilder.expireAfterWrite(long,TimeUnit)
31. Caching
➢ Reference Based Eviction
➢ Guava allows you to garbage collect entries by
using weak References for key & values
➢ Soft Refernces for Values
➢ Builders for Refernce based Eviction
➢ CacheBuilder.weakKeys()
➢ CacheBuilder.weakValues()
➢ CacheBuilder.softValues()
32. Caching
➢ Refreshing
➢ Refreshing is not same as eviction
➢ Refreshing a key loads a new value for the key
➢ LoadingCache.refresh(K)
Give an overview of Guava and set scope for the discussion.
Idea is to create awareness about this awesome library.
Talk about JAVA REPL- to run some examples on the fly
There are multiple other modules which are not in scope of this presentation
1) Collections
2) Event Bus
3) Handling Nulls
4) Predicates
5) Concurrency
6) IO
7) Reflection
Explain the builder design pattern. Item 2 Effective Java
Difficult to appreciate the beauty of fluid pattern if you don&apos;t understand Builder Design Pattern.
Mention about the number of tests in guava
Pure Java example can be discussed here on how to do it.
Explain the concept of Caching
- In computing, a cache is a hardware or software component that stores data so future requests for that data can be served faster
Explain the cache replacement policies
- Least Recently Used cache replacement policy
First Question:
Is there a sensible default function to load or compute a value associated with a key?
Get -If-Absecent-Compute semantics
Elements can be directly inserted as well
Weak References: GC can mark referants from being made finalizable,finalized and then reclaimed
Strong Reference: Regular
Soft References; LRU
WeakKeys: stores keys using weak ref. Allows enteries to be garbage collected if no ref to key
WeakValues: stores value using weak ref. Allows enteries to be gc&apos;ed if no strong or soft ref to values
SoftValues: wraps value in soft ref. Softly ref values are gc&apos;ed based on global LRU manner