• java
  • java

Inner classes in java

Inner classes in java



What is inner class?

Inner classes are classes defined within other classes.


Benefits of inner classes:

1. Special relationship:

An instance of inner class share with an instance of outer class, this special relationship
gives code in the inner class access the members of outer class even they are private.

2.More organizational 

 Using packages we can organize related classes. using inner classes we can provide more organizational separation.

3.Event handling

Inner classes are more useful for event handling, like button listener, text listener etc..


They are four ways you can define inner classes:

1. Inner classes

2. Method-local inner classes

3. Anonymous inner classes

4. Static nested classes

Inner classes:

This type is simple inner class, creating  class directly into another class.

Applicable modifiers for inner class is
  1. final
  2. abstract
  3. public
  4. private
  5. protected
  6. strictfp


Example:

public class OuterClass {    

   private int x=10;
       class Inner{      
              public void m1(){  

                   System.out.println("Value of outer class member :"+x);    

          }    

   }   

    public static void main(String[] args) {      
              OuterClass.Inner inner = new OuterClass().new Inner();
   //To create instance of an inner class, you must have an instance  of the outer                  class              

          inner.m1();      
       }
}Output:

Value of outer class member :10


 2.Method-Local inner classes:

Defining an inner class with in a method.

A method local inner class can instantiated only with in the method where the inner class is defined.

Inner class object cannot use the local variables of that method. it is possible only when the variable is declared as final.

Applicable modifiers for method local inner class are
  1. abstract
  2. final

Example:


public class MethodLocal {
      
       public static void m1(){
              final int x=10;
                     class class2{
                           public void m2(){
                                  System.out.println(x+"::i'm in method local inner class");
                           }
                     }
                     class2 class2=new class2();
                     class2.m2();
                    
         }
        public static void main(String[] args) {
              MethodLocal methodLocal=new MethodLocal();
              methodLocal.m1();
               
       }

}

Output:10::i'm in method local inner class

 3.Anonymous Inner class:

Anonymous class is an inner class can be declared without any name . An anonymous class has a ability to declared and initiated a class at the same time.

There are there ways you can create an anonymous inner class  

 i. Plain old anonymous inner class type-1:

In this creating anonymous inner class of the specified class type 

Example: 

 class InnerTest {

      
       public void m1(){
              System.out.println("Im parent method");
       }
       public void m2(){
              System.out.println("Im parent method2");
       }

}
public class PlainOldAnonymous{
      
