Sunday, 29 November 2020

JAVA Threads

 The following information helps to understand the Thread Executor. The following exam show the Interfaces and classes hierarchy .


The following code helps to understand how to use the ThreadExecutor to create connections while starting the ATG nucleus component.

ThreadExecutor has three mains points

1)Define the ThreadExecutor by setting the minimum and maximum threads , time, timeUnits, LinkedBlockingQueue.

2)Define the Callable Object. (Callable is interface with call method, need to implement the actual logic (in our case creating connection object)

2)Invoke the submit method over the ThreadExecutor by passing the Callable Object

1)write the below logic in the doStart() method

  ThreadPoolExecutor  executor = new ThreadPoolExecutor(0, 5, 20000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

setThreadExecutor(executor);


2)Implement the logic for Callable as follows

Callable<String> cuCallableObj=new Callable<String>() {

public String call() throws Exception {

HttpEntity entity = null;

String resString = null;

try {

HttpHost proxy = null;

CloseableHttpClient client = null;

HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

if (isEnableProxy()) {

proxy = new HttpHost(getProxyHost(), getProxyPort());

client = httpClientBuilder.setProxy(proxy).build();

} else {

client = httpClientBuilder.build();

}

HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("Content-Type", "application/json");

httpPost.setEntity(new StringEntity(pJSON));

CloseableHttpResponse response = client.execute(httpPost);

if (response != null) {

entity = response.getEntity();

}

if (entity != null) {

resString = EntityUtils.toString(entity);

}

response.close();

} catch (Exception ex) {

vlogError(ex, "Exception occurred inside the getGlobalConnectionPool()");

}

return resString;

}

};

3)Then call the submit() method over ThreadExecutor as follows.


Future<String> featureresponseObject = getThreadExecutor().submit(cuCallableObj);

if (featureresponseObject != null) {

try {

try {

responseObject = featureresponseObject.get(2000000, TimeUnit.MILLISECONDS);

} catch (TimeoutException ex) {

vlogError(ex, "TimeoutException occurred inside the getGlobalConnectionPool()");

}

} catch (ExecutionException ex) {

vlogError(ex, "ExecutionException occurred inside the getGlobalConnectionPool()");

}

}