Tuesday 31 January 2012

Thread.yield() in Java Thread

The Thread.yield() method is essentially used to notify the system that the current thread is willing to "give up the CPU" for a while. The thread scheduler may select another runnable thread with the same or greater priority to run instead of the current thread.

What yield() is supposed to do is make the currently running thread move back to runnable to allow other threads of the same priority(and those of greater priority) to get their turn.

So the intention to use yield() is that equally distribute the CPU time among equal-priority threads.But there is no guarantee for that ,because the yielding thread itself may be selected to run again.i.e the yielding thread is eligible to compete with other equal-priority threads for CPU time.

A yield() won't ever cause a thread to go to the waiting/sleeping/ blocking
state. At most, a yield() will cause a thread to go from running to runnable, but
again, it might have no effect at all.

Sunday 29 January 2012

join() method in Java Thread with Examples

The join() method of a Thread instance can be used to "join" the start of a thread's execution to the end of another thread's execution so that a thread will not start running until another thread has ended. If join() is called on a Thread instance t, the currently running thread will block until the thread instance t has finished execution. 
See one example 
class MyThread extends Thread {

    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("From mythread i=" + i);
        }
    }
}

public class Main {
    public static void main(String args[]) {
        MyThread mythread = new MyThread();
        System.out.println("Before starting mythread");

        mythread.start();
        try {
            mythread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Thread.sleep() method in Java with Examples

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Thread.sleep() sends the current thread into the "
Not Runnable" state for a specified amount of time.Also,if another thread calls t.interrupt(), it will wake up the sleeping thread.

sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method).It is a common mistake to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

One thread can't make sleep another thread t using t.sleep method.Only the current thread which is executing the statement 't.sleep' will go for sleep.

Sleep doesn’t cause the thread to lose ownership of the acquired monitors.The thread keeps the monitors it has acquired i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method.

Thread.sleep method is available in two different formats as given below

Uses of Thread.sleep() in Java with Examples


Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

Thread.sleep can also be used to implement some graphical functionalities i.e.to make some delay in displaying some texts,frames,windows etc.

Consider one real-time scenario, you and your friend has got a box of apples,both of you are started to eat apples.Suppose you can eat more fast than your friend,what will happen ?.Your friend won't get enough apples.

This situation is called 'Starvation' in Computer Science,where some threads won't get enough CPU time compared to some other concurrent threads.See the code given below


Saturday 28 January 2012

Inter Thread Communication in Java with Example

I hope you have gone through  my previous post  Inter-Thread Communications in Java  before reading it.

We have a classic 'Producer-Consumer' problem to explain the use of Inter-Thread communications in java,where one thread is producing some data and another is consuming it .The producer has to wait until the consumer is finished before it generates more data.

Let us start with an incorrect implementation of  Producer-Consumer problem, where we are just using the mercy of synchronized method .


// An incorrect implementation of a producer and consumer.
class Q {
    int n;

    synchronized int get() {
        System.out.println("Got: " + n);
        return n;
    }

    synchronized void put(int n) {
        this.n = n;
        System.out.println("Put: " + n);
    }
}

Friday 27 January 2012

wait(), notify() and notifyAll() -Inter Thread Communications in java


Let us take a real-time scenario ,What is the use of  message alert in your mobile phone ?? .The answer is very simple ,once you get a message alert ,you can go and check your mail box and read the message.Suppose that your mobile is not providing message alert facility ,then what is the problem?.
You have to check your mailbox frequently to see a new message ,and it consumes a lot of time.This is nothing but ,polling in Computer Science.

Polling refers to the situation where one or more threads repeatedly checking one condition for performing some actions.Polling is usually implemented by a loop that is used to check some condition repeatedly.Once the condition is true, appropriate action is taken. This wastes CPU time.


 For example, consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable.

Thursday 26 January 2012

Final Reference Variables in Java

If the final variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.See the example given below


class Rectangle {
Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
int length;
int breadth;
}
public class Main {
public static void main(String[] args) {
final Rectangle rect = new Rectangle(10, 5);
rect.length = 20; //Valid,can change the state of object
rect.breadth = 10; //Valid,can change the state of object
rect = new Rectangle(30, 20);// Invalid,final variable can't be reassigned.

}
}
Please listen one point that


final != immutable object

Blank Final Variables in Java

The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initialization. A blank final must be initialized at run-time and that value remains throughout the life-time of variable.Both the static and non static variables can be declared as blank final variable.

static blank final variable


All the static blank final variables should be initialized within a static block.Example given below

class StaticBlankFianl{
final static int X;
static{
X=10;
}
public static void main(String args[]){
X=20;//Wrong !! .Once assigned we cant change value of a static blank variable
}
}
Here when the class loads ,the static block will be executed and it initializes the blank final X.

non-static blank final variable


Here all the declared blank final variables  should be initialized within at-least one constructor and within all other overloaded constructors..See the example

Compile Time Constants in Java

Compile Time Constant means at the time of compilation itself ,the compiler can understands the value of a final variable and acts as 'literal' value.So it will reduce some run-time overhead.General rules for a compile time constants are 
  • They must be declared final
  • They are of primitive data types or String
  • They must be initialized with their declaration.
  • Their value must be constant expression.

Final variables of primitive data types and Strings can be compile time constants. No other type of variables are compile time constants, not even the wrapper classes. They must also be initialized with their declaration, otherwise they’ll not be compile time constants. Lets take a few examples. 

All of the following are compile time constants,

class CompileTimeConstant{
final float PI=3.14f;
final String NATIONALITY="Indian";
final int X=10;
final int Y=20;
final int Z=X+Y;
final int S="Hello"+"World";
}

Monday 23 January 2012

Difference Between volatile and synchronized in Java

Before discussing the difference between volatile and synchronized we have to know a little about java memory model,if one instance or static variable is shared among multiple threads,how it is stored in memory.Consider one example

class Counter
{
static int count;

static void setCount(int cnt){
count=cnt;
}
static int getCount(){
return count;
}}

Two threads thread1 and thread2 are sharing this Counter.count variable.
Both threads have a working copy(i.e cache) of this count variable ,initial value of this local copy gets from original counter variable stored in main memory .The local working copy of count variable will re-sync with the original count variable at a particular interval of time. i.e.

Saturday 21 January 2012

Synchronized method in Java with Example

Suppose a single thread wants to run a set of statements as a single unit (atomic action) and some other thread trying to disturb it by executing that same set of statements.Can you guess what will be the result??

See the example given below.Here one thread trying to print a statement [Hello] ,simultaneously another thread also trying to do the same thing.Will it work correctly??.Let us check.


public class Main {

public static void main(String[] args) {
MyResource resource = new MyResource();
MyThread t1 = new MyThread(resource);
MyThread t2 = new MyThread(resource);
t1.start();
t2.start();
}
}

class MyThread extends Thread {
MyResource resource;

public MyThread(MyResource resource) {
this.resource = resource;
}

public void run() {
try {
resource.display();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Thursday 19 January 2012

java.lang.Thread Objective Questions

1)
class Main implements Runnable {
    public void run() {
        System.out.println("thread");
    }

    public static void main(String args[]) {
        Main m = new Main();
        m.start();
    }
}
// What is the result of attempting to compile and run the program?

  1. Prints thread
  2. Prints Nothing
  3. Compile-time error
  4. Run-time error
Answer:Compile-time error.

start() method is declared with in java.lang.Thread class.So here to start the thread use following
Thread t=new Thread(m);
m.start();
It will start a new thread and prints the message 'thread'.

Monday 16 January 2012

Static Variable(Class Variable) and Static Method(Class Method) In Java

Static Variable or Class Variable

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Student class, the instance variables are rollno, name, and dept. Each Student object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Student objects and assign each a roll number. This rollno is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Student objects have been created . Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfStudents, as follows:

Saturday 14 January 2012

Access Modifiers In Java

There are four access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no access modifier is specified.
Access Modifiers
1. private
2. protected
3. default (friendly or package-private)
4. public
Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

Class level access modifiers (java classes only)


It is used to control the visibility of classes between packages.We can use the following access modifiers for class level access.
  • default (friendly or package-private)
  • public
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).

Thursday 12 January 2012

Overridding Method Rules in Java


The rules for overriding a method are as follows: 
 
1) The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method you didn't intend.

Example :
 class Base{
public void add(int x,int y){
}
}
class Sub extends Base{
public void add(float x,float y){
}
}
Where Sub class overloads the add(int,int) method.If you want to override the Base class add(int,int) method declare the method as given below.

class Sub extends Base{
public void add(int x,int y){
}
}

Monday 9 January 2012

Java ClassLoader and Usage of Custom ClassLoader

The Java Classloader is a part of Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually classes are only loaded on demand(lazy loading).i.e. There are exactly two cases: When the first instance of the class is created (MyClass cl=new MyClass()) and static reference to a class is made (System.out.).
The class loader is responsible for locating libraries, reading their contents, and loading the classes contained within the libraries. This loading is typically done "on demand", in that it does not occur until the class is actually used by the program. There is a few difference to get the first class running (which is why you have to declare the main() method as static, taking a string array as an argument), but once that class is running, future attempts at loading classes are done by the class loader.

A class with a given name can only be loaded once by a given classloader(Note: possible with custom class loader .Will discuss later) .
Each Java class must be loaded by a class loader. Furthermore, Java programs may make use of external libraries (that is, libraries written and provided by someone other than the author of the program) or they may be composed, at least in part, of a number of libraries.
When the JVM is started, three class loaders are used :
  1. Bootstrap class loader
  2. Extensions class loader
  3. System class loader

Sunday 8 January 2012

Java Custom ClassLoader Example

Let us discuss how to load multiple versions of a class into a single JVM using custom classloader.

Once a class is loaded into a JVM, the same class (I repeat, the same class) will not be loaded again. This leads to the question of what is meant by "the same class." Similar to the condition that an object has a specific state, an identity, and that an object is always associated with its code (class), a class loaded into a JVM also has a specific identity, which we'll look at now.

In Java, a class is identified by its fully qualified class name. The fully qualified class name consists of the package name and the class name. But a class is uniquely identified in a JVM using its fully qualified class name along with the instance of the ClassLoader that loaded the class. Thus, if a class named Cl in the package Pg is loaded by an instance kl1 of the class loader KlassLoader, the class instance of C1, i.e. C1.class is keyed in the JVM as (Cl, Pg, kl1). This means that the two class loader instances (Cl, Pg, kl1) and (Cl, Pg, kl2) are not one and the same, and classes loaded by them are also completely different and not type-compatible to each other.

Thursday 5 January 2012

Java Classpath & How to Set Classpath in Java


In Java the compiler and JVM uses the classpath to locate classes when they are referenced by other Java code.Compiler and JVM identifies the location of these classes using the -classpath option on the javac command line or by using the CLASSPATH environment variable.

Class paths can be set to the .jar, .zip or .class files. Each classpath should end with a filename or directory depending on what you are setting the class path to:
  • For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file.
  • For .class files in an unnamed package, the class path ends with the directory that contains the .class files.
  • For .class files in a named package, the class path ends with the directory that contains the "root" package (the first package in the full package name).
The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.

Sunday 1 January 2012

Java Objective Questions -Packages and Access Controls

1 )
// Class A is declared in a file named A.java.
package com.dan.chisholm;
public class A {
  public void m1() {System.out.print("A.m1, ");}
  private void m2() {System.out.print("A.m2, ");}
  }
// Class D is declared in a file named D.java.
package com.dan.chisholm.other;
import com.dan.chisholm.A;
public class D {
  public static void main(String[] args) {
    A a = new A();
    a.m1();  // 1
    a.m2();  // 2
    }}
What is the result of attempting to compile and run the program? 
    • Prints: A.m1, A.m2,
    • Compile-time error at 1
    • Compile-time error at 2
    • None of the above