Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 1 July 2013

Java Threading interview queations

This topic is the fecto for clearing any java investment banking jobs. There are few java interviews where they ask most of questions from this topic. This topic become synonyms for how much knowledge you have in java. No interviewer takes a chance that candidate will not be aware of threading and caondidate is not able to resolve threading issue. I will say it is better to do same example coding and practice this topic.
  
Here is presentation on Java threading, providing details on Java Threading concept.

Java Threading presentation

Interview Questions:-
  1. What is synchronization in respect to multi-threading?
    With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
  2. Explain different way of using thread?
    The thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.
  3. What is the difference between Thread.start() & Thread.run() method?
    Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.
  4. Why do we need run() & start() method both. Can we achieve it with only run method?
    We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called.
    Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.
  5. What is ThreadLocal class? How can it be used?
    - A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
    - ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread

    - In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
    - Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)

    Good article on ThreadLocal: http://www-128.ibm.com/developerworks/java/library/j-threads3.html

    Good example : http://javaboutique.internet.com/tutorials/localdata/

    Multithreading in Swing: http://java.sun.com/developer/JDCTechTips/2003/tt1208.html

    Refer API Docs:http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html
       
  6. When InvalidMonitorStateException is thrown? Why?

    This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll())

    wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
  7. What is the difference between sleep(), suspend() and wait() ?

    Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the
    sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

    t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.

    object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original,
    waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
  8. What happens when I make a static method as synchronized?

    Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.
  9. Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?

    Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized.
    Below is the example which demonstrates this, The Common class has two methods
    synchronizedMethod1() and method1()
    MyThread class is calling both the methods in separate threads,
                  1.  public class Common {
2.   
3.  public synchronized void synchronizedMethod1() {
4.  System.out.println("synchronizedMethod1 called");
5.  try {
6.  Thread.sleep(1000);
7.  } catch (InterruptedException e) {
8.  e.printStackTrace();
9.  }
10. System.out.println("synchronizedMethod1 done");
11. }
12. public void method1() {
13. System.out.println("Method 1 called");
14. try {
15. Thread.sleep(1000);
16. } catch (InterruptedException e) {
17. e.printStackTrace();
18. }
19. System.out.println("Method 1 done");
20. }
21. }
1.  public class MyThread extends Thread {
2.  private int id = 0;
3.  private Common common;
4.   
5.  public MyThread(String name, int no, Common object) {
6.  super(name);
7.  common = object;
8.  id = no;
9.  }
10.  
11. public void run() {
12. System.out.println("Running Thread" + this.getName());
13. try {
14. if (id == 0) {
15. common.synchronizedMethod1();
16. } else {
17. common.method1();
18. }
19. } catch (Exception e) {
20. e.printStackTrace();
21. }
22. }
23.  
24. public static void main(String[] args) {
25. Common c = new Common();
26. MyThread t1 = new MyThread("MyThread-1", 0, c);
27. MyThread t2 = new MyThread("MyThread-2", 1, c);
28. t1.start();
29. t2.start();
30. }
31. }
public class O
OutPut-->
1.  Running ThreadMyThread-1
2.  synchronizedMethod1 called
3.  Running ThreadMyThread-2
4.  Method 1 called
5.  synchronizedMethod1 done
6.  Method 1 done
This shows that method1() - is called even though the synchronizedMethod1() was in execution.
10. Can two threads call two different synchronized instance methods of an Object?
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods.
1.  public class Common {
2.  public synchronized void synchronizedMethod1() {
3.  System.out.println("synchronizedMethod1 called");
4.  try {
5.  Thread.sleep(1000);
6.  } catch (InterruptedException e) {
7.  e.printStackTrace();
8.  }
9.  System.out.println("synchronizedMethod1 done");
10. }
11.  
12. public synchronized void synchronizedMethod2() {
13. System.out.println("synchronizedMethod2 called");
14. try {
15. Thread.sleep(1000);
16. } catch (InterruptedException e) {
17. e.printStackTrace();
18. }
19. System.out.println("synchronizedMethod2 done");
20. }
21. }
 -----------------------------------
23. public class MyThread extends Thread {
24. private int id = 0;
25. private Common common;
26.   
27. public MyThread(String name, int no, Common object) {
28. super(name);
29. common = object;
30. id = no;
31. }
32.  
33. public void run() {
34. System.out.println("Running Thread" + this.getName());
35. try {
36. if (id == 0) {
37. common.synchronizedMethod1();
38. } else {
39. common.synchronizedMethod2();
40. }
41. } catch (Exception e) {
42. e.printStackTrace();
43. }
44. }
45.  
46. public static void main(String[] args) {
47. Common c = new Common();
48. MyThread t1 = new MyThread("MyThread-1", 0, c);
49. MyThread t2 = new MyThread("MyThread-2", 1, c);
50. t1.start();
51. t2.start();
52. }
53. }
11. What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:
o    When two threads call Thread.join() on each other.
o    When two threads use nested synchronized blocks to lock two objects and the blocks lockthe same objects in different order.

          12. What is Starvation? and What is a Livelock?

Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
LiveLock
Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:

o    When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
o    When all the threads in a program are stuck in infinite loops.
Starvation
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.
Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...