Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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.

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.

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