Tuesday, December 10, 2013

Thread Scheduling

Execution of multiple threads on a single CPU in some order is called Thread Scheduling. The Java Runtime Environment supports a very simple, deterministic algorithm called fixed-priority scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads.

When a thread is created, it inherits the priority from the thread that creates it. In addition, by using the setPriority method, you can modify a thread's priority at any time after its creation.

Thread priorities ranges between MIN_PRIORITY and MAX_PRIORITY.

Following are the main features of Thread Scheduling:
  • The JVM schedules using a pre-emptive, priority based algorithm.
  • All threads have a priority and the thread with the highest priority is scheduled to run by the JVM.
  • In case two threads have the same priority, FIFO ordering is followed.
  • A different thread is invoked to run in case one of the following events occur:
    • The currently running thread exits the Running state. i.e., either blocks or terminates.
    • A thread with a higher priority than the thread currently running enters the Runnable state. The lower priority thread is preempted and the higher priority thread is scheduled to run.
  • Time slicing is dependent on the algorithm implementation.
  • A thread can voluntarily give up its right to execute at any time by calling the yield() method. This process is called Cooperative Multitasking. Threads can yield the CPU only to other threads of the same priority. Attempts to yield to a lower-priority thread are ignored.

Monday, December 9, 2013

Thread Priorities

  • Every thread has a priority.
  • The priority of a thread is used to inform the thread scheduler how important the thread to get picked.
  • Threads with higher priority are executed in preference to threads with lower priority.
  • Below are the thread priorities that Java API provides
    • MAX_PRIORITY - The maximum priority a thread can have.
    • NORM_PRIORITY - The default priority that is assigned to a thread.
    • MIN_PRIORITY - The minimum priority that a thread can have.
  • Java API offers method to get and set the priorities of the thread.
    • getPriority() method:
                               Return the thread's priority.
    • setPriority() method:
                              Changes the priority of this thread. First checkAccess() method of this thread, to determine if the currently running thread has permission to modify the thread, is called with no arguments. This may result in throwing SecurityException. If the priority is not in the range MIN_PRIORITY and MAX_PRIORITY, an IllegalArgumentException will be thrown.

    • toString() method:
                             Returns a string representation of the thread, including thread name, priority, and thread group.

  • The priority of a newly created thread is set equal to the priority of the thread creating it, that is, the currently running thread. The method setPriority() may be used to change the priority to a new value.

Sunday, December 8, 2013

The Lifecycle of a Thread in Java

Understanding the lifecycle of threads is very important while programming in Threads.

A Thread can be various states during its life time. The following diagram describes all the states a thread can undergo and the method calls that cause the transition from one state to another:


Java Thread States
  1. Runnable: A Thread starts its life from this state. Thread first enters into this state after the start() method of the thread is invoked. In this state, thread will be waiting for the scheduler to pick the thread for execution. The scheduler picks the threads based on their priorities. A thread can also re-enter this state either after running, waiting, sleeping or also while coming back from blocked state.
  2. Running: A thread is in running state means its currently running. There are several ways for thread to go into Runnable state. But there is only one way to come into Running state: the scheduler selects the thread for execution for the runnable pool. A thread runs until its swapped out, becomes blocked, or voluntarily give up its turn by invoking the static method Thread.yield().
  3. Dead: A thread enters this state when it completes execution. It may also enters this state when it is terminated by unrecoverable error condition. If a thread goes to this state means it can not be run again.
  4. Sleep: A Java thread may be forced to sleep (suspend) for some predefined time. In this state, thread is still alive but is not runnable, it might be return to runnable state later. It can throw InterruptedException.
  5. Blocked: A thread can enter blocked state because of waiting for the resources that are held by another thread.
    1. Blocked on I/O: Thread enters this state because of waiting for I/O resources. In this case, the thread will be sent back to Runnable state after the availability of resources.
    2. Blocked on Synchronization: Thread may enters this state while waiting for object lock. Thread will be moved to Runnable state after it acquires lock.
  6. Waiting state: A call to Object.wait() method causes the current object to wait. The thread remains in waiting state until some other thread invokes notify() or notifyAll() method of this object.

Release 5.0 introduced the Thread.getState() method, which results in one of the following Thread.State values:
  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED
The Thread class API also introduced a method isAlive(), which returns true if the thread has already been started and not stopped. If the method isAlive() returns false, the thread is either New, or is Dead.

