How to Create a Singleton Class in Groovy

A singleton class in Groovy is a class that can only be instantiated one time. Traditionally this task has been accomplished by defining a class that has a private constructor and a method to return the instance of the class. Groovy provides an annotation, @Singleton, which simplifies the process.

To learn how to create a singleton class in Groovy, follow these 3 steps:

  1. Open your text editor and type in the following Groovy statements:
    class Arithmetic {
    	int add (int i, int j) {
    		return i+j;
    println "Result of calling add method: ${Arithmetic.instance.add(10, 20)}"
    // attempt instantiation
    try {
    	def arithmetic=new Arithmetic()	
    catch (RuntimeException e) {
    	println("Runtime exception detected: ${e.message}")
    The program defines a class, Arithmetic, that contains a method named add. Note that the class is declared as a singleton class using the @Singleton annotation. Therefore only one instance of this class can be present in memory at any time. In addition, an instance property is available in order to reference the singleton instance. The add method is called using the instance property. Next, an attempt is made to instantiate the class and therefore create another instance of the class. At runtime, a RuntimeException will be raised. The program catches this exception and displays a message to the console.
  2. Save your file as SingletonClass.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run singleton class script
    The output shows the result of calling the add method using the instance property, followed by the output of the catch block. Therefore, a runtime exception did indeed occur when an attempt was made to instantiate the singleton class.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.