javablogspot

Just another WordPress.com weblog

Posts Tagged ‘Java’

Type conversion in Java

Posted by damuchinni on March 15, 2009

The type conversion in java of two types.
a)Automatic type conversion
b)Casting

Automatic type conversion: When one type of data is assigned to another type of variable an automatic type conversion will take place.
Conditions 1)The two types are compatible 2)The destination type is larger than the source type.
Ex:
int x=10;
byte y=2;
x=y; byte to int automatic conversion.

Casting: It is used to perform conversion between incompatible types.
Syntax: (Target_type)value
Target type specifies the desired type of convert the specified value to.
Ex:
Int i=257;
Byte b;
B=(byte)i; //now b value is 1.

Posted in Java | Tagged: | Leave a Comment »

WebKit Component for Java, Second Contestant

Posted by damuchinni on March 14, 2009

While there weren’t any news related to Sun’s JWebPane, there is a new contestant: WebKit for SWT by Genuitec. The website says:

WebKit for SWT (ver. 0.5) is an embeddable Java™ WebKit browser component developed by Genuitec. This component can be used in the development of a wide range of Java SWT applications that require integration of rich HTML5, CSS3, JavaScript and Flash content and functionality.

The solution seems a little bit more high-level than Sun’s approach: While Sun is integrating WebKit directly, Genuitec build on top of Google’s chromium. The biggest difference however at this time: They provide code, documentation and samples.

Posted in Java, swings | Tagged: , , | Leave a Comment »

Dynamic Java Programming With Rule Engine

Posted by damuchinni on March 14, 2009

Rules are statements that define business procedures and policies. Normally, every business application contains many embedded business rules that determine business process flow and execution. When we program these rules with static languages like Java, there is no problem at all.

However, the problem is that some business rules change over time very frequently. It is very expensive to fix these changing parts since it requires new versions and software development cycles; develop, deploy on a test server, test, package, deploy on a production server etc. Here “Dynamic Programming” comes to our rescue. Our program doesn’t have to necessarily be written with a dynamic language. We can use this advantage in Java with Rule Engine mechanism.

Rule Engines don’t serve only the dynamic programming. They evaluate rules and extract some inferences by using some algorithms like RETE. This inference mechanism is hardly possible with many “if-else” statements in normal program code. Rule Engines have generally 4 types of rules;

* Constraint Rule: We may need to define restriction or limits for some entities. “A customer sales order amount must be lower than 100 if the plant is over capacity ”

* Validation Rule: Some validation rules may change over time. “Production order can’t be accepted if current day is Sunday”

* Action Rule: Some actions may be triggered. “Send a notification e-mail if a purchase order is over $1000 to boss”.

* Computation Rule: Some formula may be executed. “Discount is 20% if customer is Mr. Anderson”

We can use Rule Engines on the market but even we can write our own Rule Engine to benefit the dynamic programming in Java. By using Java compilers, classloaders, it is not so much hard. My favorite rule definition format is Java source code instead of some natural languages or XML. This can also reduce the overall development cost of your custom rule engine. By writing Java rule definitions, we can also use the IDE debugger features without learning a new syntax. If we develop our own Rule Engine, we may skip the inference engine part since we only want dynamic programming feature for now. Best place for plugging rule execution is database access layer. Rules should work invisibly behind the database objects. In some cases, some rules might be invoked from static program codes.

The benefits that we have when using Rule Engine are:

* Dynamic programming with hotswapping feature that provides fix&run easiness.
* Minimal cost of business rule changes that occurs many times.
* Accumulation of business rules in one place that may result re-usability and code repetition prevention.
* Dynamic validations that may change over time.
* Constraints can be defines for default values, assertion checks etc.
* In any time rule may be turned off/on.

Some of the features of Rule Engine may remind us database constraints and triggers. Using database may hinder portability and require DBA involvement. I think Rule Engine is better for business rule definitions. These database features may be used for other purposes.

The critical question we should ask ourselves is which part of business rules should be taken into Rule Engine from the programs. The answer is “frequently changing” rules. Some changing parts can be defined within parameter tables (processing options) but we can’t define computation or many if-else statements in these tables. But we should prefer parameter table if it is enough for the problem.