Tuesday, December 3, 2013

Concurrency in Java

If a system that allows to execute multiple tasks simultaneously that system is called a Concurrent System

The Java language and the JVM have been designed to support concurrent programming from the beginning. Since Java 5.0 version, it has also included high-level concurrency APIs in java.uti.concurrent packages. Also the later versions introduced updated versions of the existing APIs, also added several new APIs.

 

Processes and Threads:

 

  • In concurrent programming, there are two basic units of execution, called processes and threads. In Java, concurrent programming mainly concerned about threads.
  • A process has a self-contained execution environment. It generally has a complete private set of basic run-time resources, in particular, each process has its own memory space.
  • Threads are sometimes called as lightweight processes. Both processes and threads provide and execution environment, but creating new threads requires fewer resources than required for new processes.
  • Threads exist within a process. Every process has at least one thread
  • Threads share the process's resources, including memory and open files. 
  • Java Program runs in its own process and by default in one thread.


 Thread Basics:

  • A thread is a thread of execution. 
  • The JVM allows an application to have multiple threads of execution running concurrently. 
  • Each thread has a priority. Threads with higher priority are executed in preference to the threads with the lower priority. 
  • Each thread may or may not have also marked a Daemon
  • When a JVM starts up, there is usually a single non-daemon thread (which typically invokes the main method).
  • The JVM continues to execute the threads until either of the following occurs:
    • The exit method of Runtime class has been invoked and the security manager has allowed the exit method to execute.
    • All threads that are not daemon threads have died, either by returning from the run method call or by throwing an exception.

 

Creating and Running Threads:


Threads can be created in two ways: 
    • Extending Thread class and overriding run() method.
    • Building a class that implements Runnable interface and then creating an object of Thread class passing the Runnable object as a parameter.
Below is a simple example of creating threads using the second approach. This example creates 10 threads, each of the thread calculate and prints the multiplication tables from 1 to 10.

Steps to implement the example:
  • Create a class Name Calculator implementing Runnable interface.
public class Calculator implements Runnable
  • Declare a private int attribute named number and implement the constructor to initialize its value.
private int number;
  • Implement the run() method. This method calculates the multiplication table of the number.
@Override
 public void run() {
  for (int i = 1; i <= 10; i++) {
   System.out.printf("%s: %d * %d = %d\n", Thread.currentThread()
     .getName(), number, i, i * number);
  }
 }
  • Implement the main class of the application, which contains main() method.
  • Inside the main() method, create a for loop with 10 iterations. Inside for loop, create an object of Calculator class, an object of the Thread class, pass the object of Calculator class as a parameter, and invoke the start() method of the Thread object.
public class Main {
 public static void main(String[] args) {
  for(int i=0; i<10; i++){
   Thread thread = new Thread(new Calculator(i));
   thread.start();
  }
 }
}


Below is the partial output of a sample run of the above code:



  • Every Java Program has atleast one thread in Execution. When we run a program, JVM runs the execution thread that calls main() method.
  • Creating an object to the Thread class doesn't create an execution of the Thread. Or calling the run() method of the implemented Runnable interface will not create a new execution of Thread. Invoking start() method on creates a new execution thread.
  • When we call the start() method of Thread object, it creates another execution thread. Our program will have as many threads as calls to the start() method are made.
  • A Java program ends when all its threads(all non-daemon) finishes.
  • If the initial thread(the one that executes main() method) ends, the rest of threads continue with their execution until they finish.
  • If a thread is exited by calling System.exit(), all threads end their execution.


References:
  • http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html
  • http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/
  • Java 7 Concurrency Book by Javier Fernández

What is the difference between Concurrency and Parallelism?

Parallelism:
            Parallelism is when multiple tasks literally executing at the same time. This arises when two threads are executing simultaneously.

            Ex: Running Multiple tasks on a multi core processor.
 
Concurrency:
  • Concurrency is when multiple tasks can start, run and complete execution in overlapping time periods. It doesn't necessarily mean that they will be running at the same instant.
  • This occurs when at least two threads are making progress.
  • This is a more generalized form of parallelism that includes time-slicing as a form of virtual parallelism.
          Ex: Multitasking in a single core processor.

Concurrent Programming

Concurrent Programming?

