Monday, January 08, 2007

Google Vulnerability A Sign Of Web 2.0 Weakness by Larry Greenemeier

Managers must weigh security risks and protect systems as employees use Web applications from workplace computers.
A design flaw discovered earlier this week in Web-based Google applications spotlights a troublesome security trend for IT departments: what to do about protecting internal systems and data as workers access Web-based e-mail and collaborative applications using their employer's PCs.

Google's problem, first reported by the Googlified Web site and since patched by Google, resulted from the way Google software stored information in a JavaScript file on the company's servers. Prior to the patch, an attacker could overwrite the JavaScript Object Notation, or JSON, that Google used to send information from its servers to a user's client device and gain access to all of the contact information stored in a user's Gmail account, as long as that user was logged on to any Google application. This is known as a "cross-site request forgery." JSON is what makes it possible for a Web mail application to, among other things, fill in the "To:" field in an e-mail from a user's address book after the user has typed in just a few characters.

Google acknowledged that, over the New Year's weekend, it was notified of a vulnerability related to the use of JSON objects that affected several of the company's products. "These objects, if abused, can expose information unintentionally," Google

While most security experts agree that guarding Web applications, a notorious security soft spot today, is crucial for the overall well-being of systems and data, they debate whether security vulnerabilities in consumer-focused Web apps such as Web mail, instant messaging, and social networking sites such as MySpace and Facebook are a great threat to business IT systems.

Employees use Web mail and other Web-based services from their work computers, and IT managers have little control over how securely those Web applications are written. Yankee Group senior analyst Andrew Jaquith says that it's what we don't know about Web applications that make them so dangerous. "Because they aren't fully understood, they're going to attract a lot of attention from hackers," he says, adding that this should concern IT managers because "consumer-grade applications are increasingly becoming de facto parts of corporate IT infrastructures."

This means employees may be mixing IT work with pleasure in their cubicles, potentially adding work-related information to the vast repositories managed by Web mail systems. For example, whenever a user can't remember a password for a given Web site, they'll typically have that password mailed to a Web mail account because they can access that account from any
computer with an Internet connection. If these passwords are for work-related sites, Web mail security becomes a problem.

"Web mail accounts give you access to everything," says Jeremiah Grossman, founder and CTO of WhiteHat Security, a maker of Web application security assessment software. Grossman, who also worked at Yahoo as its security officer, notes that cross-site request forgeries can be used for more than poaching information from Web mail accounts. "An attacker can gain access to any account the user is logged on to," he says. "This includes Web mail address books and even bank accounts."

Under another scenario, a Web mail user's ID and password could be stolen and then used by the attacker to send bogus messages to the victim's co-workers. "All the attacker has to do is send a Web mail saying 'I'm working from home today; use my Web mail account'," McGraw says. This trick could divert all sorts of business-related information to a Web mail account.

Yet other security experts see Web mail as more of a danger for users purposely or inadvertently leaking data out of their employers' IT environments, rather than as an attack vector for malware. "Applications that your employees are going to use that are not under the control of your IT department are definitely a security concern," says 451 Group senior analyst Nick Selby. But, "if an attacker is using malware, that's already being addressed by checking endpoints and isolating infected end points," he adds.

Google, Yahoo, and other Web companies that rely on the fancy Web 2.0 features enabled by JavaScript will most likely continue to respond quickly to security vulnerabilities, although it's less comforting to know that a site known as Googlified was the first to point out the most recent problem. While it's unrealistic for IT managers to stop the use of Web applications, they should be aware of the potential threats to their IT systems and data.

'Infomania' worse than marijuana

'Infomania' worse than marijuana

Workers distracted by email and phone calls suffer a fall in IQ more than twice that found in marijuana smokers, new research has claimed. The study for computing firm Hewlett Packard warned of a rise in "infomania", with people becoming addicted to email and text messages.

Researchers found 62% of people checked work messages at home or on holiday. The firm said new technology can help productivity, but users must learn to switch computers and phones off.

Losing sleep

The study, carried out at the Institute of Psychiatry, found excessive use of technology reduced workers' intelligence. Those distracted by incoming email and phone calls saw a 10-point fall in their IQ - more than twice that found in studies of the impact of smoking marijuana, said esearchers. More than half of the 1,100 respondents said they always responded to an email "immediately" or as soon as possible, with 21% admitting they would interrupt a meeting to do so. The University of London psychologist who carried out the study, Dr Glenn Wilson, told the Daily Mail that unchecked infomania could reduce workers' mental sharpness. Those who are constantly breaking away from tasks to react to email or text messages suffer similar effects on the mind as losing a night's

Monday, January 01, 2007

Configuring Your Home Computer to Run Apache Server, PHP, MySQL, ColdFusion, and IIS

Configuring Your Home Computer to Run Apache Server, PHP, MySQL, ColdFusion, and IIS

This tutorial for installing WAMP Server (Apache, PHP, MySQL, and phpMyAdmin) was written for the students in the Web Page Design program at the Contra Costa ROP. This tutorial will cover basic server installation for web development testing purposes on your home computer. This tutorial will not cover all of the necessary security settings used to create a public web server.

We currently use three texts for web database development:

Macromedia Dreamweaver MX 2004 - ISBN 0-619-21420-1 - Covers Dreamweaver from the ground up. This text also includes an introduction to web database development using PHP/MySQL and ASP/Access. This book is required for all students in the program.

Dreamweaver MX 2004 with ASP, Coldfusion, and PHP - ISBN 0-321-24157-6 - Covers some basic Dreamweaver functions, but the reader should have some prior experience using Dreamweaver to fully comprehend the text. Students can learn the basics of three different scripting languages, PHP/MySQL, ASP/Access, and Coldfusion/Access, by completing this book. Elective course.

Sams Teach Yourself PHP, MySQL, and Apache - ISBN 0-672-32489-X - For students who would like to learn how to hand-code PHP/MySQL applications. Elective course.
Definition of Terms

PHP: Hypertext Preprocessor is a scripting language that is embedded in HTML. PHP scripting code is frequently used to connect web pages to MySQL databases to create dynamic web sites. Some popular examples of PHP driven web sites would be blogs, message boards, and Wikis. PHP files are actually plain text files; they can be created in TextPad or any other Plain Text Editor. In a text editor set the Save As type to text and save the file with a .php extension. Note: You must type the .php yourself. PHP files can also be created with Dreamweaver MX 2004. PHP is "open source" and therefore free. We use the Apache Server to work with PHP files in the classroom.

MySQL is a relational database system. MySQL uses "Structured Query Language" which is the most common database language. It is the most popular "open source" database in the World. MySQL content can be managed via a command line or a web interface. MySQL is "open source" and therefore free. We use the Apache Server to work with MySQL files in the classroom.

Coldfusion is another scripting language used to connect to databases. It performs essentially the same functions as PHP, but it is produced by Macromedia. There is a free developer edition of Coldfusion available on Macromedia's web site. We use the Apache Server to work with Coldfusion files in the classroom.

phpMyAdmin is a popular PHP driven web interface that allows you to manage your MySQL database content via a web form. It is much easier to learn to use phpMyAdmin to manage your MySQL database content than it is to edit it from the command line. phpMyAdmin is "open source" and therefore free.

Apache is a popular web server that many ISP's and individuals use to host web pages. When you install Apache on your system your machine becomes a web server. Pages stored on your system in a "special folder" are accessible on the Internet via the machine's IP address. In order for pages to be viewed on the Internet, the files must be stored in a special directory; this directory is usually called htdocs, public_html, or www. If you use a web host, you probably upload your files to a directory with one of these names. If someone else wants to access your web pages, they must know the IP Address of your machine, i.e., 179.199.9.100. Apache is "open source" and therefore free.

IIS or Internet Information Server is Microsoft's web server. It performs the same functions as Apache and is used with ASP and Access files primarily, but it can also run PHP and MySQL. It can be installed on Windows based machines (Windows 2000, Windows XP, etc.). IIS is available on the Windows installation CD. Typically you will install Apache or IIS; both servers services should not be running on your machine at the same time. IIS is needed to run ASP/Access applications.

Windows Services are used to run these servers and modules. Once services are installed they can be started and stopped via Start > Control Panel > Administrative Tools (switch to classic view if you do not see the Administrative tools) > Services. These Services can be configured to automatically start or to be started manually. The Apache Service and the IIS service should not run at the same time. This will be discussed in more detail later in the tutorial.
PHP and Coldfusion Testing Requirements

