Tuesday, December 19, 2006

Flyweight Design Pattern

I was wondering about Flyweight pattern for so many days. Let me present its definition and some detail.

Flyweight pattern: Flyweight is one of the structural patterns. The Flyweight Design Pattern is useful when there is the need for many, many objects to exist that share some information. Several thousand or even several hundred thousand objects might be needed, and this is usually very memory-consuming to keep track of. Given certain constraints, it is possible to reduce this problem greatly and make the presence of so many objects possible. If all of the objects share some intrinsic, invariant information that is constant among all of them, it can be removed from each object, and referenced. This eliminates the redundancy of having to repeat the same invariant, intrinsic information for each object, so instead of storing the same information n times for n objects, it is only stored once. This object that contains all of the intrinsic information is called a flyweight object.
It is possible for a flyweight to have extrinsic information as well. This information must be stateless and determined by context, having no stored values, but values that can be calculated on the spot.
The different components involved in the Flyweight Pattern are the Flyweight, the ConcreteFlyweight, the FlyweightFactory and the Client.

One classic example of a flyweight pattern is the characters stored in a word processor. Each character represents an object that has a font face, font size, and other formatting data. As you can imagine, a large document with this data structure would bloat the memory footprint of the word processor. Moreover, since much of this data is repeated, there must be a way to reduce the footprint - the Flyweight pattern. Each of the character objects would contain a reference to a separate formatting object which contains the required properties. This greatly reduces the memory footprint by combining all of the like-formatted characters into simpler objects that reference a single formatting object.

In Design Patterns, the Gang of Four (GOF) authors describe the Flyweight pattern like this:

Use sharing to support large numbers of fine-grained objects efficiently.

Memory Leak

Memory Leak: Unintentional object retention is sometimes called as "memory leaks". It could come about in several ways. One of the case is when an object is no longer needed is referenced through some path from the rootset.

Monday, December 18, 2006

OOP vs AOP

OOP is object-oriented programming that modularizes software using basic oop concepts such as encapsulation, inheritance and polymorphism. OOP is not bound to any programming languages.

