{"id":308,"date":"2025-06-29T14:36:29","date_gmt":"2025-06-29T14:36:29","guid":{"rendered":"https:\/\/thetestdata.com\/blog\/?p=308"},"modified":"2025-07-16T10:15:48","modified_gmt":"2025-07-16T10:15:48","slug":"what-is-singleton-class-in-java","status":"publish","type":"post","link":"https:\/\/thetestdata.com\/blog\/what-is-singleton-class-in-java\/","title":{"rendered":"What is Singleton Class in java?"},"content":{"rendered":"\n<p>A <strong>singleton class<\/strong> in Java is a class that allows <strong>only one instance<\/strong> to be created throughout the lifetime of an application. It\u2019s a design pattern used when exactly one object is needed to coordinate actions across the system\u2014like a single configuration manager, logger, or database connection pool.<\/p>\n\n\n\n<p><strong>\ud83e\uddf1 Key Characteristics of a Singleton Class<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Private Constructor<\/strong>: Prevents external instantiation.<\/li>\n\n\n\n<li><strong>Static Instance<\/strong>: Holds the single instance of the class.<\/li>\n\n\n\n<li><strong>Public Static Method<\/strong>: Provides global access to the instance.<\/li>\n<\/ol>\n\n\n\n<p>\ud83e\uddea Example: Classic Singleton Implementation<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Singleton class\npublic class Singleton {\n    \/\/ Step 1: Create a private static instance variable\n    private static Singleton instance;\n\n    \/\/ Step 2: Private constructor to prevent instantiation\n    private Singleton() {\n        System.out.println(\"Singleton instance created.\");\n    }\n\n    \/\/ Step 3: Public synchronized method to provide access to the instance\n    public static synchronized Singleton getInstance() {\n        if (instance == null) {\n            instance = new Singleton(); \/\/ Lazy initialization\n        }\n        return instance;\n    }\n\n    \/\/ Example method\n    public void showMessage() {\n        System.out.println(\"Hello from Singleton!\");\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>\ud83e\uddea Test Class to Demonstrate Singleton<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Main {\n    public static void main(String&#91;] args) {\n        \/\/ Get the only object from Singleton class\n        Singleton obj1 = Singleton.getInstance();\n        obj1.showMessage();\n\n        \/\/ Try to get another instance\n        Singleton obj2 = Singleton.getInstance();\n        obj2.showMessage();\n\n        \/\/ Check if both references point to the same object\n        System.out.println(\"Are both instances the same? \" + (obj1 == obj2));\n    }\n}<\/code><\/pre>\n\n\n\n<p>\ud83e\uddfe <strong>Output<\/strong>:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"967\" height=\"130\" src=\"https:\/\/thetestdata.com\/blog\/wp-content\/uploads\/2025\/06\/image-28.png\" alt=\"\" class=\"wp-image-309\" srcset=\"https:\/\/thetestdata.com\/blog\/wp-content\/uploads\/2025\/06\/image-28.png 967w, https:\/\/thetestdata.com\/blog\/wp-content\/uploads\/2025\/06\/image-28-300x40.png 300w, https:\/\/thetestdata.com\/blog\/wp-content\/uploads\/2025\/06\/image-28-768x103.png 768w\" sizes=\"auto, (max-width: 967px) 100vw, 967px\" \/><\/figure>\n\n\n\n<p>Singleton instance created. Hello from Singleton! Hello from Singleton! Are both instances the same? true<\/p>\n\n\n\n<p>This confirms that only <strong>one instance<\/strong> of the class is created and reused.<\/p>\n\n\n\n<p><strong>\ud83e\udde0 Why Use Singleton?<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Resource Sharing<\/strong>: One shared object (e.g., database connection).<\/li>\n\n\n\n<li><strong>Global Access Point<\/strong>: Easy to access from anywhere.<\/li>\n\n\n\n<li><strong>Controlled Access<\/strong>: Centralized control over the instance.<\/li>\n<\/ul>\n\n\n\n<p><strong>\u26a0\ufe0f Caution: Thread Safety<\/strong><\/p>\n\n\n\n<p>In multi-threaded environments, the above implementation can create multiple instances. To fix this, you can:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <strong>synchronized<\/strong> keyword.<\/li>\n\n\n\n<li>Use <strong>double-checked locking<\/strong>.<\/li>\n\n\n\n<li>Use <strong>eager initialization<\/strong>.<\/li>\n\n\n\n<li>Or the most elegant: <strong>Enum Singleton<\/strong> (thread-safe by default).<\/li>\n<\/ul>\n\n\n\n<p><strong>\ud83e\udde9 Real-World Use Case<\/strong><\/p>\n\n\n\n<p>\u201cIn my automation project, I used a Singleton class to manage the WebDriver instance. This ensured that only one browser session was active at a time, avoiding conflicts and saving resources.\u201d<\/p>\n\n\n\n<p>\ud83d\udd27<strong> Step 1: Create the Singleton WebDriver Class<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\n\npublic class DriverManager {\n    private static DriverManager instance = null;\n    private WebDriver driver;\n\n    \/\/ Private constructor to prevent instantiation\n    private DriverManager() {\n        System.setProperty(\"webdriver.chrome.driver\", \"path\/to\/chromedriver\");\n        driver = new ChromeDriver();\n        driver.manage().window().maximize();\n    }\n\n    \/\/ Public method to provide access to the instance\n    public static DriverManager getInstance() {\n        if (instance == null) {\n            instance = new DriverManager();\n        }\n        return instance;\n    }\n\n    public WebDriver getDriver() {\n        return driver;\n    }\n\n    public void quitDriver() {\n        if (driver != null) {\n            driver.quit();\n            driver = null;\n            instance = null;\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p>\ud83e\uddea<strong> Step 2: Use It in Your Test Class<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.openqa.selenium.WebDriver;\n\npublic class TestExample {\n    public static void main(String&#91;] args) {\n        WebDriver driver = DriverManager.getInstance().getDriver();\n        driver.get(\"https:\/\/www.example.com\");\n\n        \/\/ Perform your test steps here...\n\n        \/\/ Quit the driver after test\n        DriverManager.getInstance().quitDriver();\n    }\n}<\/code><\/pre>\n\n\n\n<p>\u2705 Benefits<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ensures <strong>only one browser instance<\/strong> is active.<\/li>\n\n\n\n<li>Prevents <strong>resource leaks<\/strong> and <strong>driver conflicts<\/strong>.<\/li>\n\n\n\n<li>Makes your framework <strong>cleaner and more maintainable<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn what a Singleton class is in Java. Discover how it ensures a single instance throughout the application, promoting controlled access and memory efficiency<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"site-container-style":"default","site-container-layout":"default","site-sidebar-layout":"default","disable-article-header":"default","disable-site-header":"default","disable-site-footer":"default","disable-content-area-spacing":"default","footnotes":""},"categories":[17],"tags":[],"class_list":["post-308","post","type-post","status-publish","format-standard","hentry","category-java-interview-questions"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts\/308","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/comments?post=308"}],"version-history":[{"count":2,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts\/308\/revisions"}],"predecessor-version":[{"id":433,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts\/308\/revisions\/433"}],"wp:attachment":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/media?parent=308"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/categories?post=308"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/tags?post=308"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}