In order to test PHP and Coldfusion pages you must have Apache, MySQL, and the PHP and/or Coldfusion module installed on your own computer or have a host that supports PHP or Coldfusion. You can use your f2o.org account, but it is much easier to test your PHP pages on your local machine. If you do not have these modules installed, you would have to upload your PHP pages to your ISP to view them. The beauty of Apache, MySQL, and PHP is that they're free. If you are working in the classroom and you are creating PHP web pages, you must start the Apache Web Server at the beginning of class each day.

follow this link to get more

WAMP Installation Guide

WAMP (Windows-Apache-mySQL-PHP) is an all-in-one packages which installs
the basic programs you will need to get a localhost running and to be able to
build and run PHP scripts.

This guide will walk you through installing a WAMP package for the first time.

follow this link to get more information
http://www.eacomm.com/web/support/wamp_install/index.html

An Introduction to Salesforce.com's AppExchange-by Tony Stubblebine

This is part one of a three-part series on how to build and distribute applications on Salesforce's AppExchange.

I attended Salesforce's Dreamforce conference last month because I'd heard that Salesforce has been making a big effort to build a platform that was friendly to developers. I expected to be confronted with a pile of corporate-speak and a lot of vaporware, but what I found was much more surprising. Six different keynote presenters talked about mashups, and one-third of customers in attendance talked about wanting to build or purchase mashups. There was some corporate-speak, which these articles should cut through. The technology, however, was powerful and easy.

Two main things set Salesforce apart from other companies building development platforms. The first is that their platform is entirely "on demand", meaning there's no installed software, it runs across the internet in a software as a service model. The other is the directory of Salesforce applications called AppExchange. You can build apps and keep them within your organization -- if, for example, you work in a corporate IT department. But if you want to share your application with the world, for profit or otherwise, the AppExchange directory is the answer. It's integrated directly into all Salesforce accounts. If you build an application inside your own account, you can package it directly to the AppExchange directory. Customers who find your application on AppExchange can install it directly into their accounts. Salesforce wants to remove the burden of customer acquisition and distribution so that developers can focus on what they do best: finding and solving problems. I met a number of small companies and individual consultants who all said that Salesforce is making it easier to sell software to the corporate world.

This series of articles will show you how to build and distribute an application on AppExchange. If you're not familiar with Salesforce, then there's some basic information that you should know. I'll lay that out in this article, as well as the process for setting yourself up as a Salesforce developer, the interfaces available for building applications, and the major sources of news and reference. The next two articles will lead you through the steps of building an application and distributing it on AppExchange.
What Is Salesforce.com?

If you're not in sales, you might not even know what Salesforce.com does or even what Customer Relationship Management (CRM) is. Salesforce started out primarily offering software for sales groups to manage their customer relationships. This included simple tools like address books, which are called contacts in the Salesforce world, and more complicated processes to track potential customers from lead to sale. Sales people also like reports with charts and graphs, so those are part of the package.

The interesting point from a developer's perspective is that the underlying technology is based around database concepts, with default actions and views. Salesforce has almost completely opened up this infrastructure. Even novice users can create custom objects that are the equivalent of database tables, and add or remove fields from the default objects.

This infrastructure includes a built-in customer base, built-in distribution through the AppExchange directory, built-in data and authentication models, developer support on the AppExchange Developer Network, and a slew of programming tools. That means developers can focus on solving new problems and not reinventing solutions to old ones.

This infrastructure has been flexible enough to allow Salesforce to branch out into other business applications like marketing and customer support. It has also been flexible enough to allow customers to build their own applications in areas like financial services and human resources.

Signing Up

To get a feel for what Salesforce customers experience, you need to sign up for an account. This will also serve as a sandbox for developing your own applications. You might be tempted to sign up for the 30-day, free trial offer that is prominently advertised on their home page, but signing up for a developer account from the AppExchange Developer Network will give you an account that never expires. The account does come with a few limitations. You can only have two users, one an admin account so that you can build and install applications and the other a normal user account so you can test your work from the perspective of a normal user. The account has a 2MB data limit, which is enough space to add roughly 1500 contacts. There seem to be some other limitations--you can't send mass emails, for example--but I didn't notice any that would hinder development.

After you sign up for an account you'll be sent a confirmation email. Following the link in the email will give you your first look at your new Salesforce account.


Browse the tabs to get a sense of the default functionality that comes with a Salesforce account.

Customizing

For most Salesforce customers, customizing their Salesforce account is a common and exciting experience that feels like application building. This functionality is available in the Setup area. Here users can add and remove fields, customize templates, and even create new database tables that come with automatically created forms and views. Salesforce provides a web UI for all of this functionality.

Don't worry, as a developer you're going to be able to build applications much more powerful than what most users are creating using the Salesforce customization forms. You should, however, know how to use these. You will need this familiarity if you want to extend the data schema, install AppExchange applications, or package your own AppExchange applications.

Start by clicking the Setup link located above the tabs.

Later in this article, we'll be using this area to install an application from AppExchange. For now let's get a feel for how the Setup area works by adding a Website field to the Contacts object, as many of our friends have their own websites.

Start by choosing Customize -> Contacts -> Fields in the left navigation bar. This will show a long list of the standard fields for the Contacts object.

Edit Contact Fields

At the bottom of the list of fields is a list of custom fields and a New button. Clicking this button will start you on a four-step process for adding a field to the Contacts object.

The first step is to select a field type. I was expecting to make this a text field, but found that Salesforce has an explicit URL field type that ensures that the URL will be displayed as a link. Choose the URL field type.

The second step is to give the field a label and a name. The label is shown on displays and reports alongside the field contents. The name is what you're going to use to reference the field when you're writing code. I chose "Website" for the label and "website" for the name.

The last two steps are important if you're managing a Salesforce account with thousands of users. If that were the case, you would want to spend some time setting the access controls and templates. For our purposes, you should just choose the defaults and then save your changes. To see your handiwork, visit the Contacts tab and click the New button. You should see that your field has been automatically added to the form.

Installing an AppExchange Application

Before we can build our own application for the AppExchange, we need to figure out how to install other people's applications.

The first step is to visit the AppExchange. There are over 400 applications in the directory so far. Some of the applications require that you pay for them. Some require that you install software on your own server. But many are completely free applications that run entirely in your Salesforce instance. The Pricing section of each application entry will let you know if the application is free or not.

If you see a Get It Now button then you can install the application directly into your Salesforce account. Other applications have Download buttons instead. These are applications that you run on your desktop or server that access your Salesforce account through the API.

Let's install Salesforce for Google AdWords, an application that lets you create and track Google AdWords campaigns from within Salesforce. It's a good example of a mashup that combines an external service with the database and reporting features of Salesforce.

AdWords App Page

Click the Get It Now button to start the installation process. This will take you through a series of confirmation screens asking you to review legal terms, the contents of the package, and security settings. On step 3, choose "Grant access to all users," since we're installing into an account that doesn't have any users.

It turns out that you still have a little more work to do once you've finished the install process. You need to customize your account through the Setup area so that the new application is visible. It would be nice if applications came with a help document that walked you through this process. However, in my experience the next step is usually the same. Most applications come with their own tab, which you need to add to your visible tabs. In this case click the arrow on your last tab, which takes you to the All Tabs tab. Then click the Customize My Tabs button.

Customize Tabs

This will give you a form for moving available tabs to your selected tabs. Choose Search Campaigns from the Available Tabs list and move it to the Selected Tabs list.

Choose Search Tab

Once you have saved your choice you'll see a new Search Campaigns tab that will let you create and track AdWords campaigns.
Building Native Applications

The most common form of Salesforce application development is done entirely through the Salesforce.com interface. Native applications are built by extending Salesforce's data schema, by writing custom HTML, and by writing JavaScript. These native applications can be bundled and shared through AppExchange.

Extending the data schema can be as simple as adding a field to an existing object like we did when we added a website field to the Contact object. It can also mean creating your own objects. These are essentially database tables, called "custom objects" in Salesforce parlance. Whenever you make a schema change, Salesforce automatically creates or updates the related forms and pages. You don't need to build the standard CRUD actions like create, update, show, or list.

Like most customizations, you can add custom objects through the Setup area. Get started by visiting Setup and then Build -> Custom Objects in the left sidebar.

Add Custom Object

