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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

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

  • Designing for Sustainability: The Rise of Green Software
  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  • Optimizing Software Performance for High-Impact Asset Management Systems
  • Designing AI Multi-Agent Systems in Java
  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
Likes (2)
Comment
Save
Tweet
Share
4.2K 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
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!