|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.
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
Dec. 20, 2014 06:00 AM EST Reads: 1,429
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 19, 2014 06:00 PM EST Reads: 1,969
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
Dec. 19, 2014 11:30 AM EST Reads: 2,959
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 19, 2014 11:00 AM EST Reads: 2,419
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, 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. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
Dec. 19, 2014 07:00 AM EST Reads: 2,781
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
Dec. 19, 2014 06:30 AM EST Reads: 2,795
ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ -- IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...
Dec. 19, 2014 05:00 AM EST Reads: 3,086
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
Dec. 19, 2014 04:00 AM EST Reads: 2,501
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
Dec. 18, 2014 09:45 PM EST Reads: 1,708
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 18, 2014 09:00 AM EST Reads: 2,208
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
Dec. 18, 2014 06:00 AM EST Reads: 1,263
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
Dec. 17, 2014 11:15 PM EST Reads: 2,180
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 17, 2014 11:00 PM EST Reads: 2,195
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 17, 2014 08:00 PM EST Reads: 2,187
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Dec. 17, 2014 06:30 PM EST Reads: 2,094
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...
Dec. 17, 2014 11:45 AM EST Reads: 2,291
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Dec. 16, 2014 11:45 PM EST Reads: 2,154
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
Dec. 15, 2014 11:45 PM EST Reads: 2,577
The 3rd International Internet of @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 - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Dec. 15, 2014 10:30 AM EST Reads: 8,162
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...
Dec. 15, 2014 10:00 AM EST Reads: 3,298