Salesforce has just released a book that shows how to build an example recruiting application using native application techniques. They gave away hard copies of the book for free at their Dreamforce conference, but they've also just started including a link to a PDF copy as part of an advertising campaign on TechCrunch. Until they produce a more official page, you can download the book for free from their advertisement landing page.
Building Custom Pages with S-Controls

Congratulations on graduating from the basics. Most Salesforce development happens entirely through the Salesforce web UI. This gives incredible power to customize and build applications to people who wouldn't normally have any control over their application. However, you probably want to write code. For native applications, that starts with S-Controls.

S-Controls let you write your own HTML in order to build pages and forms. S-Controls include templating variables that let you access Salesforce data. The application-building part can be done in any web application technology, like Java applets or Flash. However, most people use JavaScript.

Salesforce is putting a lot of work into their Ajax toolkit. This toolkit allows you to call back to the Salesforce API in order to read and write data to the database. The beta release includes two excellent tutorials to get you started.

The Ajax toolkit will graduate from beta in Salesforce's Winter '07 release, due out in the next few months.
Accessing Data with SOQL

Many times when you're developing for Salesforce you'll be treating it like a database. Salesforce provides an SQL-like query language called SOQL that you use in combination with the API to query data. SOQL has been limited by the ability of Salesforce to host the high volume and unpredictable data queries of its users. The Winter '07 release will eliminate the biggest limitation, finally allowing users to join multiple tables. The other difference you'll notice right away is that queries won't return the full result of a large data set. Instead you'll have to use queryMore until you've retrieved everything you need.

The developer documentation has the basic syntax.
The Salesforce API

So far, we've been talking about building applications that are limited to filling out web forms and writing JavaScript. If you'd rather build an application in your favorite programming language, then you should plan on hosting the application on your own server and treating Salesforce as a database that you access through their API. This way you can access the data that your company or client is entering into the Salesforce application without having to be an expert yourself.

The Salesforce Projects and Toolkits page lists toolkits for almost every language including Java, .NET, Perl, PHP, and Ruby. Many of the toolkits hide the API behind a traditional Object Relational Model.

Before you get started, you need to generate and download a Salesforce WSDL file. Do this by going to the Setup area and then to Integrate -> AppExchange API.

Here's an example Perl script that would list the names, emails, and websites of all of our contacts. You could get going with a similar few lines of code in almost any language.

use WWW::Salesforce::Simple;

my $sforce = WWW::Salesforce::Simple->new(
'username' => $user,
'password' => $pass,
);

my $query = "select FirstName, LastName, Email, website__c from Contact";
my $res = $sforce->do_query($query);

foreach my $field ( @{ $res } ) {
print $field->{'FirstName'} . "\n"
. $field->{'LastName'} . "\n"
. $field->{'Email'} . "\n"
. $field->{'website__c'} . "\n";
}

The developer docs will probably be your main reference when using the API.
Getting More Information

Developers will probably spend most of their research time referring to the documentation on the AppExchange Developer Network. However, there are several other important sources of information.

Salesforce hosts very active developer forums. You can get most any question about the API or the toolkit answered there. Many members of Salesforce's API and development teams also spend time there, so you're likely to get the inside scoop or even influence the direction of the product.

There's also two popular blogs that cover Salesforce and AppExchange development. Mark Mangano summarizes Salesforce news at SalesForceWatch by monitoring nearly a hundred RSS feeds. Scott Hemmeter talks about his experiences as a developer and Salesforce consultant at Perspectives on Salesforce. You should probably also subscribe to the official AppExchange blog.

If you're looking for a job as a Salesforce consultant or developer, you will want to watch the job board section of the developer forums. If you're looking to build a product that you can sell on AppExchange, then you should definitely check out Salesforce's IdeaExchange. Salesforce built IdeaExchange so that customers could submit feature requests and other customers could rate the requests, Digg-style. This is a gold mine for product ideas. Salesforce knows they can't develop all of these ideas themselves. That's why they're putting so much effort into encouraging an active developer community.
The Future

The Winter ’07 release of Salesforce will be out within a few months. This release will introduce many powerful new development features including inline S-Controls, improved Ajax support, improved SOQL, and external outbound messaging. Soon after the release, Salesforce will release the beta of a new programming language called Apex that runs on the Salesforce servers. This will let you write validation rules, triggers, and stored procedures. They’re re-branding the development platform Apex as well, not to be confused with their new programming language.

On the development roadmap is a JavaScript proxy that will let you access external APIs from JavaScript running on Salesforce hosted pages. This will eliminate one of the major challenges to building JavaScript-powered mashups.

One clearly missing feature of AppExchange is the ability to bill your customers. If you want to charge for your product, you're going to have to build the infrastructure yourself. The good news is that the people I talked to at Salesforce recognized this as a key service to enable developers to make a living by focusing on what they do best. It's not on the development road map yet, but it should be.

In the next article, we'll build a Salesforce application using the Salesforce API and add that application to the AppExchange.