AOP is aspect-oriented programming. AOP modularizes software applications based on loosely coupled aspects. AOP is a concept and not bound to any programming language. Software vendors can provide implementation for AOP in any programming language and make it available for the entire software community. For example, AspectJ (http://www.aspectj.org/ ).
A concern is nothing but a function in a given system. Any system is typically composed of both core and non-core concerns. The non-core concerns such as logging and security are actually the supporting functionalities for the mainstay core functionalities. The core functionality is the one that the system is expected to do.
AOP helps separate the non-core concerns from the core concerns by implementing concerns as aspects. Each aspect is independent and loosely coupled with other aspects in the system. This provides the flexibility for developers to enhance or remove any aspect at a later point in time without affecting the design and current state of the system.

Examples of AOP are following:

1. Logging functionality which is non-core concern could be implemented as one of the aspect.
2. Benchmarking logic such as time stamps across a block of code could be senn as one of the aspect.

Using AOP prevents the utility codes to be tightly coupled from the main code.

For detail, go to http://www.developer.com/lang/article.php/3649681

Thursday, December 14, 2006

Visitor Pattern : Java

I was trying to understand Visitor design pattern when I got into Single-dispatch and double-dispatch terms. Well, understanding of visitor pattern is enhanced once you understand the dispatch terminology in OOPs.

Single dispatch is a mechanism where a function call on an object is rightly dispatched to correct method based on the type of the object. The arguments of function call do not really matters. However, in a double dispatch mechnism, a function call is dispatched to different concrete functions depending on the runtime types of multiple objects involved in the call. Java does support single dispatch mechsnism. However, there is MultiJava compiler written to take of double dispatch mechanism. Check out a nice simple reading on dispatch definition, http://ifacethoughts.net/2006/07/29/single-double-and-multiple-dispatch/


The link http://rileywhite.com/software/visitorpattern.html  presents nice explanation on the visitor pattern. One thing is sure. Visitor pattern is definitely hard to learn, unlike adapter, observer, factory patterns which are intuitive and widely used.

Another great reading on visitor pattern, which I really loved, is http://www.javaworld.com/javaworld/javatips/jw-javatip98.html .

Definition: The Visitor pattern lets us define a new operation on an object structure without changing the classes of the objects on which it operates. Rather than writing dedicated methods for each programming task and afterwards recompiling, the idea is to (1) insert a so-called accept method in each class, and (2) write the action code in so-called visitors.

One example code for visitor pattern is http://bobcat.webappcabaret.net/javachina/jc/ptn/Visitor.htm


Wednesday, December 13, 2006

Java Concurrency

Concurrency according to http://dictionary.reference.com/browse/Concurrency is following:

1. Simultaneous occurrence; coincidence: the concurrence of several unusual events. OR,
2. Acting together as of agents or circumstances or events

Example of concurrent application could be following:

1. The streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display.
2. The word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display.

The Java platform is designed from the ground up to support concurrent programming, with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs. This lesson introduces the platform's basic concurrency support and summarizes some of the high-level APIs in the java.util.concurrent packages. They are following:
    *  Lock objects support locking idioms that simplify many concurrent applications.
    * Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
    * Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
    * Atomic variables have features that minimize synchronization and help avoid memory consistency errors.
    
For detail, visit http://java.sun.com/docs/books/tutorial/essential/concurrency/highlevel.html.

Going a little bit over basics, in concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important.

Processes

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.

Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes.

Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.


Threads

Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process - every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Multithreaded execution is an essential feature of the Java platform.from the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads.

Java Multi-threading Vs Dual Core Processor

Multithreading could be categorized in two kinds:

1. Temporal multithreading where operating systems simulate doing many things at once by rapidly time-slicing between threads.
2. Simultaneous multithreading (SMT) when multiple threads executes instructions during the same clock cycle.

The java multithreading which we have known so far is actually temporal multithreading as most processors so far has been capable of executing only a single thread in a given time-slice.

True concurrency could actually be termed as Simultaneous multithreading (SMT). In past, SMT has been possible only on high-end multiprocessor systems. There arrives the Intel Dual Core Processor.

Intel dual core processor consists of two complete execution cores in one physical processor, both running at the same frequency. This is intended to provide immediate advantages to people looking to buy systems that boosts multitasking computing power and improve the throughput of multithreaded applications. To read more about dual core processors, refer http://www.intel.com/technology/computing/dual-core/.

Running Java program on a dual core processor does not immediately inherit advantages provided by SMT. One has to adapt the algorithms such that time consuming sections are performed by multiple threads designed to run simultaneously.

The java concurrency API should be used in such cases to speed up time-consuming tasks on dual core processors. The package java.util.concurrent classes could be used to achieve true concurrency. A simple approach for multithreading follows:
1. Develop a single-threaded, sequential, robust, and clearly organized version of your algorithm.
2. Identify the subtasks.
3. Benchmark the algorithm.
4. Delegate the most time-consuming subtasks to a thread pool.

For detail reading on java hyper-threading, visit http://www.javaworld.com/javaworld/jw-11-2006/jw-1121-thread.html?fsrc=rss-index


Tuesday, December 12, 2006

Java SE 6 Support for Javascript

Talking about javascript, Java SE 6 has support for javascripting. Earlier to this release, I found myself using mozilla rhino.jar file. Now that’s cool new feature of Java SE 6. For those who want to quickly get familiar with javascript, try out the website, http://www.quirksmode.org/js/contents.html.
Cheers.

Monday, December 11, 2006

JVM and Three kinds of memory

JVM has following three kinds of memory:

1. Heap memory: Runtime data area from which memory for all class instances and array is allocated.
2. Non-heap memory: Method area and memory required for internal processing. Method area stores code for method and constructors. It stores per class structures such as runtime constant pool, field and method data.
3. Native memory: Virtual memory managed by the operating system.

Java Application Common Problems

My Java application was running fine some time before and now in the later release, it is slow or it is acting unresponsive. At times, it hangs too.
Well, some of the problems with java application could be following:

1. Insufficient memory. The symptom is when one gets OutOfMemoryError.
2. Memory Leaks: Following could be symptoms:
    - Growing use of memory
    - A class with high growth rate
    - A class with an unexpected number of instances
    - An object being referenced unintentionally
3. Finalizers: Objects are pending for finalization
4. Deadlocks: Thread blocks on object monitor or java.util.concurrent locks
5. Looping threads: Threads CPU time is continuously increasing
6. High lock contention: Thread with high contention statistics

Thursday, December 07, 2006

Downcasting vs Upcasting in Java

CharSequence l_sq0 = new String( "HelloWorld 0" );
System.out.println( "CharSequence: " + l_sq0.toString() );
// Downcasting CharSequence to String
String l_tstr2 = (String)l_sq0;
byte[] l_bytes = l_tstr2.getBytes();
System.out.println( "String: " + l_tstr2.toString() +
                " Length: " + l_bytes.length );
        
String l_tstr = new String( "Hello World 1" );
// Upcasting String to CharSequence
CharSequence l_sq = (CharSequence)l_tstr;
System.out.println( "String: " + l_tstr.toString() );
System.out.println( "CharSequence: " + l_sq.toString() );
 
In the above example, String which implemented CharSquence in java.lang has been upcasted and downcasted at two different places. So, that is allowed.


Need a quick answer? Get one in minutes from people who know. Ask your question on Yahoo! Answers.

Does Programming Language really matter?

I do not think programming languages really makes difference if the technology remain focussed on object-orientation. Based on one's project's requirements, one could choose the appropriate programming language and work accordingly.
 
Some of the famous ones are following:
 
Java
C++
Ruby (Recently)
 
Server-side Scriptling languages also support object-orientation. They are languages such as ASP, PHP.


Everyone is raving about the all-new Yahoo! Mail beta.

Tuesday, December 05, 2006

I am fed up with AJAX.

Is AJAX worth that attention?
 
Give me a break! It is OK that AJAX is a cool technology, a Web 2.0 enabler. But, it has been there since so long. It is only that now, IT gurus have formalized the technology and guys out there are coming otu with so many toolkits. Do not why?
 
Well, its just that I goto http://java.sun.com to read every day and find that every 15 days there is one AJAX related article on the front home page.
 
Now, please give AJAX a break and move on.
 
 
 


Cheap Talk? Check out Yahoo! Messenger's low PC-to-Phone call rates.