Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Java IoT, IBM Cloud, Weblogic

Java IoT: Article

Java Feature — Concurrent Queries

A pattern for improving database query performance

Does this sound familiar? You have a domain object, perhaps for reporting purposes, that's built from a ton of JDBC queries and it takes too long to load. Nothing else happens until this object is built, so it's become a bottleneck. Even worse, each of the queries is actually well tuned, so there isn't much to gain from modifying the queries themselves - there are just too many of them. You don't want to change (or can't change) your data model, so what can be done to alleviate this problem short of a major redesign? There are several options like caching, lazy loading, resource pooling. Another worthy option would be to implement a variation of the concurrent query pattern.

Concurrent queries are fairly simple to implement and even simpler to describe. Rather than serializing a set of queries, one after the other, waiting for one to complete before the next begins, one would actually use threads to run sets of independent queries simultaneously. Now, using threading for database I/O might sound daunting or ill-advised, but the Java threads package is one of the best, if not the best, I've had the pleasure of working with. Plus, the new concurrency utilities supplied with Java 5 make using threading for database I/O much more feasible. The UML-ish diagram in Figure 1 attempts to provide a pictorial representation of what I hope to explain in the following paragraphs.

Suppose a domain object is built from 200 queries that can each run from execution to processing results in 100 milliseconds on average. Now 100ms isn't too bad for a query, but stacked end to end, the result would be up to 20 seconds to build an object. Ouch. Now, suppose you could run up to five of these queries concurrently at any one time. In an example that will be described later, I was able to take a similar scenario and increase performance from 20+ seconds to build an object to 5+ seconds. First, though, I'll describe a simpler problem scenario and then implement a solution using concurrent queries, making use of JDBC, connection pooling, and Java 5 thread pools in an effort to demonstrate the type of performance improvements this pattern might render. Later on, I'll cover another, more complicated implementation of an object that's built from several actual database queries. Note: Full source code for these sample implementations is available on sourceforge.net.

A Serialized Baseline Sample Application
First, let's look at the usual case for building objects from database queries. For the following example, a user-defined sleep function was created in a Postgres database (using Postgres magic that I found on the Internet) that could be called as select sleep(N) where N is the number of seconds to sleep. After sleeping for the seconds indicated in the argument the number of seconds slept is returned back as a result. We'll do this with a class called SleepyObject in Listing 1.

This is a fairly standard JDBC query class that selects the sleep(N) function for the number of seconds desired and processes the ResultSet, which simply contains an integer indicating the number of seconds requested to sleep. So, if you "select sleep(1)," the result of that query will be 1. Effectively, the sleep function mimics a query that takes N seconds to complete. In the serialized example (Example1.java), an array of five SleepyObjects is created. Upon creation, each SleepyObject selects the sleep(N) function via JDBC and processes the result. This example creates an array of SleepyObjects then iterates over that array, printing out the return value from the call to the sleep function. Then, the number of seconds it took to execute the entire exercise is printed. Since this sample creates JDBC objects in the usual way, the second SleepyObject isn't created until the first object is fully created (e.g., finished with its sleep(N) query), and so on. So, in this example, since each SleepyObject sleeps 2, 1, 2, 2, and 1 seconds, respectively, the entire application must take at least eight seconds plus overhead to run, as indicated in the output below. This is Example1.java - a serialized example.

package net.sourceforge.concurrentQuery.article.serialized;

import java.sql.SQLException;

public class Example1 {

   public Example1() {}
   public static void main(String[] args) throws SQLException {

     long start = System.currentTimeMillis();

     SleepyObject[] sleepyObjects = { new SleepyObject(2),
          new SleepyObject(1),
          new SleepyObject(2),
          new SleepyObject(2),
          new SleepyObject(1)
          };
     int i = 1;
     for (SleepyObject sleepyObject : sleepyObjects) {
       System.out.println("SleepyObject " + i++ + " returned "
       + sleepyObject.getValue());
     }
     long end = System.currentTimeMillis();
     System.out.println("took: " + new Double(end - start) / 1000 + " seconds");

   }
}

The following is output from Example1.java.

run-example1:
    [java] query is: select sleep(2)
    [java] query is: select sleep(1)
    [java] query is: select sleep(2)
    [java] query is: select sleep(2)
    [java] query is: select sleep(1)
    [java] SleepyObject 1 returned 2
    [java] SleepyObject 2 returned 1
    [java] SleepyObject 3 returned 2
    [java] SleepyObject 4 returned 2
    [java] SleepyObject 5 returned 1
    [java] took: 8.54 seconds

An Implementation Using Concurrent Queries
Next, we'll build on the same example, but this time we'll use a class called ConcurrentSleepyObject to replace SleepyObject. The ConcurrentSleepyObject will use a singleton implementation of the concurrent query pattern to invoke queries and reap the results as seen in Example2.java below.

package net.sourceforge.concurrentQuery.article.concurrent;

import java.sql.SQLException;

public class Example2 {

   public Example2() {}
   public static void main(String[] args) throws SQLException {

     long start = System.currentTimeMillis();

     ConcurrentSleepyObject[] concurrentSleepyObjects = {
          new ConcurrentSleepyObject(2),
          new ConcurrentSleepyObject(1),
          new ConcurrentSleepyObject(2),
          new ConcurrentSleepyObject(2),
          new ConcurrentSleepyObject(1)
          };
     int i = 1;
     for (ConcurrentSleepyObject concurrentSleepyObject :
       concurrentSleepyObjects) {
       System.out.println("ConcurrentSleepyObject " + i++
       + " returned " + concurrentSleepyObject.getValue());
     }
     long end = System.currentTimeMillis();
     System.out.println("took: " + new Double(end - start) / 1000 + " seconds");

   }
}

Both Example1 and Example2 build an array containing five objects, each invokes a database sleep for the same amount of time. However, in this second example, by using an implementation of the concurrent query pattern, the same JDBC calls can be executed in less than half the time (2.86 seconds versus 8.54). This is because we have five queries running at once rather than one at a time. In this example, each of the five queries is run and resolved within its own thread. So, rather than the total execution time being the sum of all queries plus overhead, as in the first example, the total execution time is roughly the amount of time it takes for the longest query to run plus overhead. Here is the output from Example2.java shown below.

run-example2:
    [java] query is: select sleep(2)
    [java] query is: select sleep(1)
    [java] query is: select sleep(2)
    [java] query is: select sleep(2)
    [java] query is: select sleep(1)
    [java] ConcurrentSleepyObject 1 returned 2
    [java] ConcurrentSleepyObject 2 returned 1
    [java] ConcurrentSleepyObject 3 returned 2
    [java] ConcurrentSleepyObject 4 returned 2
    [java] ConcurrentSleepyObject 5 returned 1
    [java] took: 2.86 seconds

To accomplish this, a class called ConcurrentQueryThreadImpl.java was created as a singleton class that encapsulates:

  1. The number of active queries that can run at once (five for purposes of this example).
  2. A ConcurrentHashMap to hold a list of running query threads and a reference to the domain object interface to be used to reap the results of the query. ConcurrentHashMap is a thread-safe HashMap available in the java.util.concurrent package.
  3. A second ConcurrentHashMap to hold a list of queries and domain object interfaces of queries that couldn't be immediately submitted because the maximum number of threads (five) was already running.
  4. The needed JDBC code to execute the queries.
The code fragment in Listing 2 shows the initialization of the ConcurrentQueryThreadImpl class.

The interface CanResolveAConcurrentQuery, referenced in the ConcurrentQueryThreadImpl class, is used in the ConcurrentHashMaps and simply defines two methods that must be implemented by a participant in a concurrent query (e.g., ConcurrentSleepyObject), one to process the SQL results and another (isReaped())method that the ConcurrentQuery implementation can use to indicate to the object that it has processed its SQL results and is ready to go. Below is CanResolveAConcurrentQuery.java.

package net.sourceforge.concurrentQuery.article.concurrent;

import java.sql.ResultSet;
import java.sql.SQLException;

public interface CanResolveAConcurrentQuery {
    boolean processResultSet(ResultSet rs) throws SQLException;
    void setReaped(boolean isReaped);
}

By implementing this interface, the ConcurrentSleepyObject can participate in concurrent queries. Notice that in the getValue() method the query object needs to make sure that it has been "reaped" (e.g., it either processed its results or threw an SQLException) and if not, the object must call the waitForAllQueriesToComplete() method of the ConcurrentQueryThreadImpl singleton, which submits and processes all outstanding queries. See getValue() method of ConcurrentSleepyObject shown in the following.

public class ConcurrentSleepyObject implements CanResolveA-ConcurrentQuery {

...
   public int getValue() throws SQLException {
     if (!reaped) {
       ConcurrentQueryThreadImpl.getInstance().waitForQueriesToComplete();
     }
     return value;
   }
...

This is done so that the object can be sure that its results have been processed before it can be used. The waitForAllQueriesToComplete() method won't return until all running and queued queries are finished. This way, our object can be sure that its results have been processed before continuing. A better option, though, would be to assign a token, or cookie, to each participant in a concurrent query that can be used by the object to ensure that results are ready. This way, if the results aren't ready yet, the object won't have to wait for all the other queries to finish, but could be notified when its query has completed, perhaps moving it to the front of the queue, if necessary. To keep things simple, I opted for the main -strain-and-brute-force approach of waiting for all queries to finish. The complete source for the ConcurrentSleepyObject class is in Listing 3.

Details of the ConcurrentQuery Implementation
As mentioned, this implementation uses two lists to manage queries. The first list is the threads that are currently running SQL queries and can't surpass the configured value for the application. Since each thread corresponds to a JDBC connection, you want to be careful not to set this value too high. I've used five for this example. The second list is the queued queries that haven't been able to run because the running thread list was full when the query was submitted via the runQuery() method. See Listing 4.


More Stories By Andy Pardue

Andy Pardue is a senior software developer who has specialized in the medical software industry for over 15 years, 11 years as a telecommuter from his home office in Mesquite, Texas. He can be reached at: [email protected]

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
JDJ News Desk 12/19/06 01:30:06 PM EST

Does this sound familiar? You have a domain object, perhaps for reporting purposes, that's built from a ton of JDBC queries and it takes too long to load. Nothing else happens until this object is built, so it's become a bottleneck. Even worse, each of the queries is actually well tuned, so there isn't much to gain from modifying the queries themselves - there are just too many of them. You don't want to change (or can't change) your data model, so what can be done to alleviate this problem short of a major redesign? There are several options like caching, lazy loading, resource pooling. Another worthy option would be to implement a variation of the concurrent query pattern.

@ThingsExpo Stories
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...