(http://www.oreillynet.com/pub/a/network/2006/11/13/an-introduction-to-saleforcecoms-appexchange.html)

New to Java Programming Center - Step-by-Step Programming

Read through the listings of learning materials, or create a customized page specific to your interests.
Contents

* General JavaTechnology Programming
Learn or brush-up on language syntax, basics, and OOP concepts.
* Using Java Technologies
Create a customized list of learning materials on specific Java technologies.


The following articles cover general areas of the Java platform such as the basics of the Java programming language, applets, applications, and servlets.

Getting Started with NetBeans, Part 1 by Dana Nourie
Learn how to use NetBeans IDE basic features, such as the drag-and-drop Form Editor, the Source Editor, and the Properties pane by creating a simple GUI application that calculates overtime pay.

Getting Started with an IDE by Dana Nourie
Which IDE is for you: Java Studio Creator, Java Studio Enterprise, or NetBeans? Discover the advantages and differences in the three IDEs that Sun Microsystems supports. (March 2005)

Build an Application, Part 1 by Dana Nourie
Learn about classes, objects, and methods in the first part of this tutorial that teaches Java technologies and how they fit together in a dive log application.
Course Catalog
Take live, virtual, and web-based courses to learn all you can about the Java programming language and platform.

Building an Application, Part 2 by Dana Nourie
Part 2 of this tutorial series introduces inheritance, image and text objects, and how to arrange those objects using a layout manager.

Building an Application, Part 3 by Dana Nourie
Learn to receive user input through text fields and check boxes, and the basics event handling to give buttons functionality.

Building an Application, Part 4 by Dana Nourie
Create scroll bars and pop-up option boxes, and learn to read from and write to files with Java I/O.

Building an Application, Part 5 by Dana Nourie
Writing Objects to Files, Using String Arrays, and More on GUI Components.

The Java Workbook
Practice what you've learned and learn something new by visiting the Java Workbook. The Java workbook covers exercises spanning from data structures and flow control to applets and error handling.

Language Essentials Short Course by jGuru
A familiarity with some structured programming language like C, C++, or Pascal is beneficial. While the course is introductory in nature, some exposure to structured programming is practically mandatory.

Trail: Learning the Java Language by Mary Campione and Kathy Walrath
From the Java Tutorial, this trail covers the fundamentals of programming in the Java language in an easy-to-use format. A must-read for anyone interested in learning this robust platform.

The Java Language Environment: A White Paper by James Gosling and Henry McGilton
This paper, co-authored by one of the founders of the Java programming language, details the history, features, and structure of the Java programming language.

Essentials of the Java Programming Language: A Hands-On Guide, Part 1 by Monica Pawlan
Learn how applications, applets, and servlets are similar and different, how to build a basic user interface that handles simple end user input, how to read data from and write data to files and databases, and how to send and receive data over the network.

Essentials of the Java Programming Language: A Hands-On Guide, Part 2 by Monica Pawlan
Part II walks you through network communications, building a user interface using more components, data encryption and decryption (pseudo code only), grouping multiple data elements into one object (collections), and internationalizing a program.

The Java Tutorial by Mary Campione and Kathy Walrath
As part of the Java Series of books by Sun Microsystems, The Java Tutorial contains the Getting Started trail and six Trails covering the Basics. This book walks you through the process of writing a variety of applications with explanation and code samples.
Using Java Technologies

Learn how to use Java technology for desktop applications, applets, wireless devices, database connectivity, server communication, and more.


(http://java.sun.com/developer/onlineTraining/new2java/stepbystep.html)

Job scheduling with Quartz-The Quartz API takes a multifaceted approach to job scheduling in Java applications

Michael Lipton, Software Engineer, IBM
Soobaek Jang (sjang@us.ibm.com), IT Architect/Integration, IBM

21 Nov 2006

Quartz is an open source project that offers an extensive set of job scheduling features. In this article, software engineer Michael Lipton and IT architect Soobaek Jang introduce the Quartz API, starting with a general overview of the framework and concluding with a series of code examples that illustrate its fundamental features. After reading this article and following the code examples, you should feel capable of incorporating the basic features of Quartz into any Java™ application.

As modern Web applications continue to grow in scope and complexity, each underlying component of the applications must similarly grow. Job scheduling is a common requirement for Java applications in modern systems, and so is a constant preoccupation for Java developers. While current scheduling technology has evolved from more primitive methods of database trigger flags and separate scheduler threads, job scheduling is still a non-trivial problem. One of the most desirable solutions to this problem is the Quartz API from OpenSymphony.

Quartz is an open source job scheduling framework that provides simple but powerful mechanisms for job scheduling in Java applications. Quartz allows developers to schedule jobs by time interval or by time of day. It implements many-to-many relationships for jobs and triggers and can associate multiple jobs with different triggers. Applications that incorporate Quartz can reuse jobs from different events and also group multiple jobs for a single event. While you can configure Quartz through a property file (in which you can specify a data source for JDBC transactions, global job and/or trigger listeners, plug-ins, thread pools, and more) it is not at all integrated with the application server's context or references. One result of this is that jobs do not have access to the Web server's internal functions; in the case of the WebSphere application server, for example, Quartz-scheduled jobs cannot interfere with the server's Dyna-cache and data sources.

This article introduces the Quartz API using a series of code examples to illustrate mechanisms such as jobs, triggers, job stores, and properties.

Getting started

To start using Quartz, you need to configure your project with the Quartz API. The procedure is as follows:

1. Download the Quartz API.
2. Extract and place the quartz-x.x.x.jar into your project folder, or put the file into your project classpath.
3. Place the jar files from the core and/or optional folder into your project folder or project classpath.
4. If using JDBCJobStore, place all JDBC jar files into your project folder or project classpath.

For your convenience, we have compiled all the necessary files, including the DB2 JDBC files, into a single zip. See the Downloads section to download the code.

Now let's look at the main components of the Quartz API.


Jobs and triggers

The two fundamental units of Quartz's scheduling package are jobs and triggers. A job is an executable task that can be scheduled, while a trigger provides a schedule for a job. While these two entities could easily have been combined, their separation in Quartz is both intentional and beneficial.

By keeping the work to be performed separate from its scheduling, Quartz allows you to change the scheduled trigger for a job without losing the job itself, or the context around it. Also, any singular job can have many triggers associated with it.


Example 1: Jobs

You can make a Java class executable by implementing the org.quartz.job interface. An example of a Quartz job is given in Listing 1. This class overriddes the execute(JobExecutionContext context) method with a very simple output statement. The method can contain any code we might wish to execute. (All the code samples are based on Quartz 1.5.2, the stable release at the time of this writing.)

Listing 1. SimpleQuartzJob.java

package com.ibm.developerworks.quartz;

import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class SimpleQuartzJob implements Job {

public SimpleQuartzJob() {
}

public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("In SimpleQuartzJob - executing its JOB at "
+ new Date() + " by " + context.getTrigger().getName());
}
}


Notice that the execute method takes a JobExecutionContext object as an argument. This object provides the runtime context around the job instance. Specifically, it gives access to the scheduler and trigger, which collaborated to initiate execution of the job as well as the job's JobDetail object. Quartz separates the execution and the surrounding state of a job by placing the state in a JobDetail object and having the JobDetail constructor initiate an instance of a job. The JobDetail object stores the job's listeners, group, data map, description, and other properties of the job.


Example 2: Simple triggers

A trigger develops a schedule for job execution. Quartz offers a few different trigger options of varying complexity. The SimpleTrigger in Listing 2 introduces the fundamentals of triggers:

Listing 2. SimpleTriggerRunner.java

public void task() throws SchedulerException
{
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();

// current time
long ctime = System.currentTimeMillis();

// Initiate JobDetail with job name, job group, and executable job class
JobDetail jobDetail =
new JobDetail("jobDetail-s1", "jobDetailGroup-s1", SimpleQuartzJob.class);
// Initiate SimpleTrigger with its name and group name
SimpleTrigger simpleTrigger =
new SimpleTrigger("simpleTrigger", "triggerGroup-s1");
// set its start up time
simpleTrigger.setStartTime(new Date(ctime));
// set the interval, how often the job should run (10 seconds here)
simpleTrigger.setRepeatInterval(10000);
// set the number of execution of this job, set to 10 times.
// It will run 10 time and exhaust.
simpleTrigger.setRepeatCount(100);
// set the ending time of this job.
// We set it for 60 seconds from its startup time here
// Even if we set its repeat count to 10,
// this will stop its process after 6 repeats as it gets it endtime by then.
//simpleTrigger.setEndTime(new Date(ctime + 60000L));
// set priority of trigger. If not set, the default is 5
//simpleTrigger.setPriority(10);
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, simpleTrigger);

// start the scheduler
scheduler.start();
}



Listing 2 starts by instantiating a SchedulerFactory and getting the scheduler. As we discussed earlier, the JobDetail object is created by taking the Job as an argument to its constructor. As implied by its name, the SimpleTrigger instance is quite primitive. After creating the object, we set a few basic properties scheduling the job for execution immediately and then to repeat every 10 seconds until the job had been executed 100 times.

There are a number of other ways to manipulate a SimpleTrigger. In addition to a specified number of repeats and a specified repeat interval, you may schedule jobs to execute at a specific calendar time, given a maximum time of execution, or given a priority, which we discuss below. The maximum time of execution overrides a specified number of repeats, thus ensuring that a job does not run past the maximum time.


Example 3: Cron triggers

A CronTrigger allows for more specific scheduling than a SimpleTrigger and is still not very complex. Based on cron expressions, CronTriggers allow for calendar-like repeat intervals rather than uniform repeat intervals -- a major improvement over SimpleTriggers.

Cron expressions consist of the following seven fields:

* Seconds
* Minutes
* Hours
* Day-of-month
* Month
* Day-of-week
* Year (optional field)

Special characters

Cron triggers utilize a series of special characters, as follows:

* The backslash (/) character denotes value increments. For example, "5/15" in the seconds field means every 15 seconds starting at the fifth second.

* The question (?) character and the letter-L (L) character are permitted only in the day-of-month and day-of-week fields. The question character indicates that the field should hold no specific value. Therefore, if you specify the day-of-month, you can insert a "?" in the day-of-week field to indicate that the day-of-week value is inconsequential. The letter-L character is short for last. Placed in the day-of-month field, this schedules execution for the last day of the month. In the day-of-week field, an "L" is equivalent to a "7" if placed by itself or means the last instance of the day-of-week in the month. So "0L" would schedule execution for the last Sunday of the month.

* The letter-W (W) character in the day-of-month field schedules execution on the weekday nearest to the value specified. Placing "1W" in the day-of month field schedules execution for the weekday nearest the first of the month.

* The pound (#) character specifies a particular instance of a weekday for a given month. Placing "MON#2" in the day-of-week field schedules a task on the second Monday of the month.

* The asterisk (*) character is a wildcard character and indicates that every possible value can be taken for that specific field.

All of these definitions may seem daunting, but cron expressions become simple after just a few minutes of practice.

Listing 3 shows an example of a CronTrigger. Notice that the instantiation of the SchedulerFactory, Scheduler, and JobDetail are identical to that found in the SimpleTrigger example. In this case, we have only changed the trigger. The cron expression we have specified here ("0/5 * * * * ?") schedules the task for execution every 5 seconds.

Listing 3. CronTriggerRunner.java

public void task() throws SchedulerException
{
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();

// current time
long ctime = System.currentTimeMillis();

// Initiate JobDetail with job name, job group, and executable job class
JobDetail jobDetail =
new JobDetail("jobDetail2", "jobDetailGroup2", SimpleQuartzJob.class);
// Initiate CronTrigger with its name and group name
CronTrigger cronTrigger = new CronTrigger("cronTrigger", "triggerGroup2");
try {
// setup CronExpression
CronExpression cexp = new CronExpression("0/5 * * * * ?");
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
} catch (Exception e) {
e.printStackTrace();
}
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);

// start the scheduler
scheduler.start();
}


Advanced Quartz