Links:

* http://java.sun.com/developer/technicalArticles/J2SE/JavaRule.html

* http://www.javaworld.com/javaworld/jw-04-2005/jw-0425-ruleengine.html

* http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html

* http://www.amazon.com/Principles-Business-Addison-Wesley-Information-Technology/dp/0201788934/ref=sr_1_3?ie=UTF8&s=books&qid=1236927606&sr=1-3

* http://www.amazon.com/Business-Rules-Applied-Building-Approach/dp/0471412937/ref=sr_1_1?ie=UTF8&s=books&qid=1236927606&sr=1-1

Posted in Java, rule engine | Tagged: , | Leave a Comment »

How to Fix Memory Leaks in Java

Posted by damuchinni on March 11, 2009

Before You Start

Ever heard the story about how Java has “automatic memory management”—you know, the one that someone in marketing upgraded to an epic tale about how you’ll never have to worry about memory leaks ever again? As is often the case, the truth is more complex than the marketing department made it out to be. While it’s true that Java’s garbage collector (GC) helps to eliminate the most common memory leak issues from applications, it is unfortunately still possible to experience memory leaks in Java. However, they happen a lot less often than they used to in the C or C++ days.

Many people believe that black magic and complex tools are required to fix memory leaks. This undeserved reputation is caused by the lack of good explanations of what they are and what to do when you encounter them. But with the proper tools and knowledge to fix memory leaks, they aren’t nearly as intimidating.
Methodology

In this article we’ll cover everything from memory leak basics to analyzing heap dumps, so—whether you’re an experienced Java developer or encountering Java memory leaks for the first time—you’ll be better prepared to deal with memory leaks by the time you reach the conclusion. We won’t outline a series of steps, like “do ABC with commercial tool XYZ and don’t ask why,” as that approach doesn’t work and implies that remedies are more complex then they really are. Instead, we’ll give you the background information necessary to address memory leaks, with emphasis placed on particular steps you’ll need to execute. Similarly, we’ll assume that you can learn on your own how to use the memory profiler of your choice; what’s missing is an understanding of what the tool is trying to do and why, so that will be the focus of this article.

Java will be used for all examples, so all information in this article directly applies to Java applications running standalone or as a part of J2EE/JEE/Tomcat-based application server. But remember, although our primary focus is on Java, most of the process of diagnosing and fixing memory leaks described herein applies to other languages with garbage collectors. So even if you’re using Ruby, C#, or Python, there should be something for you in this article.
What Are Memory Leaks?

Let’s start by describing how memory leaks happen in Java. Java implements automatic garbage collection (GC), and once you stop using an object you can depend on the garbage collector to collect it. While additional details of the collection process are important when tuning GC performance, for the sole purpose of fixing a memory leak we can safely ignore them.

When is memory eligible for GC? Let’s take a look at an example:

gc-eligable

We don’t have to do anything special to make an object eligible for GC—we just eliminate any references to it, and it “magically” disappears and stops using memory. That’s why we say that Java performs “automatic” GC.

Why “eligible” for GC? Because objects are not collected immediately. GC is not instantaneous and comes with some performance impacts. Consequently, Java doesn’t immediately collect every object that is eligible for collection; it typically postpones collection until a more convenient time later on. The way to think about GC in Java is that it’s a “lazy bachelor” that hates taking out the trash and typically postpones the process for some period of time. However, if the trash can begins to overflow, Java immediately takes it out. In other words, if memory becomes scarce, Java immediately runs GC to free memory.

Since we don’t need to do anything special in order to dispose of objects in Java, how do memory leaks happen in Java? Memory leaks occur when a program never stops using an object, thus keeping a permanent reference to it.

Let’s take a look at an example that helps illustrate this point. The following code will cause all available memory in the JVM to be exhausted:

memory_leaks_figure6

When no more memory is remaining, an OutOfMemoryError alert will be thrown and generate an exception like this:

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space at
MemoryLeakDemo.main(MemoryLeakDemo.java:14)

