Best practice to generate unique systemPort value for parallel test execution

Hi,
I have a question regarding making parallel execution more generic and easier to maintain. We want to get rid of hard coded data as much as possible. For example in our initializerDriver() method we have this line:

desiredCapabilities.setCapability(“systemPort”,dp.get(Properties.SYSTEM_PORT.propertyName));

which is working fine but it uses hard coded systemPort value which stored in property file for every mobile device we’re running our tests because it should be unique for every used android device. What I do want to change is instead of using hard coded systemPort value and storing in properties file, generate unique value for every device from the range 8200 - 8299 (as it recommended) and use it every time new driver instance is created.

Since we’re using Appium + TestNG, I have a question are global variables somehow available with testNG framework? I mean if I generate one systemPort value I need to store it somewhere to be able to pick unique one for every new device . Or there is a better way to implement this idea? What I have in mind is to create a thread for this and use it, but I am not very familiar with this topic in Java.
Any other ideas/examples?

Cheers,
Dzmitry

AppiumServiceBuilder builder = new AppiumServiceBuilder();
    builder.usingAnyFreePort();

And to get port for capabilities
driverCapabilities.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, systemPort);
//Use the below to fetch the port.
int port = 8100;
try {
ServerSocket socket = new ServerSocket(0);
socket.setReuseAddress(true);
port = socket.getLocalPort();
socket.close();
} catch (Exception e) {
}

Hello @SankalpSharmaSDET, @Zeuge

Were you able to achieve the execution as expected ?
Currently I am trying the same but I am not able to use system port cap as it should.

Could you please help me it ?
Here is what I have tried and my functions and code that I am using.

For now , I am able to initiate app on both the device but the test case execution starts on only one and then ends giving Session ID null error.

Details for what I have tried

Thanking you in advance.