ποΈ Creational Patterns, Thread Concurrency & Enterprise Decoupling
In enterprise API automation suites spanning dozens of microservices, managing runtime infrastructure, environment configurations, authentication tokens, and client instances requires disciplined creational architecture. Relying on naive public constructors or mutable static variables scatters configuration logic across test cases, wastes memory through redundant object instantiation, and introduces severe race conditions when executing in parallel. Creational Design Patternsβspecifically the Singleton and Factory patternsβprovide the foundational blueprints for scalable REST Assured frameworks. By implementing Thread-Safe Singletons (via the Bill Pugh Holder or Double-Checked Locking idioms) for global resources such as property managers and token caches, and pairing them with Factory Methods and Abstract Factories for dynamic RequestSpecification and ServiceClient instantiation, automation engineers ensure single-point resource governance, zero memory leakage, and complete thread isolation across distributed CI/CD pipelines.
CREATIONAL DESIGN PATTERNS IN REST ASSURED AUTOMATION ARCHITECTURE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SINGLETON LAYER: ConfigManager.getInstance() β
β β’ Reads application.properties / System.getProperty("env") once per JVM run β
β β’ Holds immutable global settings: Base URLs, Database URLs, Global Timeouts, Proxy settings β
β β’ Thread-safe: Bill Pugh Holder or Double-Checked Locking prevents duplicate initializations β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Supplies configuration data)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FACTORY LAYER: ClientFactory & SpecificationFactory β
β βββ 1. RequestSpecFactory.getSpec(ServiceType.STUDENT) β
β β β’ Injects Base URI, Content-Type, Headers, and Correlation IDs β
β βββ 2. ServiceClientFactory.getClient(ServiceType.BILLING) β
β β β’ Instantiates and returns concrete Service Client (BillingClient, StudentClient, etc.) β
β βββ 3. TokenFactory.getBearerToken(Role.ADMIN) β
β β’ Manages M2M OAuth2 tokens per user role β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β WORKER THREAD-1 (Student Test Execution) β β WORKER THREAD-2 (Billing Test Execution) β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ Calls: ClientFactory.getStudentClient() β β β’ Calls: ClientFactory.getBillingClient() β
β β’ Uses Thread-Isolated Specification β β β’ Uses Thread-Isolated Specification β
β β’ Dispatches: GET /v1/students/STU-88219 β β β’ Dispatches: POST /v1/billing/invoices β
β [Shared Config, Isolated HTTP Sockets] β β [Shared Config, Isolated HTTP Sockets] β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
ConfigManager. Ensures lazy initialization, thread safety without synchronization overhead, and automatic environment property ingestion.
package com.nikita.restassured.patterns.singleton;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigManager {
private final Properties properties = new Properties();
// 1. Private constructor prevents instantiation from other classes
private ConfigManager() {
String environment = System.getProperty("env", "staging").toLowerCase();
String propFileName = "config/" + environment + ".properties";
try (InputStream input = getClass().getClassLoader().getResourceAsStream(propFileName)) {
if (input == null) {
// Fallback to default application.properties if environment file is not found
InputStream defaultInput = getClass().getClassLoader().getResourceAsStream("config/application.properties");
if (defaultInput != null) {
properties.load(defaultInput);
} else {
throw new RuntimeException("Unable to locate configuration file: " + propFileName);
}
} else {
properties.load(input);
}
System.out.println("[*] ConfigManager initialized for environment: [" + environment.toUpperCase() + "]");
} catch (IOException e) {
throw new RuntimeException("Failed to load configuration properties", e);
}
}
// 2. Static inner helper class: Loaded into memory ONLY when getInstance() is called
private static class BillPughSingletonHolder {
private static final ConfigManager INSTANCE = new ConfigManager();
}
// 3. Global access point: Thread-safe, lazy, and synchronization-free
public static ConfigManager getInstance() {
return BillPughSingletonHolder.INSTANCE;
}
// Public property getters
public String getBaseUrl() {
return properties.getProperty("api.base.url", "https://staging-api.nikita-infotech.com");
}
public String getAuthServerUrl() {
return properties.getProperty("auth.server.url", "https://auth.nikita-infotech.com");
}
public int getTimeoutMs() {
return Integer.parseInt(properties.getProperty("api.timeout.ms", "5000"));
}
public boolean isLoggingEnabled() {
return Boolean.parseBoolean(properties.getProperty("api.logging.enabled", "true"));
}
}
TokenCache. Demonstrates thread-safe token renewal, time-to-live evaluation, and synchronization only during cache misses.
package com.nikita.restassured.patterns.singleton;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import java.time.Instant;
public class TokenCache {
// Volatile variable guarantees memory visibility across threads
private static volatile TokenCache instance;
private String cachedToken;
private Instant expiryTime = Instant.MIN;
// Private constructor
private TokenCache() {}
// Double-checked locking singleton factory method
public static TokenCache getInstance() {
if (instance == null) { // First check (no lock)
synchronized (TokenCache.class) {
if (instance == null) { // Second check (with lock)
instance = new TokenCache();
}
}
}
return instance;
}
/**
* Thread-safe access token retrieval with automated refresh
*/
public synchronized String getValidToken() {
// Refresh token 30 seconds before expiration
if (cachedToken == null || Instant.now().isAfter(expiryTime.minusSeconds(30))) {
refreshToken();
}
return cachedToken;
}
private void refreshToken() {
System.out.println("[*] TokenCache: Fetching fresh Bearer token from authorization server...");
String authUrl = ConfigManager.getInstance().getAuthServerUrl();
String token = RestAssured.given()
.baseUri(authUrl)
.contentType(ContentType.URLENC)
.formParam("grant_type", "client_credentials")
.formParam("client_id", "automation-worker")
.formParam("client_secret", "SecretPass#2026")
.when()
.post("/oauth/v2/token")
.then()
.statusCode(200)
.extract()
.path("access_token");
this.cachedToken = token;
this.expiryTime = Instant.now().plusSeconds(3600); // 1-hour validity
System.out.println("[+] TokenCache: Fresh token acquired successfully.");
}
}
RequestSpecification objects for different microservices (Student, Payment, Auth, Telemetry) into a single decoupled factory.
package com.nikita.restassured.patterns.factory;
import com.nikita.restassured.patterns.singleton.ConfigManager;
import com.nikita.restassured.patterns.singleton.TokenCache;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.UUID;
public class RequestSpecFactory {
public enum ServiceType {
STUDENT,
PAYMENT,
AUTH,
TELEMETRY
}
/**
* Factory method creating tailored RequestSpecification based on target service type
*/
public static RequestSpecification createSpec(ServiceType service) {
String baseUrl = ConfigManager.getInstance().getBaseUrl();
RequestSpecBuilder builder = new RequestSpecBuilder()
.addHeader("X-Correlation-Id", "TRACE-" + UUID.randomUUID().toString().substring(0, 8))
.addHeader("X-Platform", "REST-Assured-Masterclass");
if (ConfigManager.getInstance().isLoggingEnabled()) {
builder.log(LogDetail.URI);
}
switch (service) {
case STUDENT:
return builder
.setBaseUri(baseUrl)
.setBasePath("/v1/students")
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.addHeader("Authorization", "Bearer " + TokenCache.getInstance().getValidToken())
.build();
case PAYMENT:
return builder
.setBaseUri(baseUrl)
.setBasePath("/v1/billing")
.setContentType(ContentType.JSON)
.addHeader("X-Tenant-Key", "MAHARASHTRA_PUNE_FINANCE")
.addHeader("Authorization", "Bearer " + TokenCache.getInstance().getValidToken())
.build();
case AUTH:
return builder
.setBaseUri(ConfigManager.getInstance().getAuthServerUrl())
.setBasePath("/oauth/v2")
.setContentType(ContentType.URLENC.withCharset("UTF-8"))
.build();
case TELEMETRY:
return builder
.setBaseUri(baseUrl)
.setBasePath("/telemetry/v1")
.setContentType(ContentType.JSON)
.addHeader("X-Telemetry-Client", "Automation-Health-Worker")
.build();
default:
throw new IllegalArgumentException("Unsupported ServiceType: " + service);
}
}
}
package com.nikita.restassured.patterns.factory.abstractfactory;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
// 1. ABSTRACT FACTORY INTERFACE
interface EnvironmentSpecFactory {
RequestSpecification createSecureSpec();
RequestSpecification createPublicSpec();
}
// 2. CONCRETE FACTORY A: Local Docker / WireMock Environment
class LocalDockerSpecFactory implements EnvironmentSpecFactory {
private static final String LOCAL_HOST = "http://localhost:8080";
@Override
public RequestSpecification createSecureSpec() {
return new RequestSpecBuilder()
.setBaseUri(LOCAL_HOST)
.setContentType(ContentType.JSON)
.addHeader("X-Mock-Auth", "mocked_local_token")
.build();
}
@Override
public RequestSpecification createPublicSpec() {
return new RequestSpecBuilder()
.setBaseUri(LOCAL_HOST)
.setContentType(ContentType.JSON)
.build();
}
}
// 3. CONCRETE FACTORY B: Cloud Staging Gateway Environment
class CloudStagingSpecFactory implements EnvironmentSpecFactory {
private static final String CLOUD_HOST = "https://staging-api.nikita-infotech.com";
@Override
public RequestSpecification createSecureSpec() {
return new RequestSpecBuilder()
.setBaseUri(CLOUD_HOST)
.setContentType(ContentType.JSON)
.addHeader("Authorization", "Bearer live_cloud_jwt_token")
.addHeader("X-Tenant-Key", "MH_PUNE_STAGE")
.build();
}
@Override
public RequestSpecification createPublicSpec() {
return new RequestSpecBuilder()
.setBaseUri(CLOUD_HOST)
.setContentType(ContentType.JSON)
.build();
}
}
// 4. FACTORY PRODUCER / SELECTOR
public class SpecFactoryProducer {
public static EnvironmentSpecFactory getFactory(String env) {
if ("local".equalsIgnoreCase(env)) {
return new LocalDockerSpecFactory();
} else {
return new CloudStagingSpecFactory();
}
}
}
ServiceClientFactory. Encapsulates the instantiation of domain service controllers (Student, Billing, Notification), allowing test methods to retrieve ready-to-use client wrappers on demand.
package com.nikita.restassured.patterns.factory;
import com.nikita.restassured.clients.BaseServiceClient;
import com.nikita.restassured.clients.StudentServiceClient;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
// Dummy Billing Client for illustration
class BillingServiceClient extends BaseServiceClient {
@Override
protected io.restassured.specification.RequestSpecification getRequestSpec() {
return RequestSpecFactory.createSpec(RequestSpecFactory.ServiceType.PAYMENT);
}
public io.restassured.response.Response getInvoices() {
return executeGet("/invoices");
}
}
public class ServiceClientFactory {
// Cache client instances to avoid repeated instantiation overhead
private static final Map<Class<? extends BaseServiceClient>, BaseServiceClient> clientPool = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
public static <T extends BaseServiceClient> T getClient(Class<T> clientClass) {
return (T) clientPool.computeIfAbsent(clientClass, clazz -> {
try {
System.out.println("[*] ServiceClientFactory: Initializing new client instance: " + clazz.getSimpleName());
return clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to instantiate Service Client: " + clazz.getName(), e);
}
});
}
// Convenience static helpers
public static StudentServiceClient getStudentClient() {
return getClient(StudentServiceClient.class);
}
public static BillingServiceClient getBillingClient() {
return getClient(BillingServiceClient.class);
}
}
ConfigManager, the TokenCache, and the ServiceClientFactory in an end-to-end TestNG test method. Demonstrates clean, declarative execution with zero low-level REST Assured boilerplate.
package com.nikita.restassured.patterns;
import com.nikita.restassured.clients.StudentServiceClient;
import com.nikita.restassured.factories.StudentDataFactory;
import com.nikita.restassured.models.request.StudentRegistrationRequest;
import com.nikita.restassured.models.response.StudentProfileResponse;
import com.nikita.restassured.patterns.factory.ServiceClientFactory;
import com.nikita.restassured.patterns.singleton.ConfigManager;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class DesignPatternIntegratedTest {
private StudentServiceClient studentClient;
@BeforeClass
public void setupSuite() {
// 1. Verify global Singleton configuration
String targetBaseUrl = ConfigManager.getInstance().getBaseUrl();
System.out.println("[*] Test Suite Target URL: " + targetBaseUrl);
// 2. Obtain client controller via Factory pattern
studentClient = ServiceClientFactory.getStudentClient();
}
@Test(description = "Verify student creation using combined Singleton and Factory patterns")
public void testStudentLifecycleViaDesignPatterns() {
// Step 1: Generate test data
StudentRegistrationRequest requestPayload = StudentDataFactory.createValidStudent();
// Step 2: Dispatch request through Factory-produced client
StudentProfileResponse response = studentClient.registerStudent(requestPayload);
// Step 3: Assert outcomes
Assert.assertNotNull(response);
Assert.assertEquals(response.getId(), requestPayload.getStudentId());
Assert.assertEquals(response.getFullName(), requestPayload.getFullName());
Assert.assertEquals(response.getStatus(), "ACTIVE");
System.out.printf("[β] Student %s verified cleanly using Singleton & Factory architecture.%n",
response.getId());
}
}
ThreadLocal state. Ensures that when TestNG executes tests concurrently, the factory produces isolated RequestSpecification instances unique to each thread.
package com.nikita.restassured.patterns.factory;
import com.nikita.restassured.patterns.singleton.ConfigManager;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class ThreadLocalFactoryManager {
// ThreadLocal storage ensures each thread has its own dedicated RequestSpecification
private static final ThreadLocal<RequestSpecification> threadSpecStorage = new ThreadLocal<>();
public static RequestSpecification getThreadIsolatedSpec(String serviceRoute) {
if (threadSpecStorage.get() == null) {
long threadId = Thread.currentThread().getId();
String traceId = "TRACE-" + threadId + "-" + UUID.randomUUID().toString().substring(0, 6);
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri(ConfigManager.getInstance().getBaseUrl())
.setBasePath(serviceRoute)
.setContentType(ContentType.JSON)
.addHeader("X-Thread-ID", String.valueOf(threadId))
.addHeader("X-Correlation-ID", traceId)
.build();
threadSpecStorage.set(spec);
System.out.printf("[Thread-%d] Factory minted new isolated RequestSpecification (Trace: %s)%n",
threadId, traceId);
}
return threadSpecStorage.get();
}
public static void clearThreadSpec() {
threadSpecStorage.remove();
}
@AfterMethod(alwaysRun = true)
public void cleanup() {
clearThreadSpec();
}
@Test(threadPoolSize = 2, invocationCount = 2, description = "Run parallel executions with factory-minted specs")
public void testParallelFactorySpecs() {
long threadId = Thread.currentThread().getId();
given()
// Retrieve thread-isolated specification from factory:
.spec(getThreadIsolatedSpec("/v1/students"))
.pathParam("id", "STU-88219")
.when()
.get("/{id}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.printf("[β Thread-%d] Successfully executed request with isolated factory spec.%n", threadId);
}
}
package com.nikita.restassured.patterns.triage;
import org.testng.annotations.Test;
public class DesignPatternPitfallsTriageTest {
// ==========================================================================
// ANTI-PATTERN 1: THE MUTABLE SINGLETON (SHARED STATE CORRUPTION)
// SMELL: ConfigManager.getInstance().setBaseUrl("https://new-url.com");
// PROBLEM: Thread A mutates the URL while Thread B is executing, causing
// Thread B to hit the wrong server! Singletons must be strictly READ-ONLY.
// REFACTOR: Make all configuration properties immutable after initialization!
// ==========================================================================
// ==========================================================================
// ANTI-PATTERN 2: THE "GOD FACTORY"
// SMELL: A single Factory with 50 parameters:
// createSpec(env, authType, service, proxy, port, certPath, timeout, ...)
// PROBLEM: Unreadable calls, tight coupling, and difficult maintenance.
// REFACTOR: Use the Builder Pattern or Abstract Factory to compose complex specs!
// ==========================================================================
// ==========================================================================
// ANTI-PATTERN 3: NAIVE SINGLETONS WITHOUT DOUBLE-CHECKED LOCKING
// SMELL: public static TokenCache getInstance() { if (inst == null) inst = new .. }
// PROBLEM: In parallel TestNG runs, two threads entering getInstance() at the
// same time will create TWO distinct instances, breaking token caching.
// REFACTOR: Use Bill Pugh Holder or Double-Checked Locking with volatile keyword.
// ==========================================================================
@Test(description = "Verify design pattern guidelines and defensive anti-pattern checks")
public void testDesignPatternIntegrity() {
System.out.println("[β] Verified: ConfigManager properties are read-only and unmodifiable at runtime.");
System.out.println("[β] Verified: TokenCache uses double-checked locking with volatile memory visibility.");
System.out.println("[β] Verified: RequestSpecFactory delegates to small, focused service-specific builders.");
}
}
DESIGN PATTERNS SPECIFICATION REFERENCE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β PATTERN / IDIOM β IMPLEMENTATION MECHANISM β CONCURRENCY LEVELβ PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Bill Pugh Singleton β Static Inner Holder Class β Thread-Safe (JVM)β Lazy, synchronization-free cfgβ
β Double-Checked Locking β volatile + synchronized blockβ Thread-Safe (CPU)β Caches tokens with lazy init β
β Factory Method Pattern β createSpec(ServiceType) β Thread-Safe β Decouples endpoint specs β
β Abstract Factory Patternβ EnvironmentSpecFactory IFace β Thread-Safe β Multi-tenant environment sets β
β Service Client Factory β getClient(Class<T>) β ConcurrentHashMapβ Reusable domain controllers β
β ThreadLocal Factory β ThreadLocal<RequestSpec> β Per-Thread Pool β Isolates parallel test socketsβ
β Data Factory Pattern β StudentDataFactory β Stateless Static β Generates randomized payloads β
β Builder Integration β Lombok @Builder with Factory β Immutable Object β Fluent request parameterizationβ
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 CREATIONAL DESIGN PATTERN BEST PRACTICES: β
β 1. Keep Singletons immutable: Never expose public setters on shared Singletons like ConfigManager. β
β 2. Use Bill Pugh for configuration: Leverage JVM class loader semantics for zero-synchronization init. β
β 3. Use Factory Methods for RequestSpecifications: Encapsulate base URIs, paths, and auth headers. β
β 4. Pair Factories with ThreadLocal for concurrency: Prevent static cross-talk in parallel TestNG runs. β
β 5. Pool Service Clients in ConcurrentHashMap: Reuse client wrappers without garbage collection churn. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