How to achieve parallel code execution without user Threads

What comes to your mind when you have to run a piece of code in parallel? you will create some threads to do it, correct! But this is not only a way to achieve it. Recently I came across one interesting requirement where I had to run a piece of code of an API for three parallel calls (without Threads).My approach is not something new, many of you might be doing it already and others might have not noticed this approach while maintaining the legacy code 🙂 .

Well, so this approach is nothing but a combination of Bean loading in Spring container and corresponding mapped Java class execution, and hooking a API to support parallelism. when spring container loads a annotated/configured Bean it executes Java method associated with it. using this concept we can define and load the same bean with three different ids to execute the method ( the same code runnable implementation ) code rather than doing it through Three different threads.

<beans profile="cluster">
<bean id="mongoQueryServList" class="com.skilledminds.thirdPartyService.configure.db.connectionProvider.cacheQueryProcessor"/>
<beans profile="cluster">
<bean id="cassandraQueryServList" class="com.skilledminds.thirdPartyService.configure.db.connectionProvider.cacheQueryProcessor"/>
<beans profile="no_cluster">
<bean id="graphQueryServList" class="com.skilledminds.thirdPartyService.configure.db.connectionProvider.cacheQueryProcessor"/>

Above piece of code is just a replacement of Three threads for  "cacheQueryProcessor" task, now to achieve parallelism/conditional task execution this method should be designed properly to meet the requirement. For more details on parallelism/conditional task execution please refer Spring-Batch Scaling and Parallel Processing or Java executor framework ( which is a base of every Parallelism implementation).

Still you want to take a deep dive of similar implementation then take a look at ongoing Spring Jira

PS: For an experienced java professional this may look very simple to do but considering this in a bigger picture gives the insight of an option to design an utility tool/Jar without heavy Spring batch or similar APIs.

2 thoughts on “How to achieve parallel code execution without user Threads

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s