Java @ Desk

Java @ Desk

Breaking

Thursday, April 21, 2022

Python remove leading and trailing white space from a String

7:21 AM 0
Python remove leading and trailing white space from a String

Python have 3 functions to remove the trimmed space, remove leading whitespace and remove trailing whitespace.

strip(): Removes leading and trailing whitespace.
rstrip(): Removes trailing whitespace.
lstrip(): Removes leading whitespace.

 string = '  Python Trim String  '  
 print('Original String is - \'' + string + '\'')  
 print('Removing Trailing Space - \'' + string.rstrip()+ '\'')  
 print('Removing Leading Space - \'' + string.lstrip()+ '\'')  
 print('Trimmed String is - \'' + string.strip()+ '\'')  


Output :

 Original String is - '  Python Trim String  '  
 Trimmed String is - 'Python Trim String'  
 Removing Trailing Space - '  Python Trim String'  
 Removing Leading Space - 'Python Trim String  '  

Monday, December 14, 2020

AtomicInteger and volatile in Multithreading Java

12:42 AM 0
AtomicInteger and volatile in Multithreading Java

In our previous post, we learnt about the volatile keyword in Java. But volatile keyword is not sufficient to guarantee atomicity. Volatility just guarantees the visibility of the variable and NOT atomicity, whereas Synchronization (locking) guarantees both visibility and atomicity.
But Synchronization affects processing time.
By visibility we mean that all the threads will get the latest form of the variable. In the above example, as you can see, all the threads get the latest value of counter in the subsequent reads.

AtomicInteger helps in getting the latest value of the last write by any given thread in a Multithreading environment. If we have multiple threads that reads and writes the integer, then AtomicInteger guarantees, the write operation must get the latest update from the memory.

AtomicIntegerExample.java - In this class, we have 2 variables, one is Integer and another is AtomicInteger. We have created 2 Threads that updates the values of both the fields by 1. This update operation is running 10000 times by 2 different threads. So final values expected for both the fields must be -
1) atomicInteger - 20000
2) integer - 20000

But since integer variable is just volatile, then multiple threads do not get the latest value during write. But that is taken care by the AtomicInteger as shown below -


package com.learning;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample implements Runnable {

	@Override
	public void run() {
		int max = 10000;

		for (int i = 0; i < max; i++) {
			atomicInteger.addAndGet(1);
			integer = integer + 1;
		}
	}

	public static void main(String args[]) throws InterruptedException {
		AtomicIntegerExample atomicIntegerExample = new AtomicIntegerExample();
		atomicIntegerExample.setAtomicInteger(new AtomicInteger());
		atomicIntegerExample.setInteger(new Integer(0));

		Thread first = new Thread(atomicIntegerExample);
		Thread second = new Thread(atomicIntegerExample);

		// Threads start executing
		first.start();
		second.start();

		// main thread will wait for both threads to complete execution
		first.join();
		second.join();

		// Printing final value of count variable
		System.out.println("Atomic Integer in Multithreading - " + atomicIntegerExample.getAtomicInteger());
		System.out.println("Integer Value in Multithreading - " + atomicIntegerExample.getInteger());
	}

	private AtomicInteger atomicInteger;

	private volatile Integer integer;

	public AtomicInteger getAtomicInteger() {
		return atomicInteger;
	}

	public void setAtomicInteger(AtomicInteger atomicInteger) {
		this.atomicInteger = atomicInteger;
	}

	public Integer getInteger() {
		return integer;
	}

	public void setInteger(Integer integer) {
		this.integer = integer;
	}

}




Output - Results of 5 different executions. Its clearly visible, AtomicInteger is safely incremented by 1 and all threads get the latest updates of the variable.


Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 11354

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 11681

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 12656

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 11107

Atomic Integer in Multithreading - 20000
Integer Value in Multithreading - 13106


Friday, December 11, 2020

Stream Intermediate vs Terminal Operation in Java 8

11:14 PM 0
Stream Intermediate vs Terminal Operation in Java 8