It is about the elements and mechanisms a platform offers to have multiple tasks or programs to execute at once and communicate each other exchanging data or to synchronize to each other.


When you work with a computer, you can do several things at once. You can hear music while you edit a document in a word processor and read your e-mail. This can be done because your operating system allows the concurrency of tasks.

Is Java a Concurrent Platform?

Yes. Java is a concurrent platform and offers a lot of API to execute concurrent tasks in a Java Program. Java continuously increasing the functionalities offered to facilitate the development of concurrent programs with each version.

All Modern Operating systems allows concurrent tasks execution.

For ex, you can read emails while listening to music. This is called Process-level concurrency
But inside a process we can have multiple tasks which can be executed simultaneously.  So, the concurrent tasks that run inside a process are called as threads.

Wednesday, February 1, 2012

Programming Language Syntax Highlighting with Blogger Engine

We can enable the Syntax highlighting for the Programming language code in the blogs using "Syntax Highlighter" JavaScript Library.

We can achieve that with the following steps.

1. Adding Syntax Highlighter library to blogger template.

Copy the following code.

















paste it into your Blogger Template just above the tag.
Save the template.
Then you can start creating code blocks in your existing or new Blog entries.
There are 2 ways to add a code block using syntaxhighlighter.

Method 1 : Using script tag




becomes

// Comment
public class Testing {
public Testing() {
}

public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}


Method 2 : Using pre tag
// Comment
public class Testing {
public Testing() {
}

public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}
becomes

// Comment
public class Testing {
public Testing() {
}

public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}


Ref::
http://www.craftyfella.com/2010/01/syntax-highlighting-with-blogger-engine.html

Tuesday, January 31, 2012

Useful Best Practices in Java

1. Always prefer to lazy initialization to Defer Creating Objects until we need them.

Object creation in Java is the most expensive operation in terms of memory utilization and performance impact. Hence it is advised to create or initialize the Object only when it is required in the code.

public class myClass {
private mySampleObject myObj;
public mySampleObject getSampleObject() {
if (null == myObj)
myObj = new mySampleObject();

return myObj;
}
}

The advice for lazy initialization from Joshua Bloch is:
"Don't do it unless you need to."

The great majority of your initialization code should look like this:

// Normal initialization, not lazy!
private final FieldType field = computeFieldValue();


If you need lazy initialization for correctness -- but not for performance -- just use a synchronized accessor. It's simple and clearly correct.

If you need better performance, your best choice depends on whether you're initializing a static field or an instance field. If it's a static field, use the lazy initialization holder class idiom:

// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
static FieldType getField() { return FieldHolder.field; }


This idiom is almost magical. There's synchronization going on, but it's invisible. The Java Runtime Environment does it for you, behind the scenes. And many VMs actually patch the code to eliminate the synchronization once it's no longer necessary, so this idiom is extremely fast.

If you need high-performance lazy initializing of an instance field, use the double-check idiom with a volatile field. This idiom wasn't guaranteed to work until release 5.0, when the platform got a new memory model. The idiom is very fast but also complicated and delicate, so don't be tempted to modify it in any way. Just copy and paste -- normally not a good idea, but appropriate here:

// Double-check idiom for lazy initialization of instance fields.
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) { // First check (no locking)
synchronized(this) {
result = field;
if (result == null) // Second check (with locking)
field = result = computeFieldValue();
}
}
return result;
}


2. Use Private Fields. Never make an instance field of a Class Public.

Making a field private protects it from unsynchronized access. Controlling its access means the field need to be synchronized only in the class's critical sections when it is being modified.

Making a class field private can introduce lot of issues. For example, if we have a class called MyClass contains an array of String weekdays. You may have assume that this array will always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!
public class MyCalender {

public String[] weekdays =
{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};

}

Best approach as many of you already know is to always make the field private and add a getter method to access the elements.
private String[] weekdays =
{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};

public String[] getWeekdays() {
return weekdays;
}

But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to.
public String[] getWeekdays() {
return weekdays.clone();
}
3. Always try to minimize the mutability of a class.

Immutable means the state of the object cannot be changed, therefore an object with no accessors to the field is immutable (if none of the methods change the state either). Hence, the class is immutable means unmodifiable.

Its easy to maintain immutable classes because they not be modifiable hence thread safe. The data the class carries stays the same through out the lifetime of the class.

