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
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

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • JVM Memory Architecture and GC Algorithm Basics
  • All You Need To Know About Garbage Collection in Java
  • Java Memory Management
  • Garbage Collection in Java (JVM)

Trending

  • Comparing Axios, Fetch, and Angular HttpClient for Data Fetching in JavaScript
  • Contexts in Go: A Comprehensive Guide
  • How To Perform JSON Schema Validation in API Testing Using Rest-Assured Java
  • The Rise of Kubernetes: Reshaping the Future of Application Development
  1. DZone
  2. Coding
  3. Java
  4. Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case

Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case

The approach to identifying and rectifying specific pain points, such as object churn and memory leaks, is commendable, specifically for mobile devices.

By 
Murat Gungor user avatar
Murat Gungor
DZone Core CORE ·
Jun. 27, 24 · Tutorial
Like (1)
Save
Tweet
Share
2.5K Views

Join the DZone community and get the full member experience.

Join For Free

Memory management issues and optimizing code for efficiency are critical aspects of software development, especially in resource-constrained environments like mobile devices.

Glide stands out as a remarkable library tailored for efficiently displaying images on Android devices and beyond. With its robust caching mechanism, handling caching to disk or memory becomes almost effortless. Our ongoing project, Guzel Board, endeavors to deliver a straightforward and cost-effective digital signage solution. Designed to operate seamlessly on HDMI Android TVs or TV sticks like Chromecast and Amazon Fire TV sticks, Guzel Board confronts the challenge of limited memory resources inherent in such devices.

Insidious Memory Leak

Given the expectation for extended operational durations without frequent restarts, the Guzel Board aims to sustain uninterrupted performance over months, especially considering that these displays are often mounted in elevated locations, rendering regular oversight impractical. However, our initial implementation fell short of this goal, as we noticed a gradual increase in memory consumption during runtime despite the absence of any reported memory leaks according to Android Studio Memory Profiler.

Handling Broken Image Link

The crux of the issue lies in the intricacies of Glide's behavior: when attempting to load an image that is unavailable or encountering a loss of internet connectivity, it becomes crucial to incorporate appropriate error handling mechanisms. In our case, the challenge arose from expired links to assets hosted on Amazon S3 servers.

Unfortunately, our initial approach to implementing error handling, while seemingly straightforward, inadvertently exacerbated the problem. Each instance of a failed image retrieval triggered the creation of a new RequestListener.  Over time, this led to a proliferation of objects, each retaining references that evaded garbage collection efforts by the system.

Navigating this issue proved to be a perplexing endeavor. Unlike a straightforward compilation error, the consequences of this oversight manifested in the form of a silent degradation in application performance. However, through diligent investigation, we ultimately pinpointed the root cause of our memory bloat.

The wrong way of adding a listener is the following: why, since each time any media fails, it will create a new RequestListener by that time. This creates many objects, and each has references, and GC (Garbage Collector) cannot wipe them out.  


Java
 
Glide.with(this)
	.load(aMedia.path)                      
	.addListener(new RequestListener<Drawable>() {
		@Override
		public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
			//Do something - show some image to engage the user 
			return false;
		}
		@Override
		public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
			return false;
		}
	})
	.into(imageView);


It’s the Little Details That Are Vital

In the link RequestListener link, it says:

"It is recommended to create a single instance per activity/fragment rather than instantiate a new object for each call to Glide.load() to avoid object churn."  

The right way of doing this is to create a single RequestListener object and pass it to addListener. This way you will have only one instance all the time during an activity.

Java
 
Glide.with(this)
	.load(path to your image)                      
	.addListener(glideRequestListener) // BE CAREFUL                    
	.into(imageView);
	
	
private final RequestListener<Drawable> glideRequestListener = new RequestListener<Drawable>()
{  
	@Override
	public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
		
		e.logRootCauses("GLIDE PROBLEM");

		// Load error image from URL
		Glide.with(MainActivity.this)
				.load(unsplashUrl) // Provide the URL for the error image here
				.into(imageView4LoadImageViaGlide); 
		return false;
	}
	@Override
	public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {		 
		return false;
	}
};


Following this realization, we embarked on a broader initiative to optimize our codebase, addressing similar inefficiencies wherever they surfaced. For instance, we identified scenarios where excessive creation of Runnable objects occurred each time a particular function was invoked. By relocating such operations outside the function scope, we effectively mitigated object churn and averted potential memory leaks. In essence, this strategy enabled us to streamline memory usage, retaining only essential components in memory while discarding extraneous objects.

If you are running this kind of code many times, try extracting a member variable to avoid many object creations. 

Java
 
runOnUiThread(new Runnable() { .... });


Conclusion

Addressing memory management issues and optimizing code for efficiency is a critical aspect of software development, especially in resource-constrained environments like mobile devices. The approach to identifying and rectifying specific pain points, such as object churn and memory leaks, is commendable.

One additional recommendation I would offer is to consider implementing proactive monitoring and profiling tools as part of your development workflow. Utilizing tools like Android Studio's Memory Profiler or third-party solutions can help identify performance bottlenecks and memory-related issues early in the development process. Additionally, incorporating automated testing, particularly for stress testing and memory usage analysis, can provide further assurance of your application's robustness and stability under various conditions.

Overall, your proactive approach to optimizing code and sharing your learnings can undoubtedly benefit others facing similar challenges. Collaboration and knowledge-sharing within the developer community are invaluable in driving continuous improvement and innovation.  

Android Studio garbage collection Glide (API) Object (computer science) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • JVM Memory Architecture and GC Algorithm Basics
  • All You Need To Know About Garbage Collection in Java
  • Java Memory Management
  • Garbage Collection in Java (JVM)

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: