SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Gauva – Extension to Java
JUG Hyderabad
Rohit Vaidya
Agenda
Basic Utilities Strings
Caching
Before you start...
➢ Experience bulding software with Java
➢ Builder Pattern [Item 2 – Effective Java]
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
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
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
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
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 ....
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
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
Strings
➢ Joiner
Joiner joiner = Joiner.on(" ").skipNulls();
String str = joiner.join("Harry",null,"Potter");
System.out.println(str);
---
Harry Potter
Strings
List<String> fruits =
Arrays.asList("Guava","Apple","Mango",null,"Pears");
String fruit = Joiner.on(" ").useForNull("Banana").join(fruits);
System.out.println(fruit);
---
Guava Apple Mango Banana Pears
Strings
➢ Splitter - Quiz
String[] str="foo:and:boo".split(":");
for(String s:str)
if(s.isEmpty())
System.out.print("empty ");
else
System.out.print(s+ “ “);
---
1) “empty” ”foo” ”and” ”boo” ”empty”
2) “foo” ”and” ”bar”
3) “foo:and:bar”
Strings
Quiz continued:
String[] str="foo:and:boo".split("o");
for(String s:str)
if(s.isEmpty())
System.out.print("empty ");
else
System.out.print(s+ “ “);
---
1) “empty” ”f” ”empty” ”:and:b” ”empty”
2) “foo” ”and” ”bar”
3) “foo:and:bar”
4) “f” “empty” “:and:b”
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
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”);
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);
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
Object Common Methods
➢ Equals
Integer x=10;
Integer y=10;
System.out.println(x.equals(y));//true
x=null;
x.equals(y);
---
NPE
//Instead
System.out.println(Objects.equals(null, y));
Object Common Methods
➢ HashCode
@Override public int hashCode(){
return Objects.hashCode(rollno,fname,lname);
}
➢ toString
@Override public String toString(){
return MoreObjects.toStringHelper(this)
.add("First Name", this.fname)
.add("Last Name", this.lname)
.add("Roll No", this.rollno)
.toString();
}
Object Common Methods
➢ Compare/compareTo
public int compareTo(Person other) {
int cmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
return cmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
return cmp;
}
return Integer.compare(zipCode, other.zipCode);
}
Object Common Methods
➢ Comparison Chain Guava
public int compareTo(Foo that) {
return ComparisonChain.start()
.compare(this.aString, that.aString)
.compare(this.anInt, that.anInt)
.compare(this.anEnum,
that.anEnum,Ordering.natural().nullsLast())
.result();
}
Caching
Cache
Application
Caching
➢ Guava has on heap key value cache
➢ Implementation is thread safe
➢ No support for distributed caching – Consider
memcached instead
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.
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
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)
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);
}
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);
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)
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()
Caching
➢ Refreshing
➢ Refreshing is not same as eviction
➢ Refreshing a key loads a new value for the key
➢ LoadingCache.refresh(K)
References
➢ https://github.com/google/guava/wiki
➢ http://mvnrepository.com/artifact/com.google.guava
➢ Effective Java : Joshua Bloch
➢ Wikipedia : Caching

Weitere ähnliche Inhalte

Was ist angesagt?

Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Ontico
 
How containers helped a SaaS startup be developed and go live
How containers helped a SaaS startup be developed and go liveHow containers helped a SaaS startup be developed and go live
How containers helped a SaaS startup be developed and go liveRamon Navarro
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014Ramon Navarro
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Alexey Lesovsky
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by pythonwonyong hwang
 
My sql monitoring cu沙龙
My sql monitoring cu沙龙My sql monitoring cu沙龙
My sql monitoring cu沙龙colderboy17
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server Masahiro Nagano
 
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksHow to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksCarlos Sanchez
 
WiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-TreeWiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-TreeSveta Smirnova
 
Elasticsearch und die Java-Welt
Elasticsearch und die Java-WeltElasticsearch und die Java-Welt
Elasticsearch und die Java-WeltFlorian Hopf
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeWim Godden
 
DDoS: Practical Survival Guide
DDoS: Practical Survival GuideDDoS: Practical Survival Guide
DDoS: Practical Survival GuideHLL
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...DevOps_Fest
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?MongoDB
 
ニコニコ動画を検索可能にしてみよう
ニコニコ動画を検索可能にしてみようニコニコ動画を検索可能にしてみよう
ニコニコ動画を検索可能にしてみようgenta kaneyama
 
Plone 5 and machine learning
Plone 5 and machine learningPlone 5 and machine learning
Plone 5 and machine learningRamon Navarro
 

Was ist angesagt? (20)

Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
 
How containers helped a SaaS startup be developed and go live
How containers helped a SaaS startup be developed and go liveHow containers helped a SaaS startup be developed and go live
How containers helped a SaaS startup be developed and go live
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014
 
Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.Deep dive into PostgreSQL statistics.
Deep dive into PostgreSQL statistics.
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 
My sql monitoring cu沙龙
My sql monitoring cu沙龙My sql monitoring cu沙龙
My sql monitoring cu沙龙
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server
 
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksHow to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
 
WiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-TreeWiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-Tree
 
Puppet fundamentals
Puppet fundamentalsPuppet fundamentals
Puppet fundamentals
 