However, making an object immutable can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.
public class Employee {

private String firstName;
private String lastName;

public String getFirstName(){
return this.firstName;
}

public String getLastName(){
return this.lastName;
}

}
4. Prefer Interfaces over Abstract classes.
5. Always Try to limit the scope of the local variables.

Minimizing the scope of a local variable makes code more readable, less error prone and also improves the maintainability of the code.

Thus, declare a variable only when needed just before its use.

Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.

6. Try to use Standard libraries instead of writing on own from Scratch.

Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.

For instance Google has just released a new library Google Collections that can be used if you want to add advance collection functionality in your code.

7. Use Strings with utmost care.

Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it creates a new String object. This will affect both memory usage and performance time.

Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly. For example:
//slow instantiation
String slow = new String("Yet another string object");

//fast instantiation
String fast = "Yet another string object";

8. Defensive copies are savior.

Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.
public static void main(String []arg) {

Date birthDate = new Date();
Student student = new Student(birthDate);

birthDate.setYear(2019);

System.out.println(student.getBirthDate());
}

Now we may have some other code that uses the Student object.
public static void main(String []arg) {

Date birthDate = new Date();
Student student = new Student(birthDate);

birthDate.setYear(2019);

System.out.println(student.getBirthDate());
}

In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!

To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.
public Student(birthDate) {
this.birthDate = new Date(birthDate);
}

This ensure we have another copy of birthdate that we use in Student class.

9. Never let exceptions come out of "finally" block.

Finally blocks should never have code that throws exception. Always make sure finally clause does not throw exception. If you have some code in finally block that does throw exception, then log the exception properly and never let it come out..

Ref:
----
http://java.sun.com/developer/technicalArticles/Interviews/bloch_effective_08_qa.html
http://viralpatel.net/blogs/2010/02/most-useful-java-best-practice-quotes-java-developers.html

Sunday, October 2, 2011

Tips to improve Vocabulary

To improve Vocabulary, We need

Reading Material
Dictionary
Notebook
Note Cards
Word-a-day Calendars
Internet Access
Crossword Puzzles

Step 1:
Read as much as you can to encounter the words you didnt already know.

Step 2:
Use a dictionary to look up the unfamiliar words you come across in your reading.
Remember a word can have a different meanings . Know all of the definitions of the word.

Step 3:
Use a notebook to keep the list of the vocabulary words. Write the definition as well as the sentence using the word to help you remember the context.
Use an address to keep an alphabetical order of your words.

Step 4:
Create a Flash cards to reenforce your new words.
Write the word on the one side of the card and the definition on the other side. Quiz yourself by looking at the word and remember the definitions.

Step 5:
Make efforts to learn a word every day. Use a word a day calendars and websites to introduce to new words.
Learn common prefixes and suffixes. These parts that comes together to create words can help you figure out what a word means.

Step 6:
Play word games. Use computer games or cross word puzzles to grow your vocabulary and helps reinforce the words you are learning.

Step 7:
Use your new words in your daily conversation. Continue using and reviewing your words to reenforce what you have learned.

Monday, September 26, 2011

Physical exercise

Physical exercise is any bodily activity that enhances or maintains physical fitness and overall health and wellness. It is performed for various reasons including strengthening muscles and the cardiovascular system, honing athletic skills, weight loss or maintenance, as well as for the purpose of enjoyment. Frequent and regular physical exercise boosts the immune system, and helps prevent the "diseases of affluence" such as heart disease, cardiovascular disease, Type 2 diabetes and obesity. It also improves mental health, helps prevent depression, helps to promote or maintain positive self esteem, and can even augment an individual's sex appeal or body image, which is also found to be linked with higher levels of self esteem. Childhood obesity is a growing global concern and physical exercise may help decrease the effects of childhood obesity in developed countries.

Sunday, December 19, 2010

How to configure root application in Tomcat??

http://techlightening.wordpress.com/2009/05/13/tomcat-change-default-web-application/

Tuesday, December 7, 2010

How can we write connection pooling using Vector, ArrayList classes in java??

//Comment
package connection.pooling;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

