New example and unit test

This commit is contained in:
Michael Pratt 2023-11-03 15:31:25 -06:00
parent 1aa2f849f4
commit 159461815d
2 changed files with 47 additions and 1 deletions

View File

@ -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;
}
}
}

View File

@ -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;