In Java 8, Stream is used to perform operations in pipeline to either get another Stream or Collection or Object. Stream operations are performed on objects that are returning Stream and not on any other type.

The Stream operation that returns another Stream is an Intermediary Operation. Hence these can be chained together to form a Pipeline. Basic example is, we can perform filter operations on a Stream to remove Null objects from a Collection - ".filter(Objects::nonNull)", then perform another filter operation on returned Stream as per business logic i.e. ".filter(person -> person.getGender().equals(Gender.MALE))". We can have multiple Intermediate Operations as shown above. They are lazily loaded. They are just stored in the memory and executed when the terminal operation is called on the stream.

The Stream operation that returns anything other than Stream i.e. Object or a Collection type is an Terminal Operation. These operations cannot be chained together. We can have only 1 Terminal Operations at the end.

Stream Operations - filter(), map(), limit(), skip()
Intermediate Operations - forEach(), collect(), count(), min(), max(), etc.

IntermediaryTerminalStream.java - In this example, we will learn 2 Intermediate(filter & map) and 2 Terminal(collect & count).


package com.learning;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.learning.model.Gender;
import com.learning.model.Person;

public class IntermediaryTerminalStream {
	public static void main(String args[]) {

		List persons = new ArrayList<>();
		Person personOne = new Person(10, "John", Gender.MALE);
		Person personTwo = new Person(11, "Andy", Gender.MALE);
		Person personThree = new Person(12, "Peter", Gender.MALE);
		Person personFour = new Person(13, "Sarah", Gender.FEMALE);
		Person personFive = new Person(14, "Gillian", Gender.FEMALE);

		persons.add(personOne);
		persons.add(personTwo);
		persons.add(personThree);
		persons.add(personFour);
		persons.add(personFive);

		// Filter is a Intermediate Operation, since it returns a Stream and we can
		// perform
		// Terminal Operations on them.
		Stream filterIntermediateOperation = persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE));

		// map is a Intermediate Operation, since it returns a Stream and we can perform
		// Terminal Operations on them.
		Stream mapIntermediateOperation = persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE)).map(Person::getName);

		// collect is a Terminal Operation. No Intermediary operations can be performed,
		// since its returning a List instead of Stream.
		List collectTerminalOperation = persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE)).collect(Collectors.toList());

		// count is a Terminal Operation. No Intermediary operations can be performed,
		// since its returning a Integer instead of Stream.
		Integer countTerminalOperation = (int) persons.stream().filter(Objects::nonNull)
				.filter(p -> p.getGender().equals(Gender.MALE)).count();

	}
}



Sunday, December 6, 2020

How to use Streams in Map in Java 8

6:01 AM 0
How to use Streams in Map in Java 8

Map, unlike, other Collection types is in a Key/Value Format where the Keys are unique in a Map. Using Map.Entry, we can fetch the keySet() as well as entrySet().
Stream cannot be applied directly to a Map since Stream is done on the Collection of Objects. So it is applied to a keySet() or a entrySet() or values() that return the collection of value from a Map.



Map someMap = new HashMap<>();
Set> entries = someMap.entrySet();
Set keySet = someMap.keySet();
Collection values = someMap.values();
These each give us an entry point to process those collections by obtaining streams from them:

Stream> entriesStream = entries.stream();
Stream valuesStream = values.stream();
Stream keysStream = keySet.stream();



Here are few examples of Stream for a Map


package com.learning;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import com.learning.model.Gender;
import com.learning.model.Person;

public class StreamMap {