public class ConnectionPooling {

Vector connections = null;
static ConnectionPooling instance = null;
public static final int MAX_CONNECTIONS = 10;

private ConnectionPooling() {
initialize();
}

public synchronized void removeAllConnections() {

if (connections == null) {
return;
}

try {
int sz = connections.size();
for (int i = 0; i < sz / 2; i++) {
connections.remove(i);
System.out.println("Removing Connection " + i);
}
if (connections != null && connections.size() > 0) {
connections.removeAllElements();
System.out.println("Removing all the remaining Connections");
}
connections = null;
} catch (Exception e) {
System.out.println("Error " + e);
}
instance = null;

}

public static synchronized ConnectionPooling getInstance() {
if (instance == null)
instance = new ConnectionPooling();

return instance;
}

public synchronized void initialize() {

if (connections == null) {

try {
Class.forName("com.mysql.jdbc.Driver");
connections = new Vector();
int count = 0;
while (count < MAX_CONNECTIONS) {
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/test",
"root", "root");
connections.addElement(c);
count++;
}
System.out.println("total connections created r: " + count);
} catch (Exception e) {
System.out.println("initialise:Exception");
e.printStackTrace();
instance.removeAllConnections();
}
}
}
public synchronized Connection getConnection() {
System.out.println("getConnection");
Connection c = null;
if (connections == null)
return null;
if (connections.size() > 0) {
c = (Connection) connections.elementAt(0);
connections.removeElementAt(0);
}
return c;
}

public synchronized void putConnection(Connection c) {

if (c != null) {
connections.addElement(c);
notifyAll();
}
}

public static void main(String[] args) {
ConnectionPooling cp = ConnectionPooling.getInstance();
cp.removeAllConnections();
}
}

What is Connection Pooling????

Many applications needs to connect to database for retrieving, updating, deleting and inserting the data. For every activity with the database there needs to be a connection established by the application server. If tens of thousands of connections are made to database server for every request then it chokes-up the network and server hangs.

To avoid this the Connection Pooling mechanism provides way of storing established connections in the memory.

This is nothing but pool all the connections at one place. Every time a database connection needs to be established a request is made to pool or any object which holds all the connections to provide a connection. Once that particular database activity is completed the connection is returned back to the pool.

Many J2EE application servers provide their own connection pooling mechanism.

Monday, May 17, 2010

Some useful links for Java beginners

http://www.javabeginner.com/
http://skeletoncoder.blogspot.com/2006/09/java-tutorials-arraylist-or-vector.html
http://www.codeguru.com/java/tij/tij0128.shtml
http://www.coderanch.com
.
.
.
.

Controlling Cloneability

If you want a class to be cloneable:

1. Implement the Cloneable interface.
2. Override clone( ).
3. Call super.clone( ) inside your clone( ).
4. Capture exceptions inside your clone( ).

This will produce the most convenient effects.


Courtesy: http://www.codeguru.com/java/tij/tij0128.shtml

Saturday, September 5, 2009

Top 10 errors Java programmers make

Making mistakes is the common human nature, but we need to ensure that we shouldn't do repetitive mistakes. There are a few mistakes usually all Java programmers do irrespective of their experience. They are......

10. Accessing non-static member variables from a static method.

public class StaticDemo
{
public String my_member_variable = "somedata";
        public static void main (String args[])
{
// Access a non-static member from static method
System.out.println ("This generates a compiler error" +
my_member_variable );
}
}
main is a static method. So, we must create an instance of the class if we want to access the non-static members of the class.


9. Mistyping the name of the method while overriding

public class MyWindowListener extends WindowAdapter {
// This should be WindowClosed
public void WindowClose(WindowEvent e) {
// Exit when user closes window
System.exit(0);
}
});

Compilers won't pick up on this one, and the problem can be quite frustrating to detect. In the past, I've looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn't being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn't being called, then it's likely you've mistyped the name.


8. Comparision assignment (= instead of ==)

Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.

7. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Here's the correct way to compare two strings.

String abc = "abc"; String def = "def";

// Bad way
if ( (abc + def) == "abcdef" )
{
......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
.....
}

6. Confusion over pass by value and pass by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you're passing by value, and when you're passing by reference.

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value.


When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type. So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.

On a side note, since String contains no methods to modify its contents, you might as well be passing by value.

5. Writing blank Exception handlers

I know it's very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and haven't written any error messages, it becomes almost impossible to find out the cause of the error.

4. Forgetting that Java is 0-based index

3. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Don't be fooled into thinking that such problems won't occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already, right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
{
count = amount;
}

public synchronized int getCount()
{
return count;
}
}

2. Capitalization errors