You can access a vast amount of functionality using only jobs and triggers as detailed above. Quartz is a comprehensive and flexible scheduling package, however, offering much more functionality to those who choose to explore it. The next sections discuss some of the advanced features of Quartz.

Job stores

Quartz offers two different means by which to store the data associated with jobs and triggers in memory or a database. The former, an instance of the RAMJobStore class, is the default setting. This job store is the easiest to use and offers the best performance because all data is stored in memory. This method's major deficiency is lack of data persistence. Because the data is stored in RAM, all information will be lost upon an application or system crash.

To remedy this problem, Quartz offers the JDBCJobStore. As the name infers, this job store places all data in a database through JDBC. The trade-off for data persistence is a lower level of performance, as well as a higher level of complexity.

Setting up JDBCJobStore

You have seen a RAMJobStore instance at work in the previous examples. Because it is the default job store, it is clear that no additional setup is required to use it. Using the JDBCJobStore requires some initialization, however.

Setting up the JDBCJobStore for use in your applications requires two steps: First you must create the database tables to be used by the job store. The JDBCJobStore is compatible with all major databases, and Quartz offers a series of table-creation SQL scripts that ease the setup process. You will find table-creation SQL scripts in the "docs/dbTables" directory of the Quartz distribution. Second, you must define some properties, shown in Table 1:

Table 1. JDBCJobStore properties
Property name Value
org.quartz.jobStore.class org.quartz.impl.jdbcjobstore.JobStoreTX (or JobStoreCMT)
org.quartz.jobStore.tablePrefix QRTZ_ (optional, customizable)
org.quartz.jobStore.driverDelegateClass org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.dataSource qzDS (customizable)
org.quartz.dataSource.qzDS.driver com.ibm.db2.jcc.DB2Driver (could be any other database driver)
org.quartz.dataSource.qzDS.url jdbc:db2://localhost:50000/QZ_SMPL (customizable)
org.quartz.dataSource.qzDS.user db2inst1 (place userid for your own db)
org.quartz.dataSource.qzDS.password pass4dbadmin (place your own password for user)
org.quartz.dataSource.qzDS.maxConnections 30

Listing 4 illustrates the data persistence offered by the JDBCJobStore. As in previous examples, we started by initializing the SchedulerFactory and the Scheduler. Next, rather than initialize a job and trigger, we fetched the list of trigger group names and then, for each trigger group name, the list of trigger names. Note that each existing job should be rescheduled using the Scheduler.reschedule() method. Simply reinitializing a job that was terminated in a previous application run does not accurately load the trigger's properties.

Listing 4. JDBCJobStoreRunner.java

public void task() throws SchedulerException
{
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();

String[] triggerGroups;
String[] triggers;

triggerGroups = scheduler.getTriggerGroupNames();
for (int i = 0; i < triggerGroups.length; i++) {
triggers = scheduler.getTriggerNames(triggerGroups[i]);
for (int j = 0; j < triggers.length; j++) {
Trigger tg = scheduler.getTrigger(triggers[j], triggerGroups[i]);

if (tg instanceof SimpleTrigger && tg.getName().equals("simpleTrigger")) {
((SimpleTrigger)tg).setRepeatCount(100);
// reschedule the job
scheduler.rescheduleJob(triggers[j], triggerGroups[i], tg);
// unschedule the job
//scheduler.unscheduleJob(triggersInGroup[j], triggerGroups[i]);
}
}
}

// start the scheduler
scheduler.start();
}


Running JDBCJobStore

When we run our example for the first time, the trigger is initialized in the database. Figure 1 shows the database after the trigger has been initialized but before the trigger has been fired. Therefore the REPEAT_COUNT is set to 100, based on the setRepeatCount() method in Listing 4 and TIMES_TRIGGERED is 0. After letting the application run for a while, it is stopped.

Figure 1. Data in the database using JDBCJobStore (before run)
Before run with JDBCJobStore

Figure 2 shows the database after the application has been stopped. In this figure, TIMES_TRIGGERED is set to 19, which denotes the number of times that the job was run.

Figure 2. The same data after 19 iterations
After first 19 iterations

When we start the application again, the REPEAT_COUNT is updated. This is apparent in Figure 3. Here we see that REPEAT_COUNT is updated to 81, so the new REPEAT_COUNT is equal to the previous REPEAT_COUNT value minus the previous TIMES_TRIGGERED value. Furthermore, we see that in Figure 3 the new TIMES_TRIGGERED value is 7, indicating that the job has been triggered seven more times since the application was restarted.

Figure 3. Data after the second run of 7 iterations
After the second run for 7 iterations

After stopping the application again, the REPEAT_COUNT value is again updated. This is shown in Figure 4, where the application has been stopped and not yet restarted. Again, the REPEAT_COUNT value is updated by subtracting the previous TIMES_TRIGGERED value from the previous REPEAT_COUNT value.

Figure 4. Initial data before running the trigger again
Initial data before running the trigger again

Using properties

As you have seen with the JDBCJobStore, you can use a number of properties to fine-tune the behavior of Quartz. You should specify these properties in the quartz.properties file. See Resources for a listing of configurable properties. Listing 5 shows a sample of properties used for the JDBCJobStore example:

Listing 5. quartz.properties

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

# Using RAMJobStore
## if using RAMJobStore, please be sure that you comment out the following
## - org.quartz.jobStore.tablePrefix,
## - org.quartz.jobStore.driverDelegateClass,
## - org.quartz.jobStore.dataSource
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

# Using JobStoreTX
## Be sure to run the appropriate script(under docs/dbTables) first to create tables
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX

# Configuring JDBCJobStore with the Table Prefix
org.quartz.jobStore.tablePrefix = QRTZ_

# Using DriverDelegate
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate

# Using datasource
org.quartz.jobStore.dataSource = qzDS

# Define the datasource to use
org.quartz.dataSource.qzDS.driver = com.ibm.db2.jcc.DB2Driver
org.quartz.dataSource.qzDS.URL = jdbc:db2://localhost:50000/dbname
org.quartz.dataSource.qzDS.user = dbuserid
org.quartz.dataSource.qzDS.password = password
org.quartz.dataSource.qzDS.maxConnections = 30

In conclusion

The Quartz job scheduling framework offers the best of both worlds: an API that is both comprehensively powerful and easy to use. Quartz can be used for simple job triggering as well as complex JDBC persistent job storage and execution. OpenSymphony has successfully filled a void in the open source universe by making the otherwise tedious chore of job scheduling trivial for developers.

Double-checked locking and the Singleton pattern-A comprehensive look at this broken programming idiom

Peter Haggar (haggar@us.ibm.com), Senior Software Engineer, IBM

01 May 2002

All programming languages have their share of idioms. Many are useful to know and use, and programmers spend valuable time creating, learning, and implementing them. The problem is that some idioms are later proven not to be all that they were purported, or to simply not work as described. The Java programming language contains several useful programming idioms. It also contains some that further study has shown should not be used. Double-checked locking is one such idiom that should never be used. In this article, Peter Haggar examines the roots of the double-checked locking idiom, why it was developed, and why it doesn't work.

Editor's note: This article refers to the Java Memory Model before it was revised for Java 5.0; statements about memory ordering may no longer be correct. However, the double-checked locking idiom is still broken under the new memory model.

The Singleton creation pattern is a common programming idiom. When used with multiple threads, you must use some type of synchronization. In an effort to create more efficient code, Java programmers created the double-checked locking idiom to be used with the Singleton creation pattern to limit how much code is synchronized. However, due to some little-known details of the Java memory model, this double-checked locking idiom is not guaranteed to work. Instead of failing consistently, it will fail sporadically. In addition, the reasons for its failure are not obvious and involve intimate details of the Java memory model. These facts make a code failure due to double-checked locking very difficult to track down. In the remainder of this article, we'll examine the double-checked locking idiom in detail to understand just where it breaks down.

Singleton creation idiom

To understand where the double-checked locking idiom originated, you must understand the common singleton creation idiom, which is illustrated in Listing 1:


Listing 1. Singleton creation idiom

import java.util.*;
class Singleton
{
private static Singleton instance;
private Vector v;
private boolean inUse;

private Singleton()
{
v = new Vector();
v.addElement(new Object());
inUse = true;
}

public static Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
}


The design of this class ensures that only one Singleton object is ever created. The constructor is declared private and the getInstance() method creates only one object. This implementation is fine for a single-threaded program. However, when multiple threads are introduced, you must protect the getInstance() method through synchronization. If the getInstance() method is not protected, it is possible to return two different instances of the Singleton object. Consider two threads calling the getInstance() method concurrently and the following sequence of events:

