From 159461815d99562f7d8f1babe787c7f784145a92 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Fri, 3 Nov 2023 15:31:25 -0600 Subject: [PATCH] New example and unit test --- .../synchronizedclass/Employee.java | 32 +++++++++++++++++++ .../SychronizeStaticDataUnitTest.java | 16 +++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java new file mode 100644 index 0000000000..a69b633f3b --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/synchronizestatic/synchronizedclass/Employee.java @@ -0,0 +1,32 @@ +package com.baeldung.concurrent.synchronizestatic.synchronizedclass; + +/** + * Synchronizing static variable with a synchronized block. + */ +public class Employee +{ + static int count; + int id; + String name; + String title; + + public Employee(int id, String name, String title) + { + incrementCount(); + this.id = id; + this.name = name; + this.title = title; + } + + private static void incrementCount() { + synchronized(Employee.class) { + System.out.println("Count = " + ++count); + } + } + + public static int getCount() { + synchronized(Employee.class) { + return count; + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java index 7e5dca9f2b..e633005c6f 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/synchronizestatic/SychronizeStaticDataUnitTest.java @@ -45,10 +45,24 @@ public class SychronizeStaticDataUnitTest } } + @Test + public void whenSynchronizedClass_thenDataInOrder() { + + System.out.println("Synchronization with synchronized block on class"); + + for(int i = 0; i < numberToTest; i++) { + int finalI = i; + pool.execute(() -> + { + new com.baeldung.concurrent.synchronizestatic.synchronizedclass.Employee(finalI, "John", "Smith"); + }); + } + } + @Test public void whenSynchronizedBlock_thenDataInOrder() { - System.out.println("Synchronization with synchronized block"); + System.out.println("Synchronization with synchronized block on a private object"); for(int i = 0; i < numberToTest; i++) { int finalI = i;