In the example above, we continue adding new elements to the list memoryLeakArea without ever removing them. In addition, we keep references to the memoryLeakArea, thereby preventing GC from collecting the list itself. So although there is GC available, it cannot help because we are still using memory. The more time passes the more memory we use, which in effect requires an infinite amount memory for this program to continue running.

This is an example of unbounded memory leak—the longer the program runs, the more memory it takes. So even if the memory size is increased, the application will still run out of memory at a later date.

Posted in Java | Tagged: , | Leave a Comment »

Correct declaration for a main() method

Posted by damuchinni on March 11, 2009

Correct declaration for a main() method

In the Java language, main() method allows us to run the class as an application. When we execute a class with the Java interpreter, the runtime system starts by calling the class’s main() method. The main() method then calls all the other methods required to run our application.

The main() method must be static, not return a value, and take an array of strings.

Signature:

public static void main(String[] args) or
public static void main(String args[])

Here public indicates that the main() method can be called by any object.static indicates that the main() method is a class method and void indicates that the main() method has no return value.

main() method can be overloaded

We can create any number of methods called ‘main’ in a class, which take other arguments, are not public and static, or return a value. To be able to run the class, however, there must be one method called main that takes an array of Strings as an argument, and that method must be static, and not return a value. Otherwise we will get a runtime error when you try to execute the class.

Posted in Java | Tagged: | Leave a Comment »

Processing: Revival of the Java Applet?

Posted by damuchinni on March 10, 2009

The Java Applet caused a lot of hype in the mid 90s when some people believed it would become the standard for interactive content on the web. It never happened. Some will claim this is because M$ shipped a buggy implementation. The simple truth is that designers design the web, and Adobe Flash created a very designer-friendly interface. Java Applets are Java programs and you need to be a programmer to write one. It was a completely inaccessible technology from the design side.

Arguably, the race is still on for the next-generation rich-media platform: M$’s Silverlight and SUN’s JavaFX being two new entries. It seems that even SUN have laid Java Applets to death. But recently our team stumbled upon a fantastic project called Processing which is aimed at designers who aren’t scared of a little bit of programming. There is an integrated IDE and although you feel like you’re writing pseudocode, you’re actually writing a simple version of Java (which gets compiled to an applet). For some great examples, see Processing monsters.

At xmas, our team (ThinkTank Maths) wanted to create a mathematics-inspired holiday message. After much thought, we came up with the idea of a repeating wallpaper pattern based on the recipient’s name, perhaps using a Langton’s Ant. The next challenge was to create an implementation. One of our team whipped up a Processing implementation in a few hours. Read on to see our applet, and the clean code Processing encourages…

Name:

Click the applet to restart and try using your name. For the very observant among you, you’ll notice that our xmas card wasn’t a Java Applet. Unfortunately, although Processing seems to finally be what Applets should have been from the start, Internet Explorer does not have the Java plugin by default and we opted to go for a static image served up from a Servlet to ensure that all our readers could see it. Processing was able to convert to produce Java that enabled this without too much trouble. That says it all really… Java Applets are still dead.

Code is available below.

int w = 480, h = 320;
color bg = 255;
LangtonsAnt ant1, ant2, ant3;

void setup() {
size(w, h);
background(bg);

String text = param(“text”);
if (text == null || text.length() == 0)
text = “ThinkTank Maths”;
Random r = new Random(text.hashCode());
int x = r.nextInt(w);
int y = r.nextInt(h);
ant1 = new LangtonsAnt(LangtonsAnt.NORTH, 0xCC0065C6, x, y, w, h);
x = r.nextInt(w);
y = r.nextInt(h);
ant2 = new LangtonsAnt(LangtonsAnt.SOUTH, 0xCC46A4FF, x, y, w, h);
x = r.nextInt(w);
y = r.nextInt(h);
ant3 = new LangtonsAnt(LangtonsAnt.WEST, 0xCCB6B8B9, x, y, w, h);
}

void draw(){
for (int i = 0; i = w || x = h || y < 0)
y = (y + h) % h;
return updated;
}