This is one of the most frequent errors that we all make. It's so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don't spot the lack of capitalization.


And.. last but not the least.....


1. NULL Pointers!!!!

Null pointers are one of the most common errors that Java programmers make. Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.

Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!

Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.

public static void main(String args[])
{
// Accept up to 3 parameters
String[] list = new String[3];

int index = 0;

while ( (index < i =" 0;">

This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you'll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won't. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

Courtesy : http://www.javacoffeebreak.com/articles/toptenerrors.html

Sunday, August 30, 2009

Run Commands

Program Run Command
Accessibility Controls access.cpl
Accessibility Wizard accwiz
Add Hardware Wizard hdwwiz.cpl
Add/Remove Programs appwiz.cpl
Administrative Tools control admintools
Adobe Acrobat ( if installed ) acrobat
Adobe Distiller ( if installed ) acrodist
Adobe ImageReady ( if installed ) imageready
Adobe Photoshop ( if installed ) photoshop
Automatic Updates wuaucpl.cpl

Basic Media Player mplay32
Bluetooth Transfer Wizard fsquirt

Calculator calc
Ccleaner ( if installed ) ccleaner
C: Drive c:
Certificate Manager cdrtmgr.msc
Character Map charmap
Check Disk Utility chkdsk
Clipboard Viewer clipbrd
Command Prompt cmd
Command Prompt command
Component Services dcomcnfg
Computer Management compmgmt.msc
Compare Files comp
Control Panel control
Create a shared folder Wizard shrpubw

Date and Time Properties timedate.cpl
DDE Shares ddeshare
Device Manager devmgmt.msc
Direct X Control Panel ( if installed ) directx.cpl
Direct X Troubleshooter dxdiag
Disk Cleanup Utility cleanmgr
Disk Defragment dfrg.msc
Disk Partition Manager diskmgmt.msc
Display Properties control desktop
Display Properties desk.cpl
Display Properties (w/Appearance Tab Preselected ) control color
Dr. Watson System Troubleshooting Utility drwtsn32
Driver Verifier Utility verifier

Ethereal ( if installed ) ethereal
Event Viewer eventvwr.msc

Files and Settings Transfer Tool migwiz
File Signature Verification Tool sigverif
Findfast findfast.cpl
Firefox firefox
Folders Properties control folders
Fonts fonts
Fonts Folder fonts
Free Cell Card Game freecell

Game Controllers joy.cpl
Group Policy Editor ( xp pro ) gpedit.msc

Hearts Card Game mshearts
Help and Support helpctr
Hyperterminal hypertrm
Hotline Client hotlineclient

Iexpress Wizard iexpress
Indexing Service ciadv.msc
Internet Connection Wizard icwonn1
Internet Properties inetcpl.cpl
Internet Setup Wizard inetwiz
IP Configuration (Display Connection Configuration) ipconfig /all
IP Configuration (Display DNS Cache Contents) ipconfig /displaydns
IP Configuration (Delete DNS Cache Contents) ipconfig /flushdns
IP Configuration (Release All Connections) ipconfig /release
IP Configuration (Renew All Connections) ipconfig /renew
IP Configuration (Refreshes DHCP & Re-Registers DNS) ipconfig /registerdns
IP Configuration (Display DHCP Class ID) ipconfig /showclassid
IP Configuration (Modifies DHCP Class ID) ipconfig /setclassid

Java Control Panel ( if installed ) jpicpl32.cpl
Java Control Panel ( if installed ) javaws

Keyboard Properties control keyboard

Local Security Settings secpol.msc
Local Users and Groups lusrmgr.msc
Logs You Out of Windows logoff

Malicious Software Removal Tool mrt
Microsoft Access ( if installed ) access.cpl
Microsoft Chat winchat
Microsoft Excel ( if installed ) excel
Microsoft Diskpart diskpart
Microsoft Frontpage ( if installed ) frontpg
Microsoft Movie Maker moviemk
Microsoft Management Console mmc
Microsoft Narrator narrator
Microsoft Paint mspaint
Microsoft Powerpoint powerpnt
Microsoft Word ( if installed ) winword
Microsoft Syncronization Tool mobsync
Minesweeper Game winmine
Mouse Properties control mouse
Mouse Properties main.cpl
MS-Dos Editor edit
MS-Dos FTP ftp

Nero ( if installed ) nero
Netmeeting conf
Network Connections control netconnections
Network Connections ncpa.cpl
Network Setup Wizard netsetup.cpl
Notepad notepad
Nview Desktop Manager ( if installed ) nvtuicpl.cpl

Object Packager packager
ODBC Data Source Administrator odbccp32
ODBC Data Source Administrator odbccp32.cpl
On Screen Keyboard osk
Opens AC3 Filter ( if installed ) ac3filter.cpl
Outlook Express msimn

Paint pbrush
Password Properties password.cpl
Performance Monitor perfmon.msc
Performance Monitor perfmon
Phone and Modem Options telephon.cpl
Phone Dialer dialer
Pinball Game pinball
Power Configuration powercfg.cpl
Printers and Faxes control printers
Printers Folder printers
Private Characters Editor eudcedit

Quicktime ( if installed ) quicktime.cpl
Quicktime Player ( if installed ) quicktimeplayer

Real Player ( if installed ) realplay
Regional Settings intl.cpl
Registry Editor regedit
Registry Editor regedit32
Remote Access Phonebook rasphone
Remote Desktop mstsc
Removable Storage ntmsmgr.msc
Removable Storage Operator Requests ntmsoprq.msc
Resultant Set of Policy ( xp pro ) rsop.msc

Scanners and Cameras sticpl.cpl
Scheduled Tasks control schedtasks
Security Center wscui.cpl
Services services.msc
Shared Folders fsmgmt.msc
Sharing Session rtcshare
Shuts Down Windows shutdown
Sounds Recorder sndrec32
Sounds and Audio mmsys.cpl
Spider Solitare Card Game spider
SQL Client Configuration clicongf
System Configuration Editor sysedit
System Configuration Utility msconfig
System File Checker Utility ( Scan Immediately ) sfc /scannow
System File Checker Utility ( Scan Once At Next Boot ) sfc /scanonce
System File Checker Utility ( Scan On Every Boot ) sfc /scanboot
System File Checker Utility ( Return to Default Settings) sfc /revert
System File Checker Utility ( Purge File Cache ) sfc /purgecache
System File Checker Utility ( Set Cache Size to Size x ) sfc /cachesize=x
System Information msinfo32
System Properties sysdm.cpl

Task Manager taskmgr
TCP Tester tcptest
Telnet Client telnet
Tweak UI ( if installed ) tweakui

User Account Management nusrmgr.cpl
Utility Manager utilman

Volume Serial Number for C: label
Volume Control sndvol32

Windows Address Book wab
Windows Address Book Import Utility wabmig
Windows Backup Utility ( if installed ) ntbackup
Windows Explorer explorer
Windows Firewall firewall.cpl
Windows Installer Details msiexec
Windows Magnifier magnify
Windows Management Infrastructure wmimgmt.msc
Windows Media Player wmplayer
Windows Messenger msnsgs
Windows Picture Import Wizard (Need camera connected) wiaacmgr
Windows System Security Tool syskey
Windows Script host settings wscript
Widnows Update Launches wupdmgr
Windows Version ( shows your windows version ) winver
Windows XP Tour Wizard tourstart
Wordpad write

Zoom Utility igfxzoom

Java History

JDK 1.0

Codename Oak. Initial release

JDK 1.1

Major additions included:

J2SE 1.2

Codename Playground.

J2SE 1.3

Codename Kestrel. The most notable changes were:

J2SE 1.4

Codename Merlin. This was the first release of the Java platform developed under the Java Community Process as JSR 59. Major changes included:

J2SE 5.0

Codename Tiger. (Originally numbered 1.5, which is still used as the internal version number.) Developed under JSR 176, Tiger added a number of significant new language features:

  • Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). (Specified by JSR 14.)
  • Metadata: Also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.)
  • Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). (Specified by JSR 201.)
  • Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). (Specified by JSR 201.)
  • Swing: New skinnable look and feel, called synth.
  • Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
  • Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes, using a construct of the form:
            void displayWidgets (Iterable<Widget> widgets) {
for (Widget w: widgets) {
w.display();
}

This example iterates over the Iterable object widgets, assigning each of its items in turn to the variable w, and then calling the Widget method display() for each item. (Specified by JSR 201.)

  • Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory.
  • Automatic stub generation for RMI objects.
  • static imports
  • 1.5.0_18 (5u18) is the last release of Java to officially support the Microsoft Windows 9x line (Windows 95, Windows 98, Windows ME). Unofficially, Java SE 6 Update 7 (1.6.0.7) is the last version of Java to be shown working on this family of operating systems.
  • The concurrency utilities in package java.util.concurrent.
  • Scanner class for parsing data from various input streams and buffers.

J2SE 5.0 entered its end-of-life on April 8, 2008 and will be unsupported by Sun as of October 30, 2009.

Java SE 6

Codename Mustang. As of this version, Sun replaced the name "J2SE" with Java SE and dropped the ".0" from the version number. Internal numbering for developers remains 1.6.0. This version was developed under JSR 270.

During the development phase, new builds including enhancements and bug fixes were released approximately weekly. Beta versions were released in February and June 2006, leading up to a final release that occurred on December 11, 2006. The current revision is Update 16 which was released in August 2009.

Major changes included in this version:

  • Support for older Win9x versions dropped. Unofficially Java 6 Update 7 is the last release of Java shown to work on these versions of Windows. This is believed to be due to the major changes in Update 10.
  • Scripting Language Support (JSR 223): Generic API for tight integration with scripting languages, and built-in Mozilla Javascript Rhino integration
  • Dramatic performance improvements for the core platform, and Swing.
  • Improved Web Service support through JAX-WS (JSR 224)
  • JDBC 4.0 support (JSR 221).
  • Java Compiler API (JSR 199): an API allowing a Java program to select and invoke a Java Compiler programmatically.
  • Upgrade of JAXB to version 2.0: Including integration of a StAX parser.
  • Support for pluggable annotations (JSR 269)
  • Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).