	public static void main(String args[]) {
		Map personMap = new HashMap();

		Person personOne = new Person(10, "John", Gender.MALE);
		Person personTwo = new Person(11, "Andy", Gender.MALE);
		Person personThree = new Person(12, "Peter", Gender.MALE);
		Person personFour = new Person(13, "Sarah", Gender.FEMALE);
		Person personFive = new Person(14, "Gillian", Gender.FEMALE);

		personMap.put(personOne.getAge(), personOne);
		personMap.put(personTwo.getAge(), personTwo);
		personMap.put(personThree.getAge(), personThree);
		personMap.put(personFour.getAge(), personFour);
		personMap.put(personFive.getAge(), personFive);

		// Find all Person Objects where Age is Even
		System.out.println("Persons with Even Age - " + personMap.entrySet().stream().filter(person -> person.getKey() % 2 == 0)
				.map(Map.Entry::getValue).collect(Collectors.toList()));

		// Find all Person Objects where Gender is Female
		System.out.println("Persons with Gender Female - " + personMap.values().stream().filter(person -> person.getGender().equals(Gender.FEMALE))
				.collect(Collectors.toList()));

	}
}



Output


Persons with Even Age - [10 John MALE, 12 Peter MALE, 14 Gillian FEMALE]
Persons with Gender Female - [13 Sarah FEMALE, 14 Gillian FEMALE]



Tuesday, February 25, 2020

How to get sum of Integer or Double field from a List of Pojo Java class

6:52 AM 0
How to get sum of Integer or Double field from a List of Pojo Java class

This post will demonstrate how to get sum of any particular field, for example, consider a List of Person class with property noOfMangoesEaten which represents how many mangoes an individual has consumed.

Using Java 8, we need to find how many mangoes in total have been consumed by all the persons inside a List.

We can use streams function to iterate the list and use mapToInteger function and gets sum out of it.

Here is an example

Person.java
package com.test;

public class Person {

 private int noOfMangoesConsumed;

 public int getNoOfMangoesConsumed() {
  return noOfMangoesConsumed;
 }

 public void setNoOfMangoesConsumed(int noOfMangoesConsumed) {
  this.noOfMangoesConsumed = noOfMangoesConsumed;
 }
}


SumOfFields.java -
package com.test;

import java.util.ArrayList;
import java.util.List;

public class SumOfFields {

 public static void main(String args[]) {
  Person person = new Person();
  person.setNoOfMangoesConsumed(100);
  
  Person person2 = new Person();
  person2.setNoOfMangoesConsumed(200);
  
  List<Person> persons = new ArrayList<Person>();
  persons.add(person);
  persons.add(person2);
  
  int sum = persons.stream().mapToInt(p -> p.getNoOfMangoesConsumed()).sum();
  
  System.out.println("Total Mangoes Consumed - " + sum);
 }
}


Output -
Total Mangoes Consumed - 300

Friday, January 25, 2019

Spring Validator Framework In Java

11:57 PM 0
Spring Validator Framework In Java

Spring Validator Framework validates the input Java class properties. Validator class must implement org.springframework.validation.Validator and define the validator rules in the overridden method -
public void validate(Object o, Errors errors)

This method contains the validation rules. For example, for a Person class validation rules can be to verify if name, address properties of the incoming Person class are not null and not empty.

org.springframework.validation.ValidationUtils invokes the validation on the incoming Person class by using the Validator Implemention that defined the validation rules.

There are 2 ways to invoke validation on the incoming objects -
1) ValidationUtils.invokeValidator(personValidator, person, errors); - personValidator is the class implementing Validation interface and errors is the object of class BindException
2) personValidator.validate(person, errors);

Here is a sample implementation of the Spring Validation Framework

Person.java
package com.learning.com.springvalidation;

public class Person {

    private String name;

    private int age;

    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


PersonValidator.java
package com.learning.com.springvalidation;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {
    public boolean supports(Class<?> aClass) {
        return Person.class.isAssignableFrom(aClass);
    }

    public void validate(Object o, Errors errors) {

        if (o == null) {
            errors.reject("Person Object is Null");
        }
        Person person = (Person) o;
        if (person.getName() == null) {
            errors.reject("Name Field Is Null");
        }
        if (person.getAddress() == null) {
            errors.reject("Address Field Is Null");
        }
    }
}


PersonClient.java
package com.learning.com.springvalidation;

import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;

public class PersonClient {