1. Thread 1 calls the getInstance() method and determines that instance is null at //1.

2. Thread 1 enters the if block, but is preempted by thread 2 before executing the line at //2.

3. Thread 2 calls the getInstance() method and determines that instance is null at //1.

4. Thread 2 enters the if block and creates a new Singleton object and assigns the variable instance to this new object at //2.

5. Thread 2 returns the Singleton object reference at //3.

6. Thread 2 is preempted by thread 1.

7. Thread 1 starts where it left off and executes line //2 which results in another Singleton object being created.

8. Thread 1 returns this object at //3.

The result is that the getInstance() method created two Singleton objects when it was supposed to create only one. This problem is corrected by synchronizing the getInstance() method to allow only one thread to execute the code at a time, as shown in Listing 2:


Listing 2. Thread-safe getInstance() method

public static synchronized Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}


The code in Listing 2 works fine for multithreaded access to the getInstance() method. However, when you analyze it you realize that synchronization is required only for the first invocation of the method. Subsequent invocations do not require synchronization because the first invocation is the only invocation that executes the code at //2, which is the only line that requires synchronization. All other invocations determine that instance is non-null and return it. Multiple threads can safely execute concurrently on all invocations except the first. However, because the method is synchronized, you pay the cost of synchronization for every invocation of the method, even though it is only required on the first invocation.

In an effort to make this method more efficient, an idiom called double-checked locking was created. The idea is to avoid the costly synchronization for all invocations of the method except the first. The cost of synchronization differs from JVM to JVM. In the early days, the cost could be quite high. As more advanced JVMs have emerged, the cost of synchronization has decreased, but there is still a performance penalty for entering and leaving a synchronized method or block. Regardless of the advancements in JVM technology, programmers never want to waste processing time unnecessarily.

Because only line //2 in Listing 2 requires synchronization, we could just wrap it in a synchronized block, as shown in Listing 3:


Listing 3. The getInstance() method

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) {
instance = new Singleton();
}
}
return instance;
}


The code in Listing 3 exhibits the same problem as demonstrated with multiple threads and Listing 1. Two threads can get inside of the if statement concurrently when instance is null. Then, one thread enters the synchronized block to initialize instance, while the other is blocked. When the first thread exits the synchronized block, the waiting thread enters and creates another Singleton object. Note that when the second thread enters the synchronized block, it does not check to see if instance is non-null.


Back to top


Double-checked locking

To fix the problem in Listing 3, we need a second check of instance. Thus, the name "double-checked locking." Applying the double-checked locking idiom to Listing 3 results in Listing 4.


Listing 4. Double-checked locking example

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
if (instance == null) //2
instance = new Singleton(); //3
}
}
return instance;
}


The theory behind double-checked locking is that the second check at //2 makes it impossible for two different Singleton objects to be created as occurred in Listing 3. Consider the following sequence of events:

1. Thread 1 enters the getInstance() method.

2. Thread 1 enters the synchronized block at //1 because instance is null.

3. Thread 1 is preempted by thread 2.

4. Thread 2 enters the getInstance() method.

5. Thread 2 attempts to acquire the lock at //1 because instance is still null. However, because thread 1 holds the lock, thread 2 blocks at //1.

6. Thread 2 is preempted by thread 1.

7. Thread 1 executes and because instance is still null at //2, creates a Singleton object and assigns its reference to instance.

8. Thread 1 exits the synchronized block and returns instance from the getInstance() method.

9. Thread 1 is preempted by thread 2.

10. Thread 2 acquires the lock at //1 and checks to see if instance is null.

11. Because instance is non-null, a second Singleton object is not created and the one created by thread 1 is returned.

The theory behind double-checked locking is perfect. Unfortunately, reality is entirely different. The problem with double-checked locking is that there is no guarantee it will work on single or multi-processor machines.

The issue of the failure of double-checked locking is not due to implementation bugs in JVMs but to the current Java platform memory model. The memory model allows what is known as "out-of-order writes" and is a prime reason why this idiom fails.


Back to top


Out-of-order writes

To illustrate the problem, you need to re-examine line //3 from Listing 4 above. This line of code creates a Singleton object and initializes the variable instance to refer to this object. The problem with this line of code is that the variable instance can become non-null before the body of the Singleton constructor executes.

Huh? That statement might be contradictory to everything you thought possible, but it is, in fact, the case. Before explaining how this happens, accept this fact for a moment while examining how this breaks the double-checked locking idiom. Consider the following sequence of events with the code in Listing 4:

1. Thread 1 enters the getInstance() method.

2. Thread 1 enters the synchronized block at //1 because instance is null.

3. Thread 1 proceeds to //3 and makes instance non-null, but before the constructor executes.

4. Thread 1 is preempted by thread 2.

5. Thread 2 checks to see if instance is null. Because it is not, thread 2 returns the instance reference to a fully constructed, but partially initialized, Singleton object.

6. Thread 2 is preempted by thread 1.

7. Thread 1 completes the initialization of the Singleton object by running its constructor and returns a reference to it.

This sequence of events results in a period of time where thread 2 returned an object whose constructor had not executed.

To show how this occurs, consider the following pseudo code for the line: instance =new Singleton();

mem = allocate(); //Allocate memory for Singleton object.
instance = mem; //Note that instance is now non-null, but
//has not been initialized.
ctorSingleton(instance); //Invoke constructor for Singleton passing
//instance.


This pseudo code is not only possible, but is exactly what happens on some JIT compilers. The order of execution is perceived to be out of order, but is allowed to happen given the current memory model. The fact that JIT compilers do just this makes the issues of double-checked locking more than simply an academic exercise.

To demonstrate this, consider the code in Listing 5. It contains a stripped-down version of the getInstance() method. I've removed the "double-checkedness" to ease our review of the assembly code produced (Listing 6). We are interested only in seeing how the line instance=new Singleton(); is compiled by the JIT compiler. In addition, I've provided a simple constructor to make it clear when the constructor is run in the assembly code.


Listing 5. Singleton class to demonstrate out-of-order writes

class Singleton
{
private static Singleton instance;
private boolean inUse;
private int val;

private Singleton()
{
inUse = true;
val = 5;
}
public static Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
}


Listing 6 contains the assembly code produced by the Sun JDK 1.2.1 JIT compiler for the body of the getInstance() method from Listing 5.


Listing 6. Assembly code produced from code in Listing 5

;asm code generated for getInstance
054D20B0 mov eax,[049388C8] ;load instance ref
054D20B5 test eax,eax ;test for null
054D20B7 jne 054D20D7
054D20B9 mov eax,14C0988h
054D20BE call 503EF8F0 ;allocate memory
054D20C3 mov [049388C8],eax ;store pointer in
;instance ref. instance
;non-null and ctor
;has not run
054D20C8 mov ecx,dword ptr [eax]
054D20CA mov dword ptr [ecx],1 ;inline ctor - inUse=true;
054D20D0 mov dword ptr [ecx+4],5 ;inline ctor - val=5;
054D20D7 mov ebx,dword ptr ds:[49388C8h]
054D20DD jmp 054D20B0


Note: To reference the lines of assembly code in the following explanation, I refer to the last two values of the instruction address because they all begin with 054D20. For example, B5 refers to test eax,eax.

The assembly code is produced by running a test program that calls the getInstance() method in an infinite loop. While the program runs, run the Microsoft Visual C++ debugger and attach it to the Java process representing the test program. Then, break the execution and find the assembly code representing the infinite loop.

The first two lines of assembly code at B0 and B5 load the instance reference from memory location 049388C8 into eax and test for null. This corresponds to the first line of the getInstance() method in Listing 5. The first time this method is called, instance is null and the code proceeds to B9 . The code at BE allocates the memory from the heap for the Singleton object and stores a pointer to that memory in eax. The next line, C3, takes the pointer in eax and stores it back into the instance reference at memory location 049388C8. As a result, instance is now non-null and refers to a valid Singleton object. However, the constructor for this object has not run yet, which is precisely the situation that breaks double-checked locking. Then at line C8, the instance pointer is dereferenced and stored in ecx. Lines CA and D0 represent the inline constructor storing the values true and 5 into the Singleton object. If this code is interrupted by another thread after executing line C3 but before completing the constructor, double-checked locking fails.

