Garbage Collection when your system does not have enough memory in your Python App

CK CK 3788 
Created at
Updated at  
1,014 0 0

Garbage collection is an automatic memory management feature in many programming languages that reclaims memory occupied by objects that are no longer referenced by the program. Instead of the programmer explicitly deallocating memory, the garbage collector periodically identifies and deallocates unreachable objects, preventing memory leaks and simplifying memory management.
 

Python employs a garbage collection system primarily based on reference counting, supplemented by a cyclic garbage collector. Reference counting tracks how many references point to each object; when the count reaches zero, the object is immediately deallocated. The cyclic garbage collector detects and reclaims objects involved in reference cycles (where objects mutually refer to each other, preventing their reference counts from reaching zero), preventing memory leaks. This combination ensures automatic memory management, freeing developers from manual memory allocation and deallocation.
 

Below code is tested on CentOS 7 and verified working great when we process big data.

def CHECK_OS():
	import platform
	return platform.system()

def FREE_MEMORY():
    """
    Force the Python garbage collector to release unused memory back to the system.
    """
    import gc
    
    # Run garbage collection
    gc.collect()
    
    # If running on Linux/Unix, attempt to release memory back to the system
    if CHECK_OS().lower() in ['linux', 'darwin']:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        # MALLOC_TRIM(0) releases memory back to the system if possible
        libc.malloc_trim(0)
Tags FREE_MEMORY GC Garbage Collection Facebook X
Comments 0
Similar posts
  1. Why America's Biggest Tech Companies Are Betting on Rust?
    287
  1. A Python Code to get the Server Instance ID for Remote Management
    362
  2. From Local Python Web to Standalone
    2,046
  3. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    320
  4. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    461
  5. Python ML Technologies used for the target Segmentation
    378
  6. Managing WHITE_LIST in FastAPI to Improve the Server Security
    349
  7. A common async example
    972
  8. Milvus and LLM Integration - Very Smart Approach!
    297
  9. Automated API Documentation with PyCharm
    892
  10. How to install python 3.9 alongside python 3.8 on CentOS 7?
    711
  11. How to run Python 3.9 on Mac?
    652
  12. Python Quizs
    501
  13. Automated OpenAPI documentation for a Python Flask API
    1,120
  14. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,030
  15. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  16. Method to maximize full CPU performance with Python
    317
  17. How do I get the maximum available of thread in python?
    990
  18. Using Queue Algorithm with Redis - RPUSH and LPOP
    770
  19. Use cache concept with Redis : Let's do Redis programming with Python
    533
  20. Installing Python 3.8 in a venv environment on CentOS 7
    463
  21. CUDA versus OpenCL
    579
  22. Simple gRPC server based on Python
    396
  23. Python code to convert PDF file to Excel Spreadsheet
    701
  24. Python script to list files on your Google Drive and download one of them
    941
  25. Coinbase Python API - Basic Example
    462
  26. AWS Lambda Code Example based on Python
    333
  27. Python code using GPU on CentOS with AWS
    1,252
  28. Video Scence Detection with PySceneDetect
    2,323
  29. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,446
  30. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    908
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,008
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    262