    public static void main(String args[]) {
        PersonValidator personValidator = new PersonValidator();
        Person person = new Person();
        BindException errors = new BindException(person, "person");
        ValidationUtils.invokeValidator(personValidator, person, errors);
        System.out.println("Error - " + errors.getMessage());
    }
}


Output
"C:\Program Files\Java\jdk1.8.0_181\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2018.2.5\lib\idea_rt.jar=53398:C:\Program Files\JetBrains\IntelliJ IDEA 2018.2.5\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\rt.jar;C:\Kumar\Projects\learning\target\classes;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-context\5.1.4.RELEASE\spring-context-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-aop\5.1.4.RELEASE\spring-aop-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-beans\5.1.4.RELEASE\spring-beans-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-core\5.1.4.RELEASE\spring-core-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-jcl\5.1.4.RELEASE\spring-jcl-5.1.4.RELEASE.jar;C:\Users\bhatiak1\.m2\repository\org\springframework\spring-expression\5.1.4.RELEASE\spring-expression-5.1.4.RELEASE.jar" com.learning.com.springvalidation.PersonClient
Error - org.springframework.validation.BeanPropertyBindingResult: 2 errors
Error in object 'person': codes [Name Field Is Null.person,Name Field Is Null]; arguments []; default message [null]
Error in object 'person': codes [Address Field Is Null.person,Address Field Is Null]; arguments []; default message [null]

Process finished with exit code 0

Monday, December 24, 2018

Semaphore In Java With Real Time Example

8:41 PM 1
Semaphore In Java With Real Time Example

Semaphore has been introduced in Java 5 to provide access to shared resources in an effective manner. Semaphore controls the number of threads to access shared resources. Semaphore is initialized with the integer count where only that many threads get access to shared resources.

Consider a real time example of Washroom access at a Railway Station that has only 2 washroom. When both the washroom gets filled, people outside need to wait to get them empty. In this case,
Semaphore is initialized with count as 2. Since the entry to washrooms must be allowed in a fair manner, Semaphore is initialized with fair - true. This make sure clients waiting outside must get fair chance i.e. first one in the queue must get first entry as soon as one of the washroom is available.
Semaphore is initialized with count 2. If 1 person enters the first washroom, Semaphore count is reduced to 1 by giving a call to semaphore.acquire(). When second person enters 2nd washroom, Semaphore is reduced to 0 by calling semaphore.acquire().
Now all the clients are waiting for atleast one washroom to become available. As soon as one of the washroom gets free, Semaphore is incremented to 1 by calling semaphore.release(). As soon as count becomes 1, the client waiting first get access to washroom, and so Semaphore count becomes 0 again and all clients wait in the queue. As soon as 2nd goes empty, Semaphore again increase to 1 by calling semaphore.release() and another client gets a chance.
There is a case when both the washrooms goes empty, in that case, Semaphore count is again incremented to 2.

Here is a realtime implementation of above -
SemaphoreClient.java - This is a client file that initializes Semaphore to 2 and initialize 5 clients to access washroom
package com.learning.semaphore;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class SemaphoreClient {
    public static void main(String args[]) {

        Semaphore washRoomSemaphore = new Semaphore(2, true);

        List<ClientThread> clientThreads = new ArrayList<ClientThread>();

        for(int i = 1; i <= 5; i++) {
            ClientThread clientThread = new ClientThread();
            clientThread.setWashRoomSemaphore(washRoomSemaphore);
            clientThread.setClientNumber(i);
            clientThreads.add(clientThread);
        }

        for(ClientThread clientThread : clientThreads) {
            Thread thread = new Thread(clientThread);
            thread.start();
        }
    }
}


ClientThread.java - This is a client thread that acquire and releases Semaphore in order to access Washroom
package com.learning.semaphore;

import java.util.concurrent.Semaphore;

public class ClientThread implements Runnable {
    public void run() {
        System.out.println("Client - " + this.clientNumber + " waiting for Washroom access");
        try {
            this.washRoomSemaphore.acquire();
            System.out.println("Client - " + this.clientNumber + " got access to Washroom");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        } finally {
            this.washRoomSemaphore.release();
            System.out.println("Client - " + this.clientNumber + " released Washroom");
        }
    }

