You are currently browsing the monthly archive for June 2007.

What is Lazy instantiation?
With lazy instantiation, a program refrains from creating certain resources until the resource is first needed — freeing valuable memory space. One solution is
using synchronized method getInstance(). The problem is the method called every time, while synchronization is actually needed only for the first call of the method (which introduces performance overhead in your application).
There were attempts to tackle this problem by using Double-checked locking pattern (DCL).

Lazy instantiation

What is Double-checked locking (DCL)?
The DCL idiom was designed to support lazy initialization, which occurs when a class defers initialization of an owned object until it is actually needed.
Unfortunatelly we found “Double-Checked Locking is Broken”.

The “Double-Checked Locking is Broken” Declaration
Double-checked locking: Clever, but broken

Alternatives to DCL
The most effective way to fix the DCL idiom is to avoid it. The simplest way to avoid it, of course, is to use synchronization. Whenever a variable written by one thread is being read by another, you should use synchronization to guarantee that modifications are visible to other threads in a predictable manner.

Another option for avoiding the problems with DCL is to drop lazy initialization and instead use eager initialization. Rather than delay initialization of resource until it is first used, initialize it at construction. The class loader, which synchronizes on the classes’ Class object, executes static initializer blocks at class initialization time. That means that the effect of static initializers is automatically visible to all threads as soon as the class loads.

One special case of lazy initialization that does work as expected without synchronization is the static singleton. When the initialized object is a static field of a class with no other methods or fields, the JVM effectively performs lazy initialization automatically.

What is Singleton pattern?
The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected.

Wiki: Singleton pattern
lazy-loaded-singletons

What is Stateful Singleton?
We can use ThreadLocal to implement a per-thread Singleton to render stateful Singleton or shared objects thread-safe. This is most used at multiple threads application which want to keep each thread has own non-shared resource like JDBC connection.

Improve Thread Local Pattern
Threads Versus The Singleton Pattern

What is a thread-local variable?
A thread-local variable effectively provides a separate copy of its value for each thread that uses it. Each thread can see only the value associated with that thread, and is unaware that other threads may be using or modifying their own copies

Using ThreadLocal to implement a per-thread Singleton
Thread-local variables are commonly used to render stateful Singleton or shared objects thread-safe, either by encapsulating the entire unsafe object in a ThreadLocal or by encapsulating the object’s thread-specific state in a ThreadLocal.

code snippest:

public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}  private static ThreadLocalConnection conn = new ThreadLocalConnection();

public static Connection getConnection() {
return (Connection) conn.get();
}
}

Ref:
Sometimes it’s best not to share
Writing multithreaded Java applications
Connection pools
Can ThreadLocal solve the double-checked locking problem?
Hibernate: Improved Thread Local Pattern

update: 09/17/2007

Thread Local: A Convenient Abomination 

Our project has complex object graphs in memory to calculate the available slot for scheduler. Core engine needs to solve the problem of constrains of routing, resource, machine, people and tools. This is a NP hard problem. So we consume very big big object graphs to represent whole scheduler in memory. We create our own cache, command, even-handler and transaction control. We have to make sure the complex object graphs can do things like transaction to create, read, update and delete. Especially scheduler has to be rollback both in memory and database. Here is example:

//unit of work
try{
   transaction.start();
   commandSyncOrder.create(orderbean);
   transaction.end()
}catch(Exception ex){

   //rollback in memory
   commandSyncOrder.undo();

   //rollback in database
   transaction.rollback();
}finally{

   commandSyncOrder.close(); //enforce object clean up
                            //not to depend on finalized from garbage collection
   transaction.close();     //close JDBC connection
}

Now I try to redesign this core scheduler engine to use Spring and Hibernate because we already implement that for 3 tier client-server web application. I found those post may solve my problem.

I had inspired from the book: Pragmatic Project Automation to create a Ant script that performs from compiling source code, package and deliver. Recently I has done another approach to do it.

Preparation:
1. The Enterprise logo, user license, installation path and authentication
2. Default database
3. Release document

Procedure:
1. Install ISsetup tool 5.1.11 with ISTool support
2. Install Database Publishing Wizard from Microsoft
3. Create single SQL Script file from default database using the database publishing wizard
4. Use osql.exe to execute “SQL Script” to create the template database
5. Apply application as Windows service: Javaservice and JBoss setup
6. Uninstall from Windows

Advance:
1. Remove/backup files
2. License key/expiration/evaluation 90 days
3. Multiple language support
4. NSIS (Nullsoft Scriptable Install System)
5. JBoss Web comes with Windows service
6. ObjectWeb: JavaService
08-24-2007 update

When windows user logoff, java processes will be suspended. By default, Java services receive a CTRL_LOGOFF event from the operating system when the user logs out of Windows. As a result, all Java services would stop and shut down. To prevent this, Sun recommends using the JVM option flag -Xrs. This command is specified on the start-up of a Java process, and prevents the Java processes from terminating when a Windows CTRL_LOGOFF event occurs. For example at JBoss

Open /jboss-4.0.0/bin/run.bat

set JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -Xrs

Most programmers know how to use List, Set, and Map. But how do you decide which entity to use? how it relates to hashcode, comparable and comparator? and how the sorting works? I just rewrite our project with new sort algorithm base on Collections sort!

1. Basic:
Sort it out
Managing Java Collections
Outline of Collections Framework

2. Advance:
Collections.binarySearch
Dynamic Sorting With Java

3. Java Generics and Collections:
Part 1
Part 2

A weak reference is one that does not prevent the referenced object from being garbage collected. You might use them to manage a HashMap to look up a cache of objects.

Using WeakHashMap to Avoid Memory Leaks

Using WeakHashMap for Listener Lists

O’Reilly: Java Performance and Tuning

Performance improvement on memory leak

I had been implemented a Timer tool using Swing to schedule the task to batch the bank transaction. Then last year I did work with a project to do the same thing but used Spring framework’s Timer. The more step is to allow user change the interval time
after Spring configuration has been loaded. Here is my approach.

1. Build the fundamental Spring Timer
Spring: Scheduling and Thread Pooling ( In this case I choose JDK Timer.)

2. Modify your Task to implement org.springframework.beans.factory.InitializingBean
This class will override afterPropertiesSet() method to change your interval time.

3. FYI: EJB 3.0 Timer

4. Code snippest

applicationContext.xml
<!– java.util.Timer + spring integration –>
<bean id=”myWorkTask” class=”com.me.MyEventTask”>
<property name=”insiderService”><ref local=”insiderService”/></property>
</bean>

<bean id=”jobDetail” class=”org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean”>
<property name=”targetObject” ref=”myWorkTask”/>
<property name=”targetMethod” value=”doIt”/>
</bean>

<bean id=”myScheduledTask” class=”com.me.MyScheduledTask”>
<!– wait 30 mins before starting repeated execution –>
<property name=”delay” value=”1800000″/>
<!– run every 60 mins , if you input -1, then it only runs once. –>
<property name=”period” value=”3600000″/>
<property name=”timerTask” ref=”jobDetail”/>
</bean>

<bean id=”timeFactory” class=”org.springframework.scheduling.timer.TimerFactoryBean”>
<property name=”myAllTasks”>
<list>
<ref bean=”myScheduledTask”/>
</list>
</property>
</bean>

package com.me;import org.springframework.beans.factory.InitializingBean;

import java.io.InputStream;

import java.util.Properties;

public class MyScheduledTask extends org.springframework.scheduling.timer.ScheduledTimerTask implements InitializingBean {

 private props = null;

public MyScheduledTask(){

         Properties props = new Properties();

         /**

          * process.properties loads

          */

         InputStream is = getClass().getResourceAsStream("/resources/myparas.properties");

        	props.load(is);

 }

public void afterPropertiesSet() throws Exception {

 	//read parameter from properties file or from database

 	String param = props.getProperty("INTERVAL");

 	long sysInterval = Long.valueOf(param).longValue()*1000;

 	if(sysInterval != 0){

 		//this method will change the value of timer interval time.

 		setPeriod(sysInterval);

 	}

 }

}

Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data. I have used Regular Expression, XSLT and XPath to generate the XML format in project.

1. Basic tutorial

Sun tutorial

Regex : Java Glossary 

2. Example

Regular-Expressions.info 

Java Developers Almanac: regular expressions 

3. Test your code

Regular Expression Test Page