Not all JIT compilers generate the code as above. Some generate code such that instance becomes non-null only after the constructor executes. Both the IBM SDK for Java technology, version 1.3 and the Sun JDK 1.3 produce code such as this. However, this does not mean you should use double-checked locking in these instances. There are other reasons it could fail. In addition, you do not always know which JVMs your code will run on, and the JIT compiler could always change to generate code that breaks this idiom.


Back to top


Double-checked locking: Take two

Given that the current double-checked locking code does not work, I've put together another version of the code, shown in Listing 7, to try to prevent the out-of-order write problem you just saw.


Listing 7. Attempting to solve the out-of-order write problem

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
Singleton inst = instance; //2
if (inst == null)
{
synchronized(Singleton.class) { //3
inst = new Singleton(); //4
}
instance = inst; //5
}
}
}
return instance;
}


Looking at the code in Listing 7 you should realize that things are getting a little ridiculous. Remember, double-checked locking was created as a way to avoid synchronizing the simple three-line getInstance() method. The code in Listing 7 has gotten out of hand. In addition, the code does not fix the problem. Careful examination reveals why.

This code is trying to avoid the out-of-order write problem. It tries to do this by introducing the local variable inst and a second synchronized block. The theory works as follows:

1. Thread 1 enters the getInstance() method.

2. Because instance is null, thread 1 enters the first synchronized block at //1.

3. The local variable inst gets the value of instance, which is null at //2.

4. Because inst is null, thread 1 enters the second synchronized block at //3.

5. Thread 1 then begins to execute the code at //4, making inst non-null but before the constructor for Singleton executes. (This is the out-of-order write problem we just saw.)

6. Thread 1 is preempted by Thread 2.

7. Thread 2 enters the getInstance() method.

8. Because instance is null, thread 2 attempts to enter the first synchronized block at //1. Because thread 1 currently holds this lock, thread 2 blocks.

9. Thread 1 then completes its execution of //4.

10. Thread 1 then assigns a fully constructed Singleton object to the variable instance at //5 and exits both synchronized blocks.

11. Thread 1 returns instance.

12. Thread 2 then executes and assigns instance to inst at //2.

13. Thread 2 sees that instance is non-null, and returns it.

The key line here is //5. This line is supposed to ensure that instance will only ever be null or refer to a fully constructed Singleton object. The problem occurs where theory and reality run orthogonal to one another.

The code in Listing 7 doesn't work because of the current definition of the memory model. The Java Language Specification (JLS) demands that code within a synchronized block not be moved out of a synchronized block. However, it does not say that code not in a synchronized block cannot be moved into a synchronized block.

A JIT compiler would see an optimization opportunity here. This optimization would remove the code at //4 and the code at //5, combine it and generate the code shown in Listing 8:


Listing 8. Optimized code from Listing 7

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
Singleton inst = instance; //2
if (inst == null)
{
synchronized(Singleton.class) { //3
//inst = new Singleton(); //4
instance = new Singleton();
}
//instance = inst; //5
}
}
}
return instance;
}


If this optimization takes place, you have the same out-of-order write problem we discussed earlier.


Back to top


volatile anyone?

Another idea is to use the keyword volatile for the variables inst and instance. According to the JLS (see Resources), variables declared volatile are supposed to be sequentially consistent, and therefore, not reordered. But two problems occur with trying to use volatile to fix the problem with double-checked locking:

* The problem here is not with sequential consistency. Code is being moved, not reordered.

* Many JVMs do not implement volatile correctly regarding sequential consistency anyway.

The second point is worth expanding upon. Consider the code in Listing 9:


Listing 9. Sequential consistency with volatile

class test
{
private volatile boolean stop = false;
private volatile int num = 0;

public void foo()
{
num = 100; //This can happen second
stop = true; //This can happen first
//...
}

public void bar()
{
if (stop)
num += num; //num can == 0!
}
//...
}


According to the JLS, because stop and num are declared volatile, they should be sequentially consistent. This means that if stop is ever true, num must have been set to 100. However, because many JVMs do not implement the sequential consistency feature of volatile, you cannot count on this behavior. Therefore, if thread 1 called foo and thread 2 called bar concurrently, thread 1 might set stop to true before num is set to 100. This could lead thread 2 to see stop as true, but num still set to 0. There are additional problems with volatile and the atomicity of 64-bit variables, but this is beyond the scope of this article. See Resources for more information on this topic.


Back to top


The solution

The bottom line is that double-checked locking, in whatever form, should not be used because you cannot guarantee that it will work on any JVM implementation. JSR-133 is addressing issues regarding the memory model, however, double-checked locking will not be supported by the new memory model. Therefore, you have two options:

* Accept the synchronization of a getInstance() method as shown in Listing 2.

* Forgo synchronization and use a static field.

Option 2 is shown in Listing 10:


Listing 10. Singleton implementation with static field

class Singleton
{
private Vector v;
private boolean inUse;
private static Singleton instance = new Singleton();

private Singleton()
{
v = new Vector();
inUse = true;
//...
}

public static Singleton getInstance()
{
return instance;
}
}


The code in Listing 10 does not use synchronization and ensures that the Singleton object is not created until a call is made to the static getInstance() method. This is a good alternative if your objective is to eliminate synchronization.


Back to top


String is not immutable

You might wonder about the String class given the issue of out-of-order writes and a reference becoming non-null prior to the constructor executing. Consider the following code:

private String str;
//...
str = new String("hello");


The String class is supposed to be immutable. However, given the out-of-order write problem we discussed previously, could that cause a problem here? The answer is it could. Consider two threads with access to the String str. One thread could see the str reference refer to a String object in which the constructor has not run. In fact, Listing 11 contains code that shows this occurring. Note that this code breaks only with older JVMs that I tested. Both the IBM 1.3 and Sun 1.3 JVMs produce immutable Strings as expected.


Listing 11. Example of a Mutable String

class StringCreator extends Thread
{
MutableString ms;
public StringCreator(MutableString muts)
{
ms = muts;
}
public void run()
{
while(true)
ms.str = new String("hello"); //1
}
}
class StringReader extends Thread
{
MutableString ms;
public StringReader(MutableString muts)
{
ms = muts;
}
public void run()
{
while(true)
{
if (!(ms.str.equals("hello"))) //2
{
System.out.println("String is not immutable!");
break;
}
}
}
}
class MutableString
{
public String str; //3
public static void main(String args[])
{
MutableString ms = new MutableString(); //4
new StringCreator(ms).start(); //5
new StringReader(ms).start(); //6
}
}


This code creates a MutableString class at //4 that contains a String reference shared by two threads at //3. Two objects are created, StringCreator and StringReader, on two separate threads at lines //5 and //6, passing a reference to the MutableString object. The StringCreator class enters an infinite loop and creates String objects with the value "hello" at //1. The StringReader also enters an infinite loop and checks to see if the current String object has the value "hello" at //2. If it doesn't, the StringReader thread prints out a message and stops. If the String class is immutable, you should never see any output from this program. The only way for StringReader to see the str reference to be anything other than a String object with "hello" as its value is if the problem of out-of-order writes occurs.

Running this code on old JVMs like Sun JDK 1.2.1 results in the out-of-order write problem, and thus, a non-immutable String.


Back to top


Summary

In an effort to avoid costly synchronization in singletons, programmers, quite ingeniously, invented the double-checked locking idiom. Unfortunately, it was not until this idiom was in fairly wide use that it became apparent that it is not a safe programming construct due to the current memory model. Work is underway to redefine areas of the memory model that are weak. However, even under the newly proposed memory model, double-checked locking will not work. The best solution to this problem is to accept synchronization or use a static field.


Resources

* In his book Practical Java Programming Language Guide (Addison-Wesley, 2000), Peter Haggar covers a multitude of Java programming topics including an entire chapter on multithreading issues and programming techniques.

* The Java Language Specification, Second Edition by Bill Joy, et. al. (Addison-Wesley, 2000) is the definitive technical reference for the Java programming language.

* The Java Virtual Machine Specification, Second Edition by Tim Lindholm and Frank Yellin (Addison-Wesley, 1999) is the definitive document on Java compilers and runtime environments.

* Visit Bill Pugh's Java Memory Model Web site for a wealth of information on this important topic.

* For more information on volatile and 64-bit variables, see Peter Haggar's article "Does Java Guarantee Thread Safety?" in the June 2002 issue of Dr. Dobb's Journal .

* JSR-133 deals with the revision to Java platform's memory model and thread specification.

