|By Jason Westra||
|December 1, 2000 12:00 AM EST||
Several patterns exist for generating primary keys for your EJB application. This month I'll provide a pattern for generating PKs that's scalable, generic, and portable.
My format for defining the pattern will follow the catalogued layout presented in the Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software.
Generate unique IDs for persistent objects in an EJB application
Also Known As:
PID (Persistent ID) Factory
GUID (Globally UniqueID) Manager
Enterprise JavaBeans is a server-side component model that targets the specific business domain of online transaction processing (OLTP) applications. OLTP applications generally have the need to store information persistently. The data records or objects for each transaction require unique identifiers to allow them to be stored and retrieved accurately. Thus there's a need to generate unique identifiers for the data involved in an EJB transaction processing system.
For the purposes of this pattern, I'm assuming a relational database is used as the data store rather than an object database, which would provide its own ID generator. A relational database table typically has a primary key column that's indexed to prevent duplicate IDs, which would lead to data integrity problems. Thus each row stored in the table is uniquely identifiable. For instance, in EJB the return value from the call to myHome.findByPrimaryKey is a single entity bean, not multiple entities!
There are numerous ways to generate unique IDs in a Java application. Let's review some approaches before discussing the UniqueID generator pattern presented in this article.
An easy way to generate unique IDs is to utilize the System.currentTimeMillis() method to get the current time in milliseconds and use it as your ID. Although it's an easy way to start creating applications, this approach has implications across high-volume applications. A high-volume OLTP application may perform several calls to System.currentTimeMillis() at the same time, resulting in the generation of duplicate IDs. Thus the generator must perform some sort of synchronization on ID requests. Typically, this is done with a wrapper object that uses the synchronized modifier to queue threads accessing it.
Next, you ask, "What about synchronization across multiple JVMs?" Certainly a clustered-server, multi-JVM architecture will be the norm for an enterprise application, but a clustered application poses two problems for this approach toward generating unique IDs:
- The system time on each machine may be different. Thus, in a multi-JVM architecture, calls to System.currentTimeMillis() can lead to duplicate values.
- The Java synchronize operator doesn't work across multiple JVMs, so even if the system times were equal, simultaneous calls to different machines could still result in duplicate IDs.
EntityBean Key Generator
This approach uses an entity bean to select the next value from a relational database table, which holds the latest value for unique ID generation. An entity bean can encapsulate the SQL, which it executes in a generic fashion by loading in a bean environment property containing a SQL string for each type of database. For instance, in Oracle the dual table should automatically return a sequence value. The SQL statement might look something like this:
"select mysequence.nextval from dual"
Oracle sequences are a proprietary feature and increment the value automatically for the caller by a specified increment count. Other databases that don't have this feature must increment a next ID field and select it in one call. Stored procedures are a common cure for the need to execute multiple database operations within a single request. To get the same ID generation capabilities from Microsoft SQL Server, a stored procedure could be called that both returns a value and increments it for the next caller. Since the stored procedure performs its work inside a transaction in one database request, it eliminates a "window" of opportunity when simultaneous calls for another ID get the same row and attempt to update the value.
Thus our entity bean key generator executes SQL, which it retrieved generically from its bean environment property and executed on the database. However, there are some drawbacks to this approach:
- Each call to get another ID is a remote method invocation, which can create unwanted chatter depending on where the entity bean is deployed in your system.
- Some might argue that entity beans are for business entities rather than utilitarian functionality like generating IDs for business entities.
- Few application servers provide synchronized caching across a cluster. Thus the ability to cache a set of IDs, improving ID generation by preventing database operations, is negated when the application is clustered.
A more scalable approach to ID generation that provides both local caching and guaranteed unique IDs is a singleton object that hands out IDs from its local cache (see Figure 1). Each time the cache of the singleton object is depleted, it gets a set of IDs representing the next available IDs for the application. The singleton fetches IDs from a stateless session bean that accesses the database in a portable manner, allowing it to interact with any database.
Use UniqueID Generator:
- To return a unique identifier for object and/or database row identity
- To cache sets of IDs across multiple JVMs for scalable ID generation
- To abstract database implementations from the core ID generation classes
- Singleton: Acts as the wrapper of the UniqueIDEJB and caches sets of unique IDs to prevent chatty remote invocations and database operations
- UniqueIDEJB: Component made
up of UniqueID (remote interface) and UniqueIDHome (home interface); performs generic SQL to fetch a set of IDs from the database and return them to the singleton client
- Singleton: Calls UniqueIDEJB component to fetch a set of IDs; set is cached locally and a new set is fetched when the maximum is surpassed
The UniqueID generator has several key benefits and some limitations:
- Limited remote method invocations and database operations: The UniqueID generator's singleton object caches a set of IDs that are depleted before another request is made to the UniqueIDEJB. This limits the number of remote method invocations on the EJB and the number of hits the database must handle to generate new IDs.
- Guaranteed UniqueIDs: The UniqueID generator pattern guarantees unique identifiers for your objects/data across an n-tiered solution. If a set of IDs is requested from multiple JVMs at the same time, the transaction isolation of the UniqueIDEJB and/or database layer will automatically queue multiple requests to ensure that only one singleton's request for an ID set is processed at a time.
- Portable across EJB servers: The pattern represents a component that's portable across EJB servers. It's a session bean, and session beans have been mandatory in the specification since its inception, whereas any EJB server still not up to the 1.1 version of the specification wouldn't be able to utilize an entity bean-based pattern.
- Portable across database servers: The implementation of the pattern really determines its portability, but the pattern itself allows for database-specific SQL to be loaded generically from the EJB's environment so that no code changes are required to deploy it against disparate databases.
- Singleton knows nothing about the "incrementBy" value: The singleton object knows nothing about how many IDs are returned in a set. This is controlled at the UniqueIDEJB level by an environment property. To change the incrementBy value, simply redeploy the EJB with a hot-deploy mechanism to avoid downtime and the increment will be changed to the new value without repercussions on the rest of the application.
- ID gaps: Gaps in IDs will occur with this solution. For example, if a set of 50 IDs is retrieved and the server crashes midway, 25 IDs would be lost. My recommendation is to increment only by one until ready for production, then set the UniqueIDEJB's incrementBy environment property to be sufficient for your application's load. This prevents wasting IDs in development and test.
- Support for other data types: The structure section's class diagram shows a long data type used for IDs, yet this could be any data type your application requires. However, the UniqueID generator pattern would have to be extended to account for different ID data types in a single application. For instance, if your application mixed doubles, strings, longs, and ints as keys, the singleton would have to be extended.
Consider the following issues when implementing a generic, portable UniqueID generator pattern:
- Determining incrementBy for your application: The amount of IDs contained in each ID set (and subsequently cached in the JVM) should be determined based on the number of users attempting "insert" transactions per JVM. Thus, if your incrementBy is 50 on a single J2EE server, set it to approximately 25 if you cluster two servers. Also, set incrementBy to a low number, even 1, for development and testing. As with any tunable parameter, metrics gathered from stress testing your application should ultimately drive your settings.
- Ensure portability across EJB servers: When communicating from the UniqueIDEJB to the database, don't use proprietary logic to obtain a connection from a connection pool. Use data sources looked up through JNDI instead.
- Ensuring portability across databases: There are a few ways to ensure that your code to fetch a set of IDs is portable. One way is to store the SQL that will be executed in the EJB's environment. The SQL is set in the deployment descriptor, which allows it to be modified during deployment rather than having to modify the codebase. Another option is to use data access objects (DAOs) to contain the database-specific SQL code. Last, your UniqueIDEJB component couldn't take advantage of database-specific sequence generators. Your component's implementation should create the table at runtime if it doesn't exist already. This approach isn't recommended, but it's an alternative nonetheless.
- Generating different IDs for different tables (classes): To generate a different ID for different tables, each class in the pattern would have to change its interface to take a "sequence" parameter, which indicates which class you want to get the next ID for and is forwarded throughout the pattern to the JDBC call against the database.
- Generating IDs shouldn't rely on a business transaction outcome: The UniqueIDEJB should create its own new transaction when getting an ID set. Incrementing the database to the "next ID value" shouldn't rely on whether or not the business transaction currently executing in your application succeeds or fails.
- Business transactions rely on generated ID success: An error fetching an ID set from the UniqueIDEJB will cause a business transaction to fail. Don't mix different approaches to generating unique IDs when one fails. For instance, let's say your application uses the System.currentTimeMillis() approach to key generation if the first approach, calling UniqueIDEJB, fails. This provides an extra layer of fault tolerance to your application, but you could encounter duplicate IDs! If your database counter is near the number generated by the System.currentTimeMillis(), you'll have problems.
The code in Listing 1 shows how to implement the singleton to cache the ID set, fetch a new set, and handle failures when calling the UniqueIDEJB.
This month I provided an EJB pattern to a common problem in the OLTP world, generating unique IDs. While there are variations of the pattern, the UniqueID generator overcomes many scalability and flexibility issues where other patterns fall short, such as local ID caching, limiting remote method invocations, and portability. I hope this pattern is helpful for your EJB engagement. For other EJB patterns see www.theServerSide.com. And let me know if you're interested in JDJ featuring more patterns in the future.
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
May. 23, 2015 06:00 AM EDT Reads: 4,365
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...
May. 23, 2015 06:00 AM EDT Reads: 4,468
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
May. 23, 2015 06:00 AM EDT Reads: 5,419
Advanced Persistent Threats (APTs) are increasing at an unprecedented rate. The threat landscape of today is drastically different than just a few years ago. Attacks are much more organized and sophisticated. They are harder to detect and even harder to anticipate. In the foreseeable future it's going to get a whole lot harder. Everything you know today will change. Keeping up with this changing landscape is already a daunting task. Your organization needs to use the latest tools, methods and expertise to guard against those threats. But will that be enough? In the foreseeable future attacks w...
May. 23, 2015 05:00 AM EDT Reads: 5,673
17th Cloud Expo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterprises are using some form of XaaS – software, platform, and infrastructure as a service.
May. 23, 2015 05:00 AM EDT Reads: 2,406
Cloud is not a commodity. And no matter what you call it, computing doesn’t come out of the sky. It comes from physical hardware inside brick and mortar facilities connected by hundreds of miles of networking cable. And no two clouds are built the same way. SoftLayer gives you the highest performing cloud infrastructure available. One platform that takes data centers around the world that are full of the widest range of cloud computing options, and then integrates and automates everything. Join SoftLayer on June 9 at 16th Cloud Expo to learn about IBM Cloud's SoftLayer platform, explore se...
May. 23, 2015 04:45 AM EDT Reads: 3,099
15th Cloud Expo, which took place Nov. 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA, expanded the conference content of @ThingsExpo, Big Data Expo, and DevOps Summit to include two developer events. IBM held a Bluemix Developer Playground on November 5 and ElasticBox held a Hackathon on November 6. Both events took place on the expo floor. The Bluemix Developer Playground, for developers of all levels, highlighted the ease of use of Bluemix, its services and functionality and provide short-term introductory projects that developers can complete between sessions.
May. 23, 2015 04:00 AM EDT Reads: 6,234
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo – to be held June 9-11, 2015, at the Javits Center in New York City, NY – is now accepting Hackathon proposals. Hackathon sponsorship benefits include general brand exposure and increasing engagement with the developer ecosystem. At Cloud Expo 2014 Silicon Valley, IBM held the Bluemix Developer Playground on November 5 and ElasticBox held the DevOps Hackathon on November 6. Both events took place on the expo floor. The Bluemix Developer Playground, for developers of all levels, highlighted the ease of use of...
May. 23, 2015 04:00 AM EDT Reads: 3,396
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
May. 23, 2015 04:00 AM EDT Reads: 4,815
In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway. But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years. This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles. But adding sensors and wireless connectivity won’t work in environments that demand unwavering reliability and performance. In his session at @ThingsExpo, Ron Sege, CEO of Echelon, will discuss how as enterprise IT embraces other IoT-related technology trends, enterprises with i...
May. 23, 2015 03:00 AM EDT Reads: 4,278
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
May. 23, 2015 02:45 AM EDT Reads: 6,674
We’re no longer looking to the future for the IoT wave. It’s no longer a distant dream but a reality that has arrived. It’s now time to make sure the industry is in alignment to meet the IoT growing pains – cooperate and collaborate as well as innovate. In his session at @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine the key ingredients to IoT success and identify solutions to challenges the industry is facing. The deep industry expertise behind this presentation will provide attendees with a leading edge view of rapidly emerging IoT oppor...
May. 23, 2015 02:30 AM EDT Reads: 4,919
The industrial software market has treated data with the mentality of “collect everything now, worry about how to use it later.” We now find ourselves buried in data, with the pervasive connectivity of the (Industrial) Internet of Things only piling on more numbers. There’s too much data and not enough information. In his session at @ThingsExpo, Bob Gates, Global Marketing Director, GE’s Intelligent Platforms business, to discuss how realizing the power of IoT, software developers are now focused on understanding how industrial data can create intelligence for industrial operations. Imagine ...
May. 23, 2015 02:00 AM EDT Reads: 5,176
SYS-CON Events announced today that Liaison Technologies, a leading provider of data management and integration cloud services and solutions, has been named "Silver Sponsor" of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York, NY. Liaison Technologies is a recognized market leader in providing cloud-enabled data integration and data management solutions to break down complex information barriers, enabling enterprises to make smarter decisions, faster.
May. 23, 2015 01:30 AM EDT Reads: 5,308
The 17th International Cloud Expo has announced that its Call for Papers is open. 17th International Cloud Expo, to be held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, APM, APIs, Microservices, Security, Big Data, Internet of Things, DevOps and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit your speaking proposal today!
May. 23, 2015 01:15 AM EDT Reads: 4,263
Collecting data in the field and configuring multitudes of unique devices is a time-consuming, labor-intensive process that can stretch IT resources. Horan & Bird [H&B], Australia’s fifth-largest Solar Panel Installer, wanted to automate sensor data collection and monitoring from its solar panels and integrate the data with its business and marketing systems. After data was collected and structured, two major areas needed to be addressed: improving developer workflows and extending access to a business application to multiple users (multi-tenancy). Docker, a container technology, was used to ...
May. 23, 2015 01:00 AM EDT Reads: 1,979
Hadoop as a Service (as offered by handful of niche vendors now) is a cloud computing solution that makes medium and large-scale data processing accessible, easy, fast and inexpensive. In his session at Big Data Expo, Kumar Ramamurthy, Vice President and Chief Technologist, EIM & Big Data, at Virtusa, will discuss how this is achieved by eliminating the operational challenges of running Hadoop, so one can focus on business growth. The fragmented Hadoop distribution world and various PaaS solutions that provide a Hadoop flavor either make choices for customers very flexible in the name of opti...
May. 23, 2015 12:30 AM EDT Reads: 3,755
For years, we’ve relied too heavily on individual network functions or simplistic cloud controllers. However, they are no longer enough for today’s modern cloud data center. Businesses need a comprehensive platform architecture in order to deliver a complete networking suite for IoT environment based on OpenStack. In his session at @ThingsExpo, Dhiraj Sehgal from PLUMgrid will discuss what a holistic networking solution should really entail, and how to build a complete platform that is scalable, secure, agile and automated.
May. 23, 2015 12:00 AM EDT Reads: 4,260
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, June 9-11, 2015, at the Javits Center in New York City. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be
May. 22, 2015 11:30 PM EDT Reads: 1,967
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal an...
May. 22, 2015 11:30 PM EDT Reads: 2,631