DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Singleton: 6 Ways To Write and Use in Java Programming
  • Simple Sophisticated Object Cache Service Using Azure Redis
  • Scaling Databases With EclipseLink And Redis
  • Cache in Java With LRU Eviction Policy

Trending

  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  1. DZone
  2. Data Engineering
  3. Data
  4. Lazy Loading and Caching Objects With Guava

Lazy Loading and Caching Objects With Guava

Lazy loading and caching are powerful performance tools, but they can be implemented poorly. Here's how you can pull them off in Java using Google's Guava.

By 
Bill O'Neil user avatar
Bill O'Neil
·
Sep. 11, 17 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
13.4K Views

Join the DZone community and get the full member experience.

Join For Free

Lazy loading and caching are extremely useful tools in the developer toolbox, but like most tools, they can be often overused/abused — so use them sparingly. Lazy loading can be useful when creating a singleton with any variety of double-checked locking, static holder classes, enum singleton patterns, etc. Lazy loading is also great for expensive operations that you only need to handle some of the time. Hibernate heavily utilizes lazy loading. Lazy loading can either be request scoped or in a more global scope. Google's Guava provides an extremely convenient way to create lazy loaded values as well as caching individual values with or without an expiration.

Supplier

We will be using a very simple "hello world" Supplier that will log every time it is called.

public static String helloWorldSupplier() {
    log.info("supplying");
    return "hello world";
}

 View on GitHub

Suppliers.memoize

Suppliers.memoize is a simple method that takes a Supplier and returns a new Supplier that caches the value returned from the supplied Supplier.get() method. This convenient helper allows us to turn any Supplier into a lazily loaded cached value. The returned Supplier is thread-safe, backed with double checked locking and volatile fields. It even allows the original Supplier to be garbage collected once it has been called. If you are utilizing this pattern for code that is not multi-threaded, it might be useful to make a non thread-safe version.

log.info("Memoized");
Supplier memoized = Suppliers.memoize(SuppliersExamples::helloWorldSupplier);
log.info(memoized.get());
log.info(memoized.get());

 View on GitHub


2017-09-06 08:50:58.069 [main] INFO  c.s.e.common.SuppliersExamples - Memoized
2017-09-06 08:50:58.156 [main] INFO  c.s.e.common.SuppliersExamples - supplying
2017-09-06 08:50:58.157 [main] INFO  c.s.e.common.SuppliersExamples - hello world
2017-09-06 08:50:58.157 [main] INFO  c.s.e.common.SuppliersExamples - hello world


Suppliers.memoizeWithExpiration

Suppliers.memoizeWithExpiration is also straightforward. It allows us to memoize a value from a given Supplier but have it update any time we exceed the expiration time. This is a great caching mechanism for any data you know changes infrequently. A minor drawback is if the operation is expensive, you may see a hiccup every time the object needs to be reloaded. Oftentimes, though, this is not a major concern. If it is an issue, you can investigate refreshing the object asynchronously with a background thread. 

Suppliers.memoizeWithExpiration is used to cache the scraped results for our HTML/CSS Themes page and can be seen in Web scraping in Java with jsoup and OkHttp.

log.info("Memoized with Expiration");
Supplier memoizedExpiring = Suppliers.memoizeWithExpiration(
    SuppliersExamples::helloWorldSupplier, 50, TimeUnit.MILLISECONDS);
log.info(memoizedExpiring.get());
log.info(memoizedExpiring.get());
log.info("sleeping");
TimeUnit.MILLISECONDS.sleep(100);
log.info(memoizedExpiring.get());
log.info(memoizedExpiring.get());
log.info("sleeping");
TimeUnit.MILLISECONDS.sleep(100);
log.info(memoizedExpiring.get());
log.info(memoizedExpiring.get());

 View on GitHub


2017-09-06 08:50:58.157 [main] INFO  c.s.e.common.SuppliersExamples - Memoized with Expiration
2017-09-06 08:50:58.171 [main] INFO  c.s.e.common.SuppliersExamples - supplying
2017-09-06 08:50:58.171 [main] INFO  c.s.e.common.SuppliersExamples - hello world
2017-09-06 08:50:58.171 [main] INFO  c.s.e.common.SuppliersExamples - hello world
2017-09-06 08:50:58.171 [main] INFO  c.s.e.common.SuppliersExamples - sleeping
2017-09-06 08:50:58.272 [main] INFO  c.s.e.common.SuppliersExamples - supplying
2017-09-06 08:50:58.272 [main] INFO  c.s.e.common.SuppliersExamples - hello world
2017-09-06 08:50:58.272 [main] INFO  c.s.e.common.SuppliersExamples - hello world
2017-09-06 08:50:58.272 [main] INFO  c.s.e.common.SuppliersExamples - sleeping
2017-09-06 08:50:58.377 [main] INFO  c.s.e.common.SuppliersExamples - supplying
2017-09-06 08:50:58.377 [main] INFO  c.s.e.common.SuppliersExamples - hello world
2017-09-06 08:50:58.377 [main] INFO  c.s.e.common.SuppliersExamples - hello world
Lazy loading Cache (computing) Object (computer science) Google Guava

Published at DZone with permission of Bill O'Neil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Singleton: 6 Ways To Write and Use in Java Programming
  • Simple Sophisticated Object Cache Service Using Azure Redis
  • Scaling Databases With EclipseLink And Redis
  • Cache in Java With LRU Eviction Policy

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!