Avoid Using Static Variables

Introduction

In this blog post, we will discuss a common issue faced when using static variables in applications, specifically when dealing with multiple cores. We will explore a real-world example, identify the problem, and present the solution that effectively resolved the issue.

The Problem

The application in question deals with multiple apache solr cores, each responsible for handling different types of data requests. A generic update method was designed to manage data updates across these cores based on the request type.

The Generic Method

The generic method follows two main steps:

  1. Assign Current Core to a Static Variable: Based on the request type, the current core is assigned to a static variable.
  2. Update the Data to the Assigned Core: The method updates the data to the core assigned in the first step.

Issue Encountered

A timing issue was observed where sometimes the system attempted to update data to the wrong core. This mismatch was particularly noted when:

The Solution

Modification of the Generic Method

To address this issue, the following changes were made to the generic method:

  1. Pass Request Type as a Parameter: Instead of relying on a static variable, the request type is now passed directly as a parameter to the method.
  2. Remove the Static Variable Assignment: The first step, which involved assigning the current core to a static variable, was eliminated.

Benefits of the Modification

Post-Experience Analysis

Results

Conclusion

This case study highlights the importance of avoiding static variables in scenarios where multiple concurrent processes rely on dynamic assignments. By refactoring the method to take the request type as a parameter, we achieved a more robust and reliable system.

  • Written by

  • Vignesh Nivas Athi Jaganathan
    Technical Lead
  • June 11, 2024
  • 0 mins read

More to explore