Click here to close now.

Welcome!

Java Authors: Liz McMillan, Pat Romanski, Dan Ristic, Kevin Benedict, Elizabeth White

Related Topics: Java

Java: Article

How To Use JavaSoft References For Caching

How To Use JavaSoft References For Caching

They usually happen during the early hours of the morning, shortly before the code needs to ship: exception errors. . . .

Take the following , for example. Ever seen this before?

Exception in thread "main" java.lang.OutOfMemoryError
at OutMem.main(OutMem.java, Co

In the past, developers didn't have much control over garbage collection or memory management. Java2 has changed that by introducing the java.lang.ref package. The abstract base class Reference is inherited by classes SoftReference, WeakReference and PhantomReference. SoftReferences are well suited for use in applications needing to perform caching. WeakReferences are generally used to canonicalize several references to a single object. PhantomReferences are the "weakest" type of reference and can be used for referents that require additional cleanup after finalization.

In this article I'm going to focus on the SoftReference class and demonstrate how to use it to implement caching.

Creating a SoftReference
SoftReferences are created by passing an object to SoftReference's constructor:

Object obj = new Object();
SoftReference softRef = new SoftReference(obj);
obj = null;

Please note the setting of obj to null. This is critical to proper performance of the garbage collector. A problem arises if no other stack frame places a value at that location - the garbage collector will still believe that an active (strong) reference to the object exists.

Retrieving a Reference
The following code can be used to retrieve a reference to an object:

Object obj2;
obj2 = sr.get();
if (obj2 == null) // GC freed this
sr = new SoftReference(obj2 = new Object());
Two items from the foregoing code are important to note. First, notice that SoftReference is immutable - you must create a new SoftReference that refers to the new referent. Second, the following code may appear to accomplish the same goal:
Object obj2;
obj2 = sr.get();
if (obj2 == null) {
sr = new SoftReference(new Object());
obj2 = sr.get();
}
Hopefully the problem with this code is obvious: the garbage collector could run between the creation of the new Object and the call to get(). obj2 would still be null.

Where would you use a SoftReference? SoftReferences are excellent for use in memory-intensive applications that can benefit from caching. Take, for instance, a user interface such as a button with a picture on it. Typically these are implemented by subclassing Button. The paint method is then usually overridden (see Listing 1).

Reference Queues
Sometimes it may be important to know which references the garbage collector has cleared. Good-natured daemon that it is, the collector will happily place these references into a queue. All you have to do is supply the ReferenceQueue when you create the reference.

ReferenceQueue rq = new ReferenceQueue();
Object o = new Object();
SoftReference sr = new SoftReference(o,rq);
o = null;
Later your program can query the queue by calling the nonblocking method poll. This will return a reclaimed reference or null if the queue is empty. Many cache implementations will loop through the queue during a call placing or retrieving items in the cache. Alternatively, ReferenceQueue provides two versions of the blocking method remove. One blocks indefinitely and the other will return after a timeout. Remove can be used instead of poll by a thread that blocks until items enter the queue, as in our next example.

Using SoftReferences to Implement a Cache
Programs can usually increase efficiency by reusing objects that are expensive to create. Objects such as database connections and distributed objects - like those in RMI and CORBA - incur significant overhead in object creation, as well as create and destroy network connections. While caching is nothing new, SoftReferences allow us to grow the cache almost without bound. The guarantee that the garbage collector gives us is that it will always clear SoftReferences before throwing the dreaded OutOfMemoryError.

Listing 2 provides a class that can store instances of an object until they're needed. The cache's get method will return an object if one exists in the queue. If not, null will be returned and the program will need to create a new instance. When the program has finished using an instance, it simply passes the object to the cache's put method, where it will be available for future use.

The inner class Remover subclasses Thread and waits on the ReferenceQueue. To test the program, I wrote a cruel driver that attempts to flood the cache to ensure that items will be dropped rather than exhaust memory.

SoftCache sc = new SoftCache();
for (int i=0; i < 1000000; i++) {
sc.put(new Object());
if (i%10 == 0) {
System.gc();
Thread.yield();
System.out.println("i=" + i);
}
}
This is a bit like offering the cache a sip of water from a fire hose but it does the trick. To simulate the out-of-memory condition, an explicit call to gc() was added as well as a yield() to give the cache's Remover thread a chance to delete items from its vector. To coerce the garbage collector into removing some of the reference, I set the maximum heap size to a low value. Under Linux (kernel 2.2.12, JDK 1.2.2-RC3) the maximum heap size was set to 360K. The initial heap size defaults to over one megabyte, so it must be set as well. These options are set via Java's mysterious new -X parameters:

java -Xmx360k -Xms263k AbuseCache

Conclusion
Hopefully this article has demonstrated some techniques that can be useful to satiate an application's voracious appetite for memory. SoftReferences provide a way for the virtual machine to release memory held by large or infrequently used objects. Consider subclassing SoftCache to create new instances of an object you use. It could then also ensure that only objects of the proper type can be added.

More Stories By Darren Shields

Darren Shields, a team leader with The Technical Resource Connection, Inc., at the time this article was written, has extensive experience with CORBA, Java, C++, Linux and Open Source Software. Darren earned his bachelor's degree in computer science from the University of West Florida.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Ciqada will exhibit at SYS-CON's @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Ciqada™ makes it easy to connect your products to the Internet. By integrating key components - hardware, servers, dashboards, and mobile apps - into an easy-to-use, configurable system, your products can quickly and securely join the internet of things. With remote monitoring, control, and alert messaging capability, you will meet your customers' needs of tomorrow - today! Ciqada. Let your products take flight. For more inform...
SYS-CON Events announced today that GENBAND, a leading developer of real time communications software solutions, has been named “Silver Sponsor” of SYS-CON's WebRTC Summit, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. The GENBAND team will be on hand to demonstrate their newest product, Kandy. Kandy is a communications Platform-as-a-Service (PaaS) that enables companies to seamlessly integrate more human communications into their Web and mobile applications - creating more engaging experiences for their customers and boosting collaboration and productiv...
SYS-CON Events announced today that BroadSoft, the leading global provider of Unified Communications and Collaboration (UCC) services to operators worldwide, has been named “Gold Sponsor” of SYS-CON's WebRTC Summit, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. BroadSoft is the leading provider of software and services that enable mobile, fixed-line and cable service providers to offer Unified Communications over their Internet Protocol networks. The Company’s core communications platform enables the delivery of a range of enterprise and consumer calling...
VoxImplant has announced full WebRTC support in the newest versions of its Android SDK and iOS SDK. The updated SDKs, which enable audio and video calls on mobile devices, are now compatible with the WebRTC standard to allow any mobile app to communicate with WebRTC-enabled browsers, including Google Chrome, Mozilla Firefox, Opera, and, when available, Microsoft Spartan. The WebRTC-updated SDKs represent VoxImplant's continued leadership in simplifying the development of real-time communications (RTC) services for app developers. VoxImplant (built by Zingaya, the real-time communication servi...
The IoT Bootcamp is coming to Cloud Expo | @ThingsExpo on June 9-10 at the Javits Center in New York. Instructor. Registration is now available at http://iotbootcamp.sys-con.com/ Instructor Janakiram MSV previously taught the famously successful Multi-Cloud Bootcamp at Cloud Expo | @ThingsExpo in November in Santa Clara. Now he is expanding the focus to Janakiram is the founder and CTO of Get Cloud Ready Consulting, a niche Cloud Migration and Cloud Operations firm that recently got acquired by Aditi Technologies. He is a Microsoft Regional Director for Hyderabad, India, and one of the f...
SYS-CON Events announced today that Optimal Design, an Internet of Things solution provider, will exhibit at SYS-CON's Internet of @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Optimal Design is an award winning product development firm offering industrial design and engineering services to the consumer, medical, and defense markets.
SYS-CON Events announced today that Vicom Computer Services, Inc., a provider of technology and service solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. They are located at booth #427. Vicom Computer Services, Inc. is a progressive leader in the technology industry for over 30 years. Headquartered in the NY Metropolitan area. Vicom provides products and services based on today’s requirements around Unified Networks, Cloud Computing strategies, Virtualization around Software defined Data Ce...
What exactly is a cognitive application? In her session at 16th Cloud Expo, Ashley Hathaway, Product Manager at IBM Watson, will look at the services being offered by the IBM Watson Developer Cloud and what that means for developers and Big Data. She'll explore how IBM Watson and its partnerships will continue to grow and help define what it means to be a cognitive service, as well as take a look at the offerings on Bluemix. She will also check out how Watson and the Alchemy API team up to offer disruptive APIs to developers.
The 17th International Cloud Expo has announced that its Call for Papers is open. 17th International Cloud Expo, to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, APM, APIs, Microservices, Security, Big Data, Internet of Things, DevOps and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal today!
With IoT exploding, massive data will transform businesses with opportunities to monetize almost anything that can be measured. In this C-Level Roundtable Discussion at @ThingsExpo, Brendan O’Brien, Aria Systems Co-founder and Chief Evangelist, will lead an expert panel of consultants, thought leaders and practitioners who will look at these new monetization trends, discuss the implications, and detail lessons learned from their collective experience. Finally, the panel will point the way forward for enterprises who wish to leverage the resulting complex recurring revenue models, adding valu...
How is unified communications transforming the way businesses operate? In his session at WebRTC Summit, Arvind Rangarajan, Director of Product Marketing at BroadSoft, will discuss how to extend unified communications experience outside the enterprise through WebRTC. He will also review use cases across different industry verticals. Arvind Rangarajan is Director, Product Marketing at BroadSoft. He has over 19 years of experience in the telecommunications industry in various roles such as Software Development, Product Management and Product Marketing, applied across Wireless, Unified Communic...
Buzzword alert: Microservices and IoT at a DevOps conference? What could possibly go wrong? Join this panel of experts as they peel away the buzz and discuss the important architectural principles behind implementing IoT solutions for the enterprise. As remote IoT devices and sensors become increasingly intelligent, they become part of our distributed cloud environment, and we must architect and code accordingly. At the very least, you’ll have no problem filling in your buzzword bingo cards.
Internet of Things (IoT) will be a hybrid ecosystem of diverse devices and sensors collaborating with operational and enterprise systems to create the next big application. In their session at @ThingsExpo, Bramh Gupta, founder and CEO of robomq.io, and Fred Yatzeck, principal architect leading product development at robomq.io, will discuss how choosing the right middleware and integration strategy from the get-go will enable IoT solution developers to adapt and grow with the industry, while at the same time reduce Time to Market (TTM) by using plug and play capabilities offered by a robust I...
@ThingsExpo has been named the Top 5 Most Influential Internet of Things Brand by Onalytica in the ‘The Internet of Things Landscape 2015: Top 100 Individuals and Brands.' Onalytica analyzed Twitter conversations around the #IoT debate to uncover the most influential brands and individuals driving the conversation. Onalytica captured data from 56,224 users. The PageRank based methodology they use to extract influencers on a particular topic (tweets mentioning #InternetofThings or #IoT in this case) takes into account the number and quality of contextual references that a user receives.
SYS-CON Events announced today that Dyn, the worldwide leader in Internet Performance, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Dyn is a cloud-based Internet Performance company. Dyn helps companies monitor, control, and optimize online infrastructure for an exceptional end-user experience. Through a world-class network and unrivaled, objective intelligence into Internet conditions, Dyn ensures traffic gets delivered faster, safer, and more reliably than ever.
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
The WebRTC Summit 2015 New York, to be held June 9-11, 2015, at the Javits Center in New York, NY, announces that its Call for Papers is open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 16th International Cloud Expo, @ThingsExpo, Big Data Expo, and DevOps Summit.
As Marc Andreessen says software is eating the world. Everything is rapidly moving toward being software-defined – from our phones and cars through our washing machines to the datacenter. However, there are larger challenges when implementing software defined on a larger scale - when building software defined infrastructure. In his session at 16th Cloud Expo, Boyan Ivanov, CEO of StorPool, will provide some practical insights on what, how and why when implementing "software-defined" in the datacenter.
While not quite mainstream yet, WebRTC is starting to gain ground with Carriers, Enterprises and Independent Software Vendors (ISV’s) alike. WebRTC makes it easy for developers to add audio and video communications into their applications by using Web browsers as their platform. But like any market, every customer engagement has unique requirements, as well as constraints. And of course, one size does not fit all. In her session at WebRTC Summit, Dr. Natasha Tamaskar, Vice President, Head of Cloud and Mobile Strategy at GENBAND, will explore what is needed to take a real time communications ...