       public static void main(String[] args) {

/**below code  extended  Inner test class ,m1 method is re implemented
              InnerTest plainOldAnonymous=new InnerTest(){
                     @Override
                     public void m1(){
                           System.out.println("Im child m1 method");
                     }
                    
              };
              plainOldAnonymous.m1();
              plainOldAnonymous.m2();
       }
}:


Output:
Im child m1 method
Im parent method2


 ii. Plain old anonymous inner class type-2:

In this creating anonymous inner class of the specified interface type type
Example:

interface AnonymousExample{
       public void m1();
}

public class AnonmousIntefaceType {
       public static void main(String[] args) {
              //Below line looks like creating object for interface but it's not
              //we have implemented  interface
              AnonmousIntefaceType anonmousIntefaceType=new AnonmousIntefaceType(){
                     public void m1(){
                           System.out.println("Im m1");
                     }
                    
              };
             
       }

}


 iii.  Argument-Defined Anonymous Inner Classes:

While defining arguments also you can define inner class


interface A{
       public void m1();
}


class B{
       public void test(){
       Mytest mytest=new Mytest();
       mytest.call(new A() {
              @Override
              public void m1() {
                     System.out.println(" im implemented m1");
              }
       });
       }
             
}

class Mytest{
       public void call(A a){
              System.out.println("Hai im in MYTEST");
              a.m1();
       }
}

public class ArugumentDefinedInnerClass {
      
       public static void main(String[] args) {
              B mytest=new B();
             
              mytest.test();
       }

}

Output:

Hai im in MYTESTim implemented m1


4 ) Static nested classes:

Inner classes that are declared static are called static nested classes.A static nested class is simply a class that’s a static member of outer class.

class StaticInnerClassTest {
      
       static class StaticInnerClass{
              public static void m1(){
                     System.out.println("Im in inner class method");
              }
       }

}

public class StaticTest {
       public static void main(String[] args) {
              StaticInnerClassTest.StaticInnerClass lowlevel=new StaticInnerClassTest.StaticInnerClass();
              lowlevel.m1();
             
       }
}

Output:I’m in inner class method

read more →

Multithreading interview questions

 Multithreading interview questions

 

What is multiprocessing? 

Executing multiple task simultaneously for that  operating system will create separate process
for each task.
What is a multithreading?
A multi threaded program utilizes the power of one single processor to appear to be doing more than one thing at a time,
multithreading means creating multiple thread in same process.

What is the main purpose of multithreading? 

Multithreading is the  best of utlizing cpu resources.

in multiprocessing comnication between two procees are difficult why because they

shared memory aloso different.in case of multithreading they share common memory location 

only so communication very easy.

A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads.

Example:Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.

What is daemon thread?
Daemon thread also like normal thread it also run in separate stack difference is
which will run background

Daemon threads will be terminated by the JVM when there are none of the other threads running, it includes main thread of execution as well.
example:grabage collector

we can convert normal thread to deamon thread using calling setDeamonThread(ture) on current thread;

How many ways we can create a thread?

we can create in two ways one is extending a Thread class another one is implementing Runnable interface.
best ways implementing runnable interface why because class can extends only one class if extend thread class
then that particular no chance for extends any other if you implement Runnbale interface we can extend any other class.

What is the use of threadscheduler? 

The main job of threadscheduler is it will push thread from Runnable to running state.

What is time slicing?
dividing CPU time to avillable threads.

How can we achieve thread safety in Java?


We can achive three ways
1.Using Synchronization
2.Using immutable
3.Wrapper classes
Synchronizing critical sections

Marking your code's critical sections as synchronized is the "normal" approach to making classes synchronized. It is also the only way to use wait() and notify() to get threads to cooperate towards achieving some common goal. So the guideline concerning Approach 1 is simply:

Unless special circumstances make it appropriate to use an immutable or wrapper object, use Approach 1 to make your class thread-safe: Make sure the appropriate instance variables are private and mark the critical sections as synchronized.
Using immutable objects

Achieving thread safety by making objects immutable (Approach 2) works well when objects are small and represent values of a simple abstract data type. The Java API includes several examples of immutable objects, including String and the primitive type wrappers such as Integer, Long, Float, Boolean, Character, and so on.

It's worth noting that instances of the AWT's Color class are immutable. Likewise, the immutable approach may make sense for this article's RGBColor class, which is similar in functionality to the AWT's Color class, because RGBColor objects are small (they contain only 3 ints) and conceptually represent values of a simple abstract data type.

MORE LIKE THIS
HOW-TO
Using threads with collections, Part 2
HOW-TO
Object finalization and cleanup
HOW-TO
My ENIGMAtic Java Ring
Another benefit of immutable objects is that you can pass references to them to methods without worrying that the method will change the object's state. In addition, if the overhead of immutability (excessive creation of short-lived objects) may at times be too inefficient, you can also define a mutable companion class that can be used when the immutable version isn't appropriate. An example of this design approach in the Java API is the StringBuffer class, which serves as a mutable companion to the immutable String class. Note that the StringBuffer class is also thread-safe, but it uses the "normal" approach: its instance variables are private and its critical sections are synchronized.

Using wrapper objects

The wrapper object approach to thread safety (Approach 3) makes the most sense when you want to give clients a choice between a version of a class that is thread-safe and one that isn't. This approach also makes sense when you're a client of someone else's class that isn't thread-safe, but you need to use the class in a multithreaded environment. Once you define your own thread-safe wrapper for the class, you can safely use the class in a multithreaded environment by going through your wrapper.

A good example of this approach from the Java API comes from the 1.2 collections library. The 1.2 collections library defines a hierarchy that includes classes that represent many kinds of collections -- none of which are thread-safe. But class Collection includes several class methods that will enclose a regular collection object in a thread-safe wrapper, so you can safely use the object in a multithreaded context. This design gives users of the collections library a choice of using a collections object that is thread-safe and one that isn't.





What is ThreadLocal?

Thread Local can be considered as a scope of access, like a request scope or session scope. It's a thread scope.
What is Thread Pool? How can we create Thread Pool in Java?

A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.

A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.

java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java.


Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

 public class ThreadPoolExample {

    public static void main(String args[]) {
       ExecutorService service = Executors.newFixedThreadPool(10);
       for (int i =0; i<100; i++){
           service.submit(new Task(i));
       }
    }
 
}

final class Task implements Runnable{
    private int taskId;
 
    public Task(int id){
        this.taskId = id;
    }
 
    @Override
    public void run() {
        System.out.println("Task ID : " + this.taskId +" performed by "
                           + Thread.currentThread().getName());
    }
 
}

Output:

Task ID : 1 performed by pool-1-thread-2
Task ID : 0 performed by pool-1-thread-1
Task ID : 11 performed by pool-1-thread-1
Task ID : 2 performed by pool-1-thread-3
Task ID : 13 performed by pool-1-thread-3
Task ID : 3 performed by pool-1-thread-4
Task ID : 15 performed by pool-1-thread-4
Task ID : 16 performed by pool-1-thread-4
Task ID : 17 performed by pool-1-thread-4
Task ID : 18 performed by pool-1-thread-4


What is use of synchronized keyword?

using synchronized  key word we can provide code thread safety (if its thread security is required then only use synchronization other wise it decreases the performance)
we can use synchronized keyword either method or constructor.


What is a volatile keyword?

In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread.
But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a
given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable
is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for
 reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.


Difference between green thread and native thread in Java?


Green threads" refers to a model in which the Java virtual machine itself creates, manages, and context switches all Java threads within one operating system process. No operating system threads library is used.

Native threads" refers to a in which the Java virtual machine creates and manages Java threads using the operating system threads library - named libthread on UnixWare - and each Java thread is mapped to one threads library thread.




What is context switching in multi-threading?


 
Difference between deadlock and livelock, deadlock and starvation?

live locks occurs when all threads are blocked.

starvation occurs when thread unable to access shared resource.

A deadlock occurs when thread A holds lock L and tries to acquire lock M, while thread B holds lock M and tries to acquire lock L. Thus both threads are waiting for a lock held by the other, and can not progress to release their own lock. This causes both threads to wait forever. The situation may be involving more than 2 threads as well.

 
What thread-scheduling algorithm is used in Java?

  
 
Why Executor framework is better than creating and managing thread by application ?

Using Executor framework we can create pool of threads so that we can ruse the threads.

wit out recreating.

How many ways we can stop current thread execution?

using sleep(),wait(),joing we can push thread from running to ruunable state.
and yield() aloso but its not sure first i will check based on priority.so theres is no gureenty using yield.

Why wait() and notify() methods are defined in the Object class, and not in the Thread class?


The wait (), notify () and notify all () methods are object-specific. The wait() method suspends the current thread of execution, The notify()method tells the object to wake up the suspended threads that it is currently keeping track of. Since wait(), notify() and notifyAll() are object specific, they must be used within code that is synchronized on the object. The another reason to define these method in Object class is that, locks are made available on per Object basis.

read more →

thread communication java

Thread communication java:



In java using three method wait(),notify(),notifyAll() therads can comnicate
these methods avilaible in object class.


what is the benefit of thread communication?


performance is the key  benefit of thread communication
example one thread is reading content in a file and creating object
and another thread saving those details into a database .
after creating first object only second thread need to continue if second thread every time is checking for first thread  means whether object creation done
by first thread or not? its time taking process
using this wait thread no need to check every time after first thread finish his work its invoke notify
after that second thread continues his work.
   when second thread call wait method thread its self its going to wait room until other thread(first)thread notifies.
A thread cant invoke  wait and  notify methods on an object unless it owns the object lock.
this mean these method should call from synchronized area.


How this communication happens?

Based on the object lock only.when ever we call wait method on current object
it release the lock immediately and enters into waiting state.
when ever we call notify on current thread it releases the lock but not immediately if any other
code is left in synchronized are for that particular method it completes execution of
synchronized code after that it release the lock

we can call wait method by passing time milli second after that particular time again thread enter into
runnable sate even if notify method not called also.

Example
:
package com.multi;
public class ThreadComnication extends Thread{
static int  total=0;
public static void main(String[] args) {
ThreadComnication comnication=new ThreadComnication();
comnication.setName("suri");
comnication.start();
synchronized(comnication){
try {
comnication.wait(1000);//thread release the lock and waits only one second after that again it moves to runnable state.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("");
e.printStackTrace();
}
}
System.out.println("Total---amount printing by--"+Thread.currentThread().getName()+"Thread-->"+total);
}
@Override
public void run(){
for(int i=1;i<=10;i++){
System.out.println("Total amount calculating  by "+Thread.currentThread().getName());

total=total+10;
synchronized (this) {
notify();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


Output:


Total amount caluculating  by suri
Total---amount printing by--mainThread-->10
Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri

Total amount calculating  by suri





read more →

java online exams

Best websites for java online exams:





1.Indiabix

This is the one of the best websites for writing java exams.this not only for java for other subjects also.for preparing  interviews this on of the best website .


 http://www.indiabix.com/online-test/java-programming-test/


2.TCYonline:

This also good for  writing java exams.you can post exam also url for the web site

in this website you can write exam  with your friends or if any online member  if they interested .after complete your exam you will get rank also.

http://www.tcyonline.com/


3.RankSheet:

RankSheet provides a bunch of free online exams for candidates to evaluate themselves in .Net, C#, VB, Java, PHP, My SQL, SQL Server, Oracle, HTML, Java script, OOPS, C++, Windows , Linux and more

RankSheet is just not a skill evaluation portal, candidates that qualify in the exams get 100% free certification.
Employers hire you directly from RankSheet based on your dynamic resume and your RankSheet certifications.
Participate in online assessments conducted by Companies in RankSheet.
Apply for jobs using your RankSheet account.
Follow the companies you like to work at and get notified about job openings and online assessments.
url: 


4.TECHGIG

This website not only for skill test its the best way to touch new technologies.
TechGig is a perfect platform to collaborate, innovate, recognize and celebrate the work.
url for website :

http://www.techgig.com/login.php



read more →

Java Thread Synchronization With Example

Java Thread Synchronization:












When synchronization  is required?


synchronization  is reqired when two threads are accessing same resource if you want to protect that resource the synchronization is required.


How many ways we can achieve synchronization ?


there is only two ways we can achieve 1.method level2.block level


how to achieve synchronization ?


using synchronization  key word in javasynchronized keyword was only way to provide synchronization of shared object in Java. Any code written by using  synchronized block or enclosed inside synchronized method will be mutually exclusive, and can only be executed by one thread at a time. You can have both static synchronized method and non static synchronized method and synchronized blocks in Java

How synchronization worked  in java?


synchronization  works on based on object lock mechanism.every object in java has a built in lock that only comes to play when that object has synchronization  method codewhen thread enters a synchronized non-static method,

we automatically acquire the lock associated with current instance of the class there is only one lock for object the one thread pick the lock means no other thread can't pick the lock until current thread release the lock.
using blocks with in method you can restrict some code only for synchronization  remaining code in the method can accessible for other thread using this block performance will be goodwhy because only piece code in the method only synchronized.

Difference between static synchronization  and non-static synchronization ?


static synchronization  is class level lockall instance of that particular class have only one lock
example:Student s1=new Student();
Student s2=new Student();both s1 and s2 have only one lock in class level lock in non-synchronization  in case of non-static synchronization  both s1 and s2 have different locksthat mean one thread only need to modify s1 object it not allow any other threadbut two threads can change both s1 and s2 parallel in nonstatic-synchronization  

the static method lock on Class instance while non-static method lock on this instance


*only method or block can be synchronized*each object has only one lock*a class can have both synchronization  and non-synchronization 

Consider one example raju and rani have one join account account balance is 50.and they are accessing same time what will happen?
see this example



package com.multi;
public class ProblemWithTh implements Runnable { 

Account account=new Account();

public static void main(String[] args) { 

ProblemWithTh problemWithTh=new ProblemWithTh();
Thread thread1=new Thread(problemWithTh); 

Thread thread2=new Thread(problemWithTh); thread1.setName("raju");

thread2.setName("rani");

thread1.start();

thread2.start(); 

}

@Override public  void run()

 {  

for(int i=0;i<=5;i++){  

makeWithDraw(10);  

if(account.getBalance()<0){ System.out.println("overdrwannnn"); 

}  

}  

}

private   void makeWithDraw(int i) {  

if(account.getBalance()>=i){  

System.out.println(Thread.currentThread().getName()+"::::is going to with draw current balance is"+account.getBalance()); account.withdrawl(i); 

System.out.println("::after "+Thread.currentThread().getName()+"::with drawl account balance:::::::"+account.getBalance()); 

try {

Thread.sleep(500);  

} catch (InterruptedException e) {

// TODO Auto-generated catch block e.printStackTrace(); } 

}

else{ System.out.println("no nougat money for"+Thread.currentThread().getName()); 

}  

}

}

Output:
raju::::is going to with draw current balance is50

::after raju::with drawl account balance:::::::40

rani::::is going to with draw current balance is50

::after rani::with drawl account balance:::::::30

raju::::is going to with draw current balance is30::

after raju::with drawl account balance:::::::20

rani::::is going to with draw current balance is30

::after rani::with drawl account balance:::::::10

rani::::is going to with draw current balance is10

::after rani::with drawl account balance:::::::0

raju::::is going to with draw current balance is10

::after raju::with drawl account balance:::::::-10

overdrawn

overdrawn

no enough money for rajuoverdrawnno enough money for ranioverdrawnno enough money for rajuoverdrawnno enough money for ranioverdrawnno enough money for ranioverdrawnno enoug money for rajuoverdrawn


raju and rani  using one account if one preforming  withdrawal or any other operation another thread need to wait in above example
i did n't use any synchronization that why in output after two threads are accessing simultaneously.
because of this reason after with drawl of raju for rani it displaying wrong amountrani will shock before withdrawal account  balance is 50 after withdrawal 10 balance is 30 :)

make sure that output you will not be same all time two are different. based on thread scheduler selection threads will get chance that's why out put will not be same all time.






just i added synchronized word on which method i need protect 

by accessing multiple threads.


private   synchronized void makeWithdraw(int i) {


if(account.getBalance()>=i){


System.out.println(Thread.currentThread().getName()+"::::is going to with draw current balance is"+account.getBalance()); account.withdrawl(i);  

System.out.println("::after "+Thread.currentThread().getName()+"::with drawl account balance:::::::"+account.getBalance()); try { Thread.sleep(500);

}

 catch (InterruptedException e) {

// TODO Auto-generated catch block e.printStackTrace(); }

}

else{ System.out.println("no enough money for"+Thread.currentThread().getName()); 

}  

}



output:rani::::is going to with draw current balance is50

::after rani::with drawl account balance:::::::40

rani::::is going to with draw current balance is40

::after rani::with drawl account balance:::::::30

rani::::is going to with draw current balance is30

::after rani::with drawl account balance:::::::20

raju::::is going to with draw current balance is20::

after raju::with drawl account balance:::::::10

raju::::is going to with draw current balance is10::

after raju::with drawl account balance:::::::0

no enough money for rajuno enough money for rani

no enough money for rani

no enough money for rani

no enough money for raju

no enough money for raju

no enough money for raju


problem is solved using synchronized key word it allow only one thread instance at a time
while rani withdrawal raju will wait raju withdraw rani will wait :)











read more →