A java blog with a collection of examples and tutorials on Java and related technologies. (Under maintenance with continuous updates) Be in touch with java jazzle or k2java.blogspot.com.
Sunday, July 28, 2013
Tuesday, December 27, 2011
Extend Thread vs implement Runnable
java.lang.Thread class, or implementing java.lang.Runnable and pass it to Thread constructor or java.util.concurrent.ThreadFactory. What is the difference, and which one is better?- The practical reason is, a Java class can have only one superclass. So if your thread class extends
java.lang.Thread, it cannot inherit from any other classes. This limits how you can reuse your application logic. - From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a
Runnalbeimpl, and the latter is job of theThreadclass. - A
Runnableinstance can be passed to other libraries that accept task submission, e.g.,java.util.concurrent.Executors. A Thread subclass inherits all the overhead of thread management and is hard to reuse. - Their instances also have different lifecycle. Once a thread is started and completed its work, it's subject to garbage collection. An instance of
Runnalbetask can be resubmitted or retried multiple times, though usually new tasks are instantiated for each submission to ease state management.
Friday, December 23, 2011
O(n) for operations on Java collections
Collection Interfaces - Java Collection Diagrams
Avoid memory leaks using Weak&Soft references
Some Java developers believe that there is no such a thing as memory leak in Java (thanks to the fabulous automatic Garbage Collection concept)
Some others had met the OutOfMemoryError and understood that the JVM has encountered some memory issue but they are not sure if it’s all about the code or maybe even an OS issue…
The OutOfMemoryError API docs reveals that it “Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. “
As we know, the JVM has a parameter that represents the maximum heap size(-Xmx), hence we can defiantly try to increase the heap size. yet some code can generate new instances all the time, if those instances are accessible(being referenced by the main program – in a recursive manner) for the entire program life span, then the GC won’t reclaim those instances. hence the heap will keep increasing and eventually a OutOfMemoryError will be thrown <- we call that memory leak.
Our job as Java developers is to release references (that are accessible by the main program) that we won’t use in the future. by doing that we are making sure that the GC will reclaim those instances (free the memory that those instances occupying in the heap).
In some cases we reference an instance from 2 different roots. one root represent a fast-retrieval space(e.g. HashMap) and the other manages the real lifespan of that instance. Sometimes we would like to remove the reference of that instance from one root and get the other root(fast retrieval) reference removed automatically.
We wouldn’t want to do it manually due to the fact that we are not C++ developers and we wouldn’t like to manage the memory manually..
Weak references
In order to solve that we can use WeakReference.
Instances that are being referenced by only Weak references will get collected on the next collection! (Weakly reachable), in other words those references don’t protect their value from the garbage collector.
Hence if we would like to manage the life span of an instance by one reference only, we will use the WeakReference object to create all the other references.
( usage: WeakReference wr = new WeakReference(someObject);)
In some apps we would like to add all our existing references to some static list, those references should not be strong, otherwise we would have to clean those references manually, we would add those references to the list using this code.
public static void addWeakReference(Object o){
refList.add(new WeakReference(o));
}
since most of the WeakReferences use cases needs a Map data structure, there is an implementation of Map that add a WeakReference automatically for you – WeakHashMap
Soft References
I saw few implementations of Cache using weak references (e.g. the cache is just a WeakHashMap => the GC is cleaning old objects in the cahce), without WeakReferences naive cache can easily cause memory leaks and therefor weak references might be a solution for that.
The main problem is that the GC will clean the cached-object probably and most-likely faster then you need.
Soft references solve that, those references are exactly like weak references, yet the GC won’t claim them as fast. we can be sure that the JVM won’t throw an OutOfMemory before it will claim all the soft and weak references!
using a soft references in order to cache considered the naive generic cache solution. (poor’s men cache)
( usage:SoftReference sr = new SoftReference(someObject);)
Thursday, December 22, 2011
One java - 2 compilers (Javac and JIT)
It seems like that for students there is a lot of confusion regarding how Java/The JVM works because there are TWO compilers involve, so when someone mentions a compiler or the Just In Time compiler some of them would imagine it’s the same one, the Java Compiler..
So how does it really works?
It’s simple..
1) You write Java code (file.java) which compiles to “bytecode“, this is done using the ‘javac” the 1st compiler.
It’s well known fact that Java can be written once get compiled and run anywhere (on any platform) which mean that different types of JVM can get installed over any type of platform and read the same good old byte code
2) Upon execution of a Java program (the class file or Jar file that consists of some classes and other resources) the JVM should somehow execute the program and somehow translate it to the specific platform machine code.
In the first versions of Java, the JVM was a “stupid” interprater that executes byte-code line by line….that was extremely slow…people got mad, there were a lot of “lame-java, awesome c” talks…and the JVM guys got irratated and reinvented the JVM.
the “new” JVM initially was available as an add-on for Java 1.2 later it became the default Sun JVM (1.3+).
So what did they do? they added a second compiler.. Just In Time compiler(aka JIT)..
Instead of interpreting line by line, the JIT compiler compiles the byte-code to machine-code right after the execution..
Moreover, the JVM is getting smarter upon every release, it “knows” when it should interpat the code line-by-line and what parts of the code should get compiled beforehand (still on runtime).
It does that by taking real-usage statistics, and a long-list of super-awesome heuristics..
The JVM can get configured by the user in order to disable/enable some of those heuristics..
To summarize, In order to execute java code, you use two different compilers, the first one(javac) is generic and compiles java to bytecode, the second(jit) is platform-dependent and compiles some portions of the bytecode to machine-code in runtime!
Optimizing and Speeding up the code in Java
Finalizers: object that overwrites the finalize() method (“Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.”) is slower!(for both allocation and collection) if it’s not a must, do clean ups in other ways ( e.g. in JDBC close the connection using the try-catch-finally block instead)
New is expensive: creating new heavy object() on the heap is expensive!, it’s recommended to recycle old objects (by changing their fields) or use the flyweight design pattern.
Strings : (1) Strings are immutable which mean that upon usage of the + operator between 2 strings the JVM will generate a new String(s1+s2) on the heap (expensive as I just mentioned), in order to avoid that, it’s recommended to use the StringBuffer.(Update) since JDK 1.5 was introduced StringBuilder is a better option than Stringbuffer in a single-threaded environment.
(2) Don’t convert your strings to lower case in order to compare them, use String.equalIgnoreCase() instead.
(3) String.startswith() is more expensive than String.charat(0) for the first character.
Inline method: inline is a compiler feature, when you call a method from anywhere in your code, the compiler copies the content of the inline method and replace the line that calls the method with it.
Obviously,It saves runtime time: (1) there is no need to call a method (2) no dynamic dispatch.
In some languages you can annotate a method to be inline, yet in Java it’s impossible, it’s the compiler decision.
the compiler will consider inline a method if the method is private.
My recommendation is to search in your code for methods that are heavily used(mostly in loops) and annotate those method as private if possible.
Don’t invent the wheel: the java api is smart and sophisticated and in some cases use native implementation, code that you probably can’t compete with. unless you know what you are doing (performance wise) don’t rewrite methods that already exists in the java API. e.g. benchmarks showed that coping and array using a for loop is at least n/4 times slower than using System.arraycopy()
Reflection: reflection became much faster for those of you who use the most recent JVMs, yet using reflection is most certainly slower than not using it. which mean that you better avoid reflection if there is no need.
Synchronization: Some data structures auto-support concurrency, in case of a single thread application don’t use those to avoid overhead e.g. use ArrayList instead of a Vector
Multithreads: in case of a multi processor use threads, it will defiantly speed up your code, if you are not a thread expert some compilers know how to restructure your code to thread automatically for you. you can always read a java threads tutorial as well
Get familiar with the standard data structures: e.g. if you need a dast for puting and retriving objects use HashMap and not an ArrayList. (O(1))
Add an id field, for faster equals(): object that contains many fields are hard to compare ( equals() wise), to avoid that add an id(unique) field to your object and overwrite the equals() method to compare ids only.
Be careful, In case your code already works, optimizing it is a sure way to create new bugs and make your code less maintainable!
it’s highly recommended to time your method before and after an optimization.
Sunday, October 9, 2011
101 reasos why java is better than .net
link
Divide by Zero in case of Java
Lets take the case:
What will be the output of this code snippet?
public class NaN { public static void main(String[] args) { double d = 2.0 / 0.0; System.out.println(d); } }
What's the answer: The code will not compile or will it throw a DivideByZero error? Both are wrong. The code compiles fine and the output is,
Let's check another code snippet,
public class NaN { public static void main(String[] args) { double d = 0.0 / 0.0; System.out.println(d); } }
The output in this case is,
NaN
Saturday, October 8, 2011
Hello World in Ruby using Netbeans
Ruby and Ruby on Rails development becomes amazingly easy using Netbeans IDE where you can perform almost all the tasks in one single IDE. Download and install the Netbeans-Ruby version. You should be having JDK installed in your box, thats pretty much the pre-requisite for Netbeans to install.
OR you can simply download the complete version of netbeans and install ruby plugins.
Download the ruby from here. Extract it to some location, Say C:\\ruby
Now create new project.
Launch Netbeans go to File --> New Project. A new project wizard should come up. Select Ruby Application i.e. C:ruby\bin., click Next and click Finish. Thats it!!!!
You dont even have to type a Hello World. The new project template does it for you! So sweet isnt it? Now, click on the big green Run button and the console should print out Hello World without a hitch.
Now just run the program :)
installing RadRails on Eclipse
Help-->Software Updates --> Find and Install....
then in the pop - up window which appears ,..
Search for new features to install
and then click next and then u will have to add 2 new remote sites, .. the details for the sites are the ones which were very difficult to obtain , they are
site 1 :
Name :RadRails
URL : http://radrails.sourceforge.net/update
site 2 :
Name :RDT
URL : http://updatesite.rubypeople.org/release
then click on finish , u are almost done with the installation , u have to just follow the instructions from here on to finish the installation .
Monday, October 3, 2011
Making collections final
We can add, delete objects from this list, but I can not
So declaring the
list final means that you cannot reassign the list variable to another object.There are two situations in which this can be useful.
- You want to make sure that no-one reassigns your
listvariable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood). - When using inner classes you need to declare variables as
finalin an enclosing scope so that you can access them in the inner class. This way, Java can copy yourfinalvariable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.
Tuesday, September 27, 2011
Difference between Proxy, Decorator, Adaptor, and Bridge Patterns ?
- Proxy could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.
See proxy pattern with details. - Decorator is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.
- Adapter / Wrapper is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.
In particular Decorator looks very close to Adapter but still there is basic difference:
Adapter / Wrapper Decorator Composes "origin" class True True Modifies original interface True False Modifies behavior of interfaceFalse True Proxies method calls True True See Adapter pattern and Decorator Pattern with examples. - Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.
See bridge pattern with example. - Facade is a higher-level (read: simpler) interface to a subsystem of one or more classes. Think of Facade as a sort of container for other objects, as opposed to simply a wrapper. So you don't have to worry about so many things, just call the facade to do all the stuff.
See Facade pattern with example.
Interface And Abstraction – Spiritual Explanation
Thursday, September 22, 2011
Shallow Copy and Deep Copy
Here is what they mean:
Shallow Copy
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.
Deep Copy
Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
![]() |
| Shallow Copy |
![]() |
| Deep Copy |
You may like :
Design patterns using shallow copy and deep copy - Prototype pattern
Shallow and deep copy using clone
MVC Pattern Basics
The Model-View-Controller (MVC) architectural pattern is used in software engineering to allow for the separation of three common features in GUI applications:
- the data access (typically via a database)
- the business logic (how the data will be used)
- user interaction (how the data and actions will be visually presented)
MVC pattern differenciates all the 3 aspects of application in 3 difft tiers.
Modal
It incorporates following point
- Holds the business logic of the application.
- holds data sent between different. tiers like JSP to servlet and handler classes.
- One of the goals of the model is to give a presentation which does not directly refer to any specific DBMS.
View
- This represents the visible user interface, so handles presentation tier of the application.
- it knows enough about the data to create a coherent presentation, but does not actually do the work of presenting the data. Instead, it provides the ability to manipulate data outside the View through event handlers defined within.
- handles presentation logic, client side validation.
- e.g. HTML, JSP
Controller
- handles the flow of the application
- Joins the Model with the View and is the heart of the business logic.
- It is the source of activity when an event occurs and defines the event handling actions which access data (from the Model) and are presented to the user (in the View).
- e.g. Servlets, Action Class in Struts, ActionServlet is using struts-config.xml as front controller to handle each request and redirect it to appropriate destination.
Advantages
- Increases modularity of the application.
- Increases Maintainability of the application, i.e. the data presentation can be changed without any notion of how the data is obtained and conversely, the data access can be changed without any knowledge of how it is to be presented.
to be added soon
Java: Rounding off to 2 decimal places
Method 1:
x = (double)int((x+0.005)*100.0)/100.0;
Method 2:
x = Math.round(x*100.0) / 100.0;
Method 3:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
Method 4:
f = (float) (Math.round(n*100.0f)/100.0f);
Method 5:
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); // setScale is immutable
r = bd.doubleValue();
System.out.println(r); // r is 5.12
[source: www.thescripts.com, accuracy unchecked]
How I did it:
float percentage = score.floatValue()/(qapairs.length*10)*100; //my float value
percentage = Float.valueOf((new DecimalFormat("###.00").format(percentage)));
Friday, July 15, 2011
The Value of String.valueOf
Most Java developers have probably had their fill of NullPointerException. Most of us have learned the value of doing certain things to reduce our "opportunities" of encountering the NullPointerException. Indeed, there is a Wiki page dedicated to preventing or reducing NullPointerExceptions.
Several people have argued for additional language support for improved and easier handling of potential null. These include Java SE 7 proposals, Optimized Null Check, and Kinga Dobolyi's thesis Changing Java’s Semantics for Handling Null Pointer Exceptions.
Among the many things we can already do rather easily to reduce our encounters with NullPointerException, one particular easy thing to do is to apply String.valueOf(Object) when appropriate. The String.valueOf(Object) method, as its Javadoc-generated documentation states, returns "null" if the passed in object is null and returns the results on the passed-in Object's toString() call if the passed-in Object is not null. In other words, String.valueOf(String) does the null checking for you.
The use of String.valueOf(Object) is particularly useful when implementing toString methods on custom classes. Because most toString implementations provide the class's data members in String format, String.valueOf(Object) is a natural fit. All Java objects based on classes that extend Object provide a toString() implementation even if it is simply their parent's (or even Object's) implementation of toString(). However, if a member class implements toString but the member itself is null rather than an instance of the class, then the toString() does no good (and actually leads to a NullPointerException when called).
This is demonstrated with the following example code.
Consider a class called PersonName, which holds last name and first name of the person:
package com.vaani.string;
/**
* Class upon which to call toString.
*/
public class PersonName
{
private String lastName;
private String firstName;
public PersonName(final String newLastName, final String newFirstName)
{
lastName = newLastName;
firstName = newFirstName;
}
/**
* Provide String representation of me.
*
* @return My String representation.
*/
@Override
public String toString()
{
return firstName + " " + lastName;
}
}
Person.java
package com.vaani.string;
public class Person
{
private PersonName name;
public Person( PersonName newName)
{
name = newName;
}
/**
* Provide String representation of me.
*
* @return My String representation.
*/
public String toString()
{
//to be implemented
}
}
Now this person.java has toString() which is to be implemented, but we will see how it throws NPE. Consider the main method:
PersonName personName = new PersonName("Flintstone", null);Output will be:
//print personname as string
System.out.println("Person's Name [DIRECT]: " + personName);
System.out.println("Person's Name [TOSTRING]: " + personName.toString());
System.out.println("Person's Name [STRING.VALUEOF]: " + String.valueOf(personName));
Person's Name [DIRECT]: null Flintstone
Person's Name [TOSTRING]: null Flintstone
Person's Name [STRING.VALUEOF]: null Flintstone
Also if we call Person's constructor with personName(instance created above), everything will still be fine:
PersonName name;
//code skipped
public String toString()
{
// Don't use -- can lead to runtime error (NullPointerException)
return name.toString();
}
PersonName personName = new PersonName("Flintstone", null);
//create next object from personName
Person personOne = new Person(personName);
System.out.println("Person One [DIRECT]: " + personOne);
System.out.println("Person One [TOSTRING]: " + personOne.toString());
System.out.println("Person One [STRING.VALUEOF]: " + String.valueOf(personOne));
Person personTwo = new Person(null);Each of this above line throws exception. So please be aware of this. To avoid null pointer exception you can implement toString() func of Person like this:
System.out.println("Person Two [DIRECT]: " + personTwo);
System.out.println("Person Two [TOSTRING]: " + personTwo.toString());
System.out.println("Person Two [STRING.VALUEOF]: " + String.valueOf(personTwo));
public String toString()Now the personTwo will be printed as null.
{
// It's all good
return String.valueOf(name);
}
Full code listing for Person.java(personName.java is already covered):
package com.vaani.string;
public class Person
{
private PersonName name;
public Person( PersonName newName)
{
name = newName;
}
/**
* Provide String representation of me.
*
* @return My String representation.
*/
public String toString()
{
// Don't use -- leads to compiler time error (incompatible types)
//return name;
// Don't use -- can lead to runtime error (NullPointerException)
//return name.toString();
// It's all good
return String.valueOf(name);
}
}
package com.vaani.string;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;
/**
* Example class demonstrating use of String representations available through
* implicit String, toString(), and String.valueOf().
*/
public class StringValueFunc
{
private static final String NEW_LINE = System.getProperty("line.separator");
/** Using java.util.logging. */
private static Logger LOGGER = Logger.getLogger(
StringValueFunc.class.getName());
/**
* Main function for running tests/demonstrations.
*
* @param arguments Command-line arguments; none anticipated.
*/
public static void main(final String[] arguments)
{
//takes last name and first name
PersonName personName = new PersonName("Flintstone", null);
//create next object from personName
Person personOne = new Person(personName);
//just initiate to null
Person personTwo = new Person(null);
printHeader("String representation of direct Strings", System.out);
System.out.println("Person's Name [DIRECT]: " + personName);
System.out.println("Person's Name [TOSTRING]: " + personName.toString());
System.out.println("Person's Name [STRING.VALUEOF]: " + String.valueOf(personName));
printBlankLine(System.out);
printHeader("String representation of non-null complex object", System.out);
System.out.println("Person One [DIRECT]: " + personOne);
System.out.println("Person One [TOSTRING]: " + personOne.toString());
System.out.println("Person One [STRING.VALUEOF]: " + String.valueOf(personOne));
printBlankLine(System.out);
printHeader("String representation of null complex object", System.out);
System.out.println("Person Two [DIRECT]: " + personTwo);
System.out.println("Person Two [TOSTRING]: " + personTwo.toString());
System.out.println("Person Two [STRING.VALUEOF]: " + String.valueOf(personTwo));
printBlankLine(System.out);
}
public static void printHeader(final String message, final OutputStream out)
{
final String headerSeparator =
"====================================================================";
try
{
out.write((headerSeparator + NEW_LINE + message + NEW_LINE).getBytes());
out.write((headerSeparator + NEW_LINE).getBytes());
}
catch (IOException ioEx)
{
System.out.println(headerSeparator);
System.out.println(message);
System.out.println(headerSeparator);
LOGGER.warning("Could not write header information to provided OutputStream.");
}
}
public static void printBlankLine(final OutputStream out)
{
try
{
out.write(NEW_LINE.getBytes());
}
catch (IOException ioEx)
{
System.out.println(NEW_LINE);
LOGGER.warning("Could not write blank line to provided OutputStream.");
}
}
}
The above code can be used to demonstrate building of a
toString method on a complex object and how its behaves when called by an owning class. The method of most interest is at the bottom of the code shown above. Two return values are commented out because of problems associated with them. The final example, using String.valueOf(Object) is NOT commented out because it works the best each time it is run whether or not the complex PersonName object is null. The next three images show the output for each of these presentations of the Person objects' String representations.Finally, the String class provides many overloaded valueOf methods. In addition to the version that was the focus of this blog post (accepts an Object), the other overloaded versions of valueOf accept primitive data types and arrays of primitive data types.
Conclusion
Regardless of what the future brings in terms of improved null handling in Java, there are many tactics we can take today to reduce the unwanted (sometimes we actually do want them thrown!) occurrences of NullPointerException. One of these is to use String.valueOf(Object) when appropriate.
Additional Resources