Java SE 6 Update 10

Java SE 6 Update 10 (previously known as Java SE 6 Update N), while it does not change any public API, is meant as a major enhancement in terms of end-user usability. The release version is currently available for download.

Major changes for this update include:

  • Java Deployment Toolkit, a set of JavaScript functions to ease the deployment of applets and Java Web Start applications.
  • Java Kernel, a small installer including only the most commonly used JRE classes. Other packages are downloaded when needed.
  • Enhanced updater.
  • Enhanced versioning and pack200 support: server-side support is no longer required.
  • Java Quick Starter, to improve cold start-up time.
  • Improved performance of Java2D graphics primitives on Windows, using Direct3D and hardware acceleration.
  • A new Swing look and feel called Nimbus and based on synth.
  • Next-Generation Java Plug-In: applets now run in a separate process and support many features of Web Start applications.

Java SE 6 Update 12

This release includes the highly anticipated 64-bit Java Plug-In (for 64-bit browsers only), Windows Server 2008 support, and performance improvements of Java and JavaFX applications

Java SE 6 Update 14

Java SE 6 Update 14 (6u14) was released as of May 28, 2009.

This release includes extensive performance updates to the HotSpot JIT compiler, compressed pointers for 64-bit machines, as well as support for the G1 (Garbage First) low pause garbage collector.

