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.