    private Semaphore washRoomSemaphore;

    private int clientNumber;

    public Semaphore getWashRoomSemaphore() {
        return washRoomSemaphore;
    }

    public void setWashRoomSemaphore(Semaphore washRoomSemaphore) {
        this.washRoomSemaphore = washRoomSemaphore;
    }

    public int getClientNumber() {
        return clientNumber;
    }

    public void setClientNumber(int clientNumber) {
        this.clientNumber = clientNumber;
    }
}


Output -
Client - 1 waiting for Washroom access
Client - 1 got access to Washroom
Client - 2 waiting for Washroom access
Client - 2 got access to Washroom
Client - 3 waiting for Washroom access
Client - 4 waiting for Washroom access
Client - 5 waiting for Washroom access
Client - 3 got access to Washroom
Client - 4 got access to Washroom
Client - 1 released Washroom
Client - 2 released Washroom
Client - 4 released Washroom
Client - 5 got access to Washroom
Client - 3 released Washroom
Client - 5 released Washroom


Its visible as soon as 2 threads got access to Washroom, Semaphore is reduced to 0 and other clients enter in wait state.

Saturday, December 15, 2018

CyclicBarrier in Java with Real Time Example

10:57 PM 0
CyclicBarrier in Java with Real Time Example

CyclicBarrier is a thread syncronization mechanism in which all the threads are requested to wait at a certain point, before all of them move forward. The specific point is called a barrier and threads enter into a wait state at barrier point until all working threads reaches at that point. Once all threads reaches barrier point, they are allowed to continue.

The importance of a Cyclic Barrier is that it is cyclic i.e. once all the threads reaches barrier point and resumes their individual jobs, CyclicBarrier is allowed to reset.

Here is an example of a Cricket Match. Before a bowler is allowed to bowl first delivery, it waits for 2 umpires to reach their specific positions and all 10 fielders at their respective fielding positions. Until and unless 2 umpires and 11 fielders reaches at their respective positions, no thread can move forward. For example, even if 2 umpires and 10 fielders reach their points, they still need to wait for 11th player to reach to his position. Once 11th player reaches his position and calls await() method, bowler is allowed to bowl.

Here is a real time implementation of CyclicBarrier

CyclicBarrierCricket.java - This is a main class that initializes CyclicBarrier. It initializes threads for 11 Players and 2 Umpires and then calls the await method(). As soon as both the umpires and 11 players calls await(), this thread moves forward.
package com.cyclicbarrier.learning;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierCricket {

 public static void main(String args[]) {
  CyclicBarrier barrier = new CyclicBarrier(14);
  System.out.println("Match about to Start");

  System.out.println("Initializing Umpires");

  for (int i = 1; i <= 2; i++) {
   CyclicBarrierUmpire barrierUmpire = new CyclicBarrierUmpire();
   barrierUmpire.setUmpireNumber(i);
   barrierUmpire.setCyclicBarrier(barrier);
   Thread thread = new Thread(barrierUmpire);
   thread.start();
  }

  System.out.println("Umpires Thread Started");

  System.out.println("Initializing Players");

  for (int i = 1; i <= 11; i++) {
   CyclicBarrierPlayers cyclicBarrierPlayers = new CyclicBarrierPlayers();
   cyclicBarrierPlayers.setPlayerNumber(i);
   cyclicBarrierPlayers.setCyclicBarrier(barrier);
   Thread thread = new Thread(cyclicBarrierPlayers);
   thread.start();
  }

  System.out.println("Players Thread Started");
  
        try {
   barrier.await();
  } catch (InterruptedException | BrokenBarrierException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

        System.out.println("Players and Umpires all set at their respective Positions. Lets start a Game");
 }

}


CyclicBarrierUmpire.java - This is a Java thread to initialize both the umpires. Both the umpires calls the await() method to notify that we are all set and waiting for rest of the players to move to the position.
package com.cyclicbarrier.learning;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierUmpire implements Runnable {

    private CyclicBarrier cyclicBarrier;
    
    private int umpireNumber;
 
 @Override
 public void run() {
  System.out.println("Umpire " + umpireNumber + " Moving to Position");
        try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Umpire " + umpireNumber + " Set at Position");
  
        try {
   cyclicBarrier.await();
  } catch (InterruptedException | BrokenBarrierException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        System.out.println("Umpire - " + umpireNumber + " all set");
 
  
 }

 public int getUmpireNumber() {
  return umpireNumber;
 }

 public void setUmpireNumber(int umpireNumber) {
  this.umpireNumber = umpireNumber;
 }

 public CyclicBarrier getCyclicBarrier() {
  return cyclicBarrier;
 }

 public void setCyclicBarrier(CyclicBarrier cyclicBarrier) {
  this.cyclicBarrier = cyclicBarrier;
 }
 
}


CyclicBarrierPlayers.java - This is a Java thread to initialize all the players. All 11 players calls the await() method to notify that we are all set and waiting for rest of the players to move to the position. As soon as 11th player calls await() method, main class moves forward and allows a match to start.
package com.cyclicbarrier.learning;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierPlayers implements Runnable {

    private CyclicBarrier cyclicBarrier;
    
    private int playerNumber;
 
 @Override
 public void run() {
  System.out.println("Player " + playerNumber + " Moving to Fielding Position");
        try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Player " + playerNumber + " Fielding Position Set");
  
        try {
   cyclicBarrier.await();
  } catch (InterruptedException | BrokenBarrierException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        System.out.println("Player - " + playerNumber + " all set");
 }

 public CyclicBarrier getCyclicBarrier() {
  return cyclicBarrier;
 }

 public void setCyclicBarrier(CyclicBarrier cyclicBarrier) {
  this.cyclicBarrier = cyclicBarrier;
 }

 public int getPlayerNumber() {
  return playerNumber;
 }

 public void setPlayerNumber(int playerNumber) {
  this.playerNumber = playerNumber;
 }
 
}


Output -
Match about to Start
Initializing Umpires
Umpires Thread Started
Initializing Players
Umpire 1 Moving to Position
Umpire 2 Moving to Position
Player 1 Moving to Fielding Position
Player 2 Moving to Fielding Position
Player 3 Moving to Fielding Position
Player 4 Moving to Fielding Position
Player 5 Moving to Fielding Position
Player 6 Moving to Fielding Position
Player 7 Moving to Fielding Position
Player 8 Moving to Fielding Position
Player 9 Moving to Fielding Position
Players Thread Started
Player 10 Moving to Fielding Position
Player 11 Moving to Fielding Position
Umpire 1 Set at Position
Umpire 2 Set at Position
Player 1 Fielding Position Set
Player 4 Fielding Position Set
Player 5 Fielding Position Set
Player 8 Fielding Position Set
Player 3 Fielding Position Set
Player 2 Fielding Position Set
Player 9 Fielding Position Set
Player 7 Fielding Position Set
Player 6 Fielding Position Set
Player 11 Fielding Position Set
Player 10 Fielding Position Set
Player - 10 all set
Umpire - 1 all set
Players and Umpires all set at their respective Positions. Lets start a Game
Umpire - 2 all set
Player - 1 all set
Player - 5 all set
Player - 4 all set
Player - 8 all set
Player - 7 all set
Player - 9 all set
Player - 6 all set
Player - 11 all set
Player - 2 all set
Player - 3 all set


Its clearly visible, main client prints "Players and Umpires all set at their respective Positions. Lets start a Game" only when all the Umpire and Player threads have called the await() method. Till then it was in wait state.