Some developers have noticed an issue introduced in this release which causes debuggers to miss breakpoints seemingly randomly. Sun has a corresponding bug, which is tracking the issue. The workaround applies to the Client and Server VMs. Using the -XX:+UseParallelGC option will prevent the failure. Another workaround is to roll back to update 13.

Java SE 6 Update 16

As of August 11, 2009, Java SE 6 Update 16 is available, fixing the issue which caused debuggers to miss breakpoints introduced in update 14.

Java SE 7

Java 7 (codename Dolphin) is the next version of Java, currently in the planning and development stages. The Dolphin Project began in August 2006 and is tentatively scheduled for release in 2010. New builds including enhancements and bug fixes are released approximately weekly.

New features that may be integrated in Java 7 include:

  • JVM support for dynamic languages, following the prototyping work currently done on the Multi Language Virtual Machine,
  • A new library for parallel computing on Multi-core processors,
  • Superpackages (JSR 294), which are a way to define explicitly in a library or module which classes will be visible from outside of the library,
  • Swing Application Framework, an infrastructure common to most desktop applications, making Swing applications easier to create.
  • Replacing the existing concurrent low-pause garbage collector (also called CMS or Concurrent Mark-Sweep collector) with the G1 garbage collector.
  • Various small language changes, grouped in a project called Project Coin. These changes are still evaluated but could include: Strings in switch, more concise calls to constructors with type parameters, or multi-catch in exceptions.