* Java software consultant Brian Goetz examines when to use synchronization in "Threading lightly: Synchronization is not the enemy" (developerWorks, July 2001).

* In "Threading lightly: Sometimes it's best not to share" (developerWorks, October 2001), Brian Goetz examines ThreadLocal and offers tips for exploiting its power.

* In "Writing multithreaded Java applications" (developerWorks, February 2001), Alex Roetter introduces the Java Thread API, outlines issues involved in multithreading, and offers solutions to common problems.

* Allen Holub proposes significant changes and additions to the Java language in "If I were king: A proposal for fixing the Java programming language's threading problems" (developerWorks, October 2000).

* Find other Java technology resources on the developerWorks Java technology zone.



About the author



Peter Haggar is a Senior Software Engineer with IBM in Research Triangle Park, North Carolina, and the author of the book Practical Java Programming Language Guide published by Addison-Wesley. In addition, he has published numerous articles on Java programming. He has a broad range of programming experience, having worked on development tools, class libraries, and operating systems. At IBM, Peter works on emerging Internet technology and is currently focused on high-performance Web services. Peter is a frequent technical speaker on Java technology at numerous industry conferences. He has worked for IBM for more than 14 years and received a B.S. in Computer Science from Clarkson University. Contact Peter at haggar@us.ibm.com.

Computers 'could store entire life by 2026' by Nic Fleming, Science Correspondent

  • Audio: You'll be able to record your entire life on video, says Nic Fleming
  • A device the size of a sugar cube will be able to record and store high resolution video footage of every second of a human life within two decades, experts said yesterday.

    Researchers said governments and societies must urgently debate the implications of the huge increases in computing power and the growing mass of information being collected on individuals.


    Some fear that the advent of "human black boxes" combined with the extension of medical, financial and other digital records will lead to loss of privacy and a dramatic expansion of the nanny state.

    Others highlight positive advances in medicine, education, crime prevention and the way history will be recorded.

    Leading computer scientists, psychologists and neuroscientists gathered to debate these issues at Memories for Life, a conference held at the British Library yesterday.

    Prof Nigel Shadbolt, president of the British Computer Society and professor of artificial intelligence at the University of Southampton, said: "In 20 years' time it will be possible to record high quality digital video of an entire lifetime of human memories. It's not a question of whether it will happen; it's already happening."

    A lap top available in the High Street can hold some 80 gigabytes (GB) of information. One hour of high resolution video footage requires 12GB.

    Since the year 2000, computing processing power has been doubling approximately every 18 months - a phenomenon known as Moore’s Law.

    Prof Shadbolt has calculated that it would take 5.5 petabytes (PT) to record every awake second of a person’s life in high resolution video.

    One PT equals one million GB. Experts expect the increase in computing power to lead to advances in “ehealth” with doctors having access to information from devices that monitor physiological data such as heart rate and blood sugar levels.

    Retailers want to get more information on their customers’ habits than they already have from their loyalty cards. The technological advances will also have a dramatic impact on the writing of biographies and history, with authors and historians able to gain vastly more information on key figures.

    Cliff Lynch, director of the US think tank Coalition for Networked Information, said the changes would allow the preservation of much more detailed memories, but could lead to a dramatic extension of state interference.

    “We will be able to replicate and pass on so much more information. In future you are going to have a much more elaborate picture for more and more people.

    “Biographers and other kinds of scholars who want to understand what someone was thinking are going to be based with an embarrassment of riches.

    “There is a certain tendency towards a technological nanny state. Imagine having a personal companion that wines at you three times a day, telling you that you are eating the wrong things and that you spent more than you earned today and you’ll never be able to retire.

    “Imagine we could end up with smart refrigerator that tells you ‘you’ve already had your beer for the day, you can’t have another one’.

    “I don’t think people would want a world like that, but the scary thing is it might be foisted on them.”

    Prof Wendy Hall, of the University of Southampton, said: “Technology can play a vital role in memory, for example by providing an artificial aid to help those with memory disorders or enabling communities to create and preserve their collective experiences.

    “However, we must also consider the social, ethical and legal issues associated with technology development and how increased access to knowledge will affect our society in open, inter-disciplinary forums.”


    Sunday, December 31, 2006

    Physics promises wireless power by Jonathan Fildes

    The tangle of cables and plugs needed to recharge today's electronic gadgets could soon be a thing of the past.

    US researchers have outlined a relatively simple system that could deliver power to devices such as laptop computers or MP3 players without wires.

    The concept exploits century-old physics and could work over distances of many metres, the researchers said.

    Although the team has not built and tested a system, computer models and mathematics suggest it will work.

    "There are so many autonomous devices such as cell phones and laptops that have emerged in the last few years," said Assistant Professor Marin Soljacic from the Massachusetts Institute of Technology and one of the researchers behind the work.

    "We started thinking, 'it would be really convenient if you didn't have to recharge these things'.

    "And because we're physicists we asked, 'what kind of physical phenomenon can we use to do this wireless energy transfer?'."

    The answer the team came up with was "resonance", a phenomenon that causes an object to vibrate when energy of a certain frequency is applied.


    This would work in a room let's say but you could adapt it to work in a factory
    Marin Soljacic

    "When you have two resonant objects of the same frequency they tend to couple very strongly," Professor Soljacic told the BBC News website.

    Resonance can be seen in musical instruments for example.

    "When you play a tune on one, then another instrument with the same acoustic resonance will pick up that tune, it will visibly vibrate," he said.

    Instead of using acoustic vibrations, the team's system exploits the resonance of electromagnetic waves. Electromagnetic radiation includes radio waves, infrared and X-rays.

    Typically, systems that use electromagnetic radiation, such as radio antennas, are not suitable for the efficient transfer of energy because they scatter energy in all directions, wasting large amounts of it into free space.

    To overcome this problem, the team investigated a special class of "non-radiative" objects with so-called "long-lived resonances".

    When energy is applied to these objects it remains bound to them, rather than escaping to space. "Tails" of energy, which can be many metres long, flicker over the surface.

    "If you bring another resonant object with the same frequency close enough to these tails then it turns out that the energy can tunnel from one object to another," said Professor Soljacic.

    Hence, a simple copper antenna designed to have long-lived resonance could transfer energy to a laptop with its own antenna resonating at the same frequency. The computer would be truly wireless.

    Any energy not diverted into a gadget or appliance is simply reabsorbed.

    The systems that the team have described would be able to transfer energy over three to five metres.

    "This would work in a room let's say but you could adapt it to work in a factory," he said.

    "You could also scale it down to the microscopic or nanoscopic world."

    Old technology

    The team from MIT is not the first group to suggest wireless energy transfer.

    Nineteenth-century physicist and engineer Nikola Tesla experimented with long-range wireless energy transfer, but his most ambitious attempt - the 29m high aerial known as Wardenclyffe Tower, in New York - failed when he ran out of money.



    Others have worked on highly directional mechanisms of energy transfer such as lasers.

    However, these require an uninterrupted line of sight, and are therefore not good for powering objects around the home.

    A UK company called Splashpower has also designed wireless recharging pads onto which gadget lovers can directly place their phones and MP3 players to recharge them.

    The pads use electromagnetic induction to charge devices, the same process used to charge electric toothbrushes.

    One of the co-founders of Splashpower, James Hay, said the MIT work was "clearly at an early stage" but "interesting for the future".

    "Consumers desire a simple universal solution that frees them from the hassles of plug-in chargers and adaptors," he said.

    "Wireless power technology has the potential to deliver on all of these needs."

    However, Mr Hay said that transferring the power was only part of the solution.

    "There are a number of other aspects that need to be addressed to ensure efficient conversion of power to a form useful to input to devices."

    Professor Soljacic will present the work at the American Institute of Physics Industrial Physics Forum in San Francisco on 14 November.

    The work was done in collaboration with his colleagues Aristeidis Karalis and John Joannopoulos.

    HOW WIRELESS POWER COULD WORK
    1) Power from mains to antenna, which is made of copper
    2) Antenna resonates at a frequency of 6.4MHz, emitting electromagnetic waves
    3) 'Tails' of energy from antenna 'tunnel' up to 5m (16.4ft)
    4) Electricity picked up by laptop's antenna, which must also be resonating at 6.4MHz. Energy used to re-charge device
    5) Energy not transferred to laptop re-absorbed by source antenna. People/other objects not affected as not resonating at 6.4MHz


    (track back URL : http://news.bbc.co.uk/go/pr/fr/-/2/hi/technology/6129460.stm)