Week6
Week6Week6
Week6
 
Elasticsearch und die Java-Welt
Elasticsearch und die Java-WeltElasticsearch und die Java-Welt
Elasticsearch und die Java-Welt
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
 
DDoS: Practical Survival Guide
DDoS: Practical Survival GuideDDoS: Practical Survival Guide
DDoS: Practical Survival Guide
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
DevOps Fest 2019. Сергей Марченко. Terraform: a novel about modules, provider...
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?
 
ニコニコ動画を検索可能にしてみよう
ニコニコ動画を検索可能にしてみようニコニコ動画を検索可能にしてみよう
ニコニコ動画を検索可能にしてみよう
 
My Old Friend Malloc
My Old Friend MallocMy Old Friend Malloc
My Old Friend Malloc
 
Plone 5 and machine learning
Plone 5 and machine learningPlone 5 and machine learning
Plone 5 and machine learning
 

Ähnlich wie Gauva

Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaCharles Nutter
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandCharles Nutter
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Mark Niebergall
 
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?Dmitri Shiryaev
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGSylvain Wallez
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
How I hack on puppet modules
How I hack on puppet modulesHow I hack on puppet modules
How I hack on puppet modulesKris Buytaert
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012mumrah
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Audit your reactive applications
Audit your reactive applicationsAudit your reactive applications
Audit your reactive applicationsOCTO Technology
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
Practical Pig and PigUnit (Michael Noll, Verisign)
Practical Pig and PigUnit (Michael Noll, Verisign)Practical Pig and PigUnit (Michael Noll, Verisign)
Practical Pig and PigUnit (Michael Noll, Verisign)Swiss Big Data User Group
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediZeroTurnaround
 

Ähnlich wie Gauva (20)

Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Guava
GuavaGuava
Guava
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM Wonderland
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUG
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
How I hack on puppet modules
How I hack on puppet modulesHow I hack on puppet modules
How I hack on puppet modules
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Audit your reactive applications
Audit your reactive applicationsAudit your reactive applications
Audit your reactive applications
 
HotSpotコトハジメ
HotSpotコトハジメHotSpotコトハジメ
HotSpotコトハジメ
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Practical Pig and PigUnit (Michael Noll, Verisign)
Practical Pig and PigUnit (Michael Noll, Verisign)Practical Pig and PigUnit (Michael Noll, Verisign)
Practical Pig and PigUnit (Michael Noll, Verisign)
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 

Kürzlich hochgeladen

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Gauva

  • 1. Gauva – Extension to Java JUG Hyderabad Rohit Vaidya
  • 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
  • 12. Strings List<String> fruits = Arrays.asList("Guava","Apple","Mango",null,"Pears"); String fruit = Joiner.on(" ").useForNull("Banana").join(fruits); System.out.println(fruit); --- Guava Apple Mango Banana Pears
  • 13. Strings ➢ Splitter - Quiz String[] str="foo:and:boo".split(":"); for(String s:str) if(s.isEmpty()) System.out.print("empty "); else System.out.print(s+ “ “); --- 1) “empty” ”foo” ”and” ”boo” ”empty” 2) “foo” ”and” ”bar” 3) “foo:and:bar”
  • 14. Strings Quiz continued: String[] str="foo:and:boo".split("o"); for(String s:str) if(s.isEmpty()) System.out.print("empty "); else System.out.print(s+ “ “); --- 1) “empty” ”f” ”empty” ”:and:b” ”empty” 2) “foo” ”and” ”bar” 3) “foo:and:bar” 4) “f” “empty” “:and:b”
  • 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
  • 19. Object Common Methods ➢ Equals Integer x=10; Integer y=10; System.out.println(x.equals(y));//true x=null; x.equals(y); --- NPE //Instead System.out.println(Objects.equals(null, y));
  • 20. Object Common Methods ➢ HashCode @Override public int hashCode(){ return Objects.hashCode(rollno,fname,lname); } ➢ toString @Override public String toString(){ return MoreObjects.toStringHelper(this) .add("First Name", this.fname) .add("Last Name", this.lname) .add("Roll No", this.rollno) .toString(); }
  • 21. Object Common Methods ➢ Compare/compareTo public int compareTo(Person other) { int cmp = lastName.compareTo(other.lastName); if (cmp != 0) { return cmp; } cmp = firstName.compareTo(other.firstName); if (cmp != 0) { return cmp; } return Integer.compare(zipCode, other.zipCode); }
  • 22. Object Common Methods ➢ Comparison Chain Guava public int compareTo(Foo that) { return ComparisonChain.start() .compare(this.aString, that.aString) .compare(this.anInt, that.anInt) .compare(this.anEnum, that.anEnum,Ordering.natural().nullsLast()) .result(); }
  • 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)

Hinweis der Redaktion

  1. 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
  2. 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
  3. Explain the builder design pattern. Item 2 Effective Java Difficult to appreciate the beauty of fluid pattern if you don&amp;apos;t understand Builder Design Pattern.
  4. Mention about the number of tests in guava
  5. Pure Java example can be discussed here on how to do it.
  6. 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
  7. 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
  8. 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&amp;apos;ed if no strong or soft ref to values SoftValues: wraps value in soft ref. Softly ref values are gc&amp;apos;ed based on global LRU manner