// turn the ant left and adjusts the position by moving the ant forward one pixel
void turnL() {
switch (d) {
case NORTH:
x–;
d = WEST;
break;
case EAST:
y–;
d = NORTH;
break;
case SOUTH:
x++;
d = EAST;
break;
case WEST:
y++;
d = SOUTH;
}
}

// turn the ant right and adjusts the position by moving the ant forward one pixel
void turnR() {
switch (d) {
case NORTH:
x++;
d = EAST;
break;
case EAST:
y++;
d = SOUTH;
break;
case SOUTH:
x–;
d = WEST;
break;
case WEST:
y–;
d = NORTH;
}
}
}

Posted in Applets, Java | Tagged: , | Leave a Comment »

What Is javasoft.com?

Posted by damuchinni on March 10, 2009

JavaSoft was Sun’s subsidiary which developed the first editions of Java. JDK/JRE were primary only available from http://www.javasoft.com, as well as common news about Java, JavaONE etc – very like java.sun.com. Actually you can still use the url http://www.javasoft.com and will be redirected to java.sun.com. This is what I actually still do. Someone asked me recently about that. Then I actually recognized the redirection :-).

Posted in Java | Tagged: | Leave a Comment »

Using Coherence*Web with JSF

Posted by damuchinni on March 8, 2009

Recently I was helping a customer install Coherence*Web on a JSF application. After running the install and deploying the war file, I saw the following exception:

javax.servlet.ServletException: Error while saving state in ’session’: ’session attribute for name “/Page1.jsp” does not implement Serializable; class: Class javax.faces.component.UIViewRoot

HTTP session attributes must be serializable in order to place them into a distributed cache. This requirement is not unique to Coherence*Web, any session replication solution will require this in order to replicate sessions to another JVM.

However, Coherence*Web does have a feature that can let you work around this. If you place a non serializable attribute into an HTTP session with sticky session optimization enabled (see description of this feature at the bottom of this link), the attribute will be placed in a local cache (and a warning will be logged.) The idea is that if a sticky load balancer is managing the traffic, the chances are very good that subsequent requests for that session will go to the same JVM which is holding that attribute in memory. Obviously if the load balancer sends the request to another JVM (or if the JVM leaves the cluster) that session attribute will not be available in the request. Therefore this is not a recommended approach; this feature is meant to ease the transition of a web application from a single JVM to a distributed environment.

So it appears that JSF is placing some sort of view metadata into the session that isn’t serializable. The good news is that JSF can be configured to store this data on the client side (as a hidden form field) instead of the server side (in a session.) This change needs to be made in web.xml; change this:

javax.faces.STATE_SAVING_METHOD
server

to this:

javax.faces.STATE_SAVING_METHOD
client

More information on this setting can be found here:

http://java.sun.com/developer/technicalArticles/GUI/JavaServerFaces/

I do find it odd however that they have the ability to write out the state to the client, but the object that holds this state isn’t serializable for some reason. I wonder if this was an oversight or if this is by design.

Posted in Java, JSF | Tagged: , | Leave a Comment »

The popularity of 3D Java game engines

Posted by damuchinni on March 8, 2009

Getting started with 3D programming requires a bit of math (Vectors and Matrices) and a programming language with access to a 3D API. In Java 3D programming is typically done using the cross-platform OpenGL API, but there do also exist a bridge to Microsoft’s Direct3D.
Most often, programming your 3D applications at this level will get very complex, at least if you plan to create a more medium to large application such as a game. Instead of using the low level API, you would usually use a 3D scenegraph that hides much of the complexity and enabled you to be more productive. A 3D scenegraph is sometimes referred to as a 3D game engine, since they are often targeted games and has features such as sound, input and particle effects.

In the Java world there exist a number of different alternatives. I’ll describe four different 3D scenegraphs that I find interesting: Java3D, JMonkeyEngine, XInth and Ardor3D.

Java3D (https://java3d.dev.java.net/)
Java3D is the standardized way to develop 3D applications using Java. The Java3D is a scenegraph developed by Intel, Silicon Graphics, Apple and Sun, and the first public version was released in 1998. Java3D encapsulate the underlying 3D API and supports both OpenGL and Direct3D. Many books has been published about the Java3D API.
Java3D is released under GPL version 2 with the CLASSPATH exception

JMonkeyEngine (http://www.jmonkeyengine.com/)
The JMonkeyEngine (also known as jME) is a scenegraph engine inspired by David Eberly’s C++ book 3D Game Engine Design. Currently jME exist in a stable version 1.0 and a beta version 2.0. The jME has a huge community site and has many tutorials and examples.
jME is released under the BSD license

Xith3D (http://xith.org/)
Xith3D project is another 3D scenegraph. Is has a very good introduction book Xith in a Nutshell that explains the basics. You are encouraged to download the latest source and build the binaries yourself.
Xith3D is released under the BSD license

Ardor3D (http://ardor3d.com/)
Ardor3D is started by two of the former jME developers. The goal of Ardor3D is to created a more professionally oriented engine. The Ardor3D is actually a fork of jME. The Ardor3D is still a very young engine and therefor lacks tutorials and documentation.
Ardor3D is released under the libpng/zlib license

Popularity
But what engine is the most popular? I have used the number of forum threads per month to measure the popularity:

Please note that the number of forum threads per months may not be the perfect ways to measure the popularity; Java3D seems to be a only a medium popular API, but I believe that this API is discussed in many other places than the official sun forum. I don’t think that is true for the other API’s.
The number of threads in the Ardor3D seems surprisingly high for a new technology. The reason for this high number of threads is that the Ardor3D forum also is used between the Ardor3D developers discussing implementation details about the API, where forums of other APIs is targeted users of the API.

Conclusion

The forum activity hints that the popularity of programming in 3D using Java is increasing. And I expect this to popularity to grow dramatically once the new JavaFX platforms enters the 3D era.

Posted in Java, java 3d | Tagged: , | Leave a Comment »

Struts2 Spring plugin can be called multiple times at startup

Posted by damuchinni on March 8, 2009

I have been writing a web application that has a plugin framework. The plugins needed to be Struts2 and Spring aware so that they would have tight integration into the web application. In order to make things easier I have been using the struts-spring-plugin.jar that comes bundled with the Struts2 download. The problem was that the following happened when my application initialised:

The Struts2 framework would initialise and call the struts-spring-plugin to set the Spring ApplicationContext;
My PluginManager would initialise and set the Spring ApplicationContext within Struts so that my plugins Spring beans would be included and could be found by both Struts and Spring;
The struts-spring-plugin would be called again and overwrite my Spring ApplicationContext that I had just set.
I tried to track down that third call but could find out where it originated from, all I could get is that it came from a class that was instantiated through the sun reflection classes. Once I had figured out the problem the solution is pretty simple. Just create a copy of the org.apache.struts2.spring.StrutsSpringObjectFactory (from the struts-spring-plugin.jar) in your project and modify it as follows:

try {
// Try and set the SpringObjectFactory with the last child of the Spring ApplicationContexts tree from the MyPluginManager.
MyPluginManager myPluginManager = MyPluginManager.getInstance();
setApplicationContext(myPluginManager.getPluginsXmlWebApplicationContext());

} catch (ExceptionMyPluginManagerNotInitialised empmni) {
// We couldn’t set the applicationContext with the one from the MyPluginManager so use the default
setApplicationContext(appContext);
}

The MyPluginManager is the class that manages my plugins. When it initialises the plugins it stores the XmlWebApplicationContext used to initialise that plugin. Each plugin has a new XmlWebApplicationContext that has either the ROOT XmlWebApplicationContext or the last pluginXmlWebApplicationContext as the parent. This means that the last pluginXmlWebApplicationContext is the last in the chain of XmlWebApplicationContext and so can see all of the spring beans from the root context AND the plugins. That is the XmlWebApplicationContext that is used in the above codes call to:

setApplicationContext(myPluginManager.getPluginsXmlWebApplicationContext());

Now Struts uses my child XmlWebApplicationContext and not the ROOT XmlWebApplicationContext.

Posted in Java, Springs, struts | Tagged: , , , | Leave a Comment »