Thursday 15 October 2015

Java MultiThreading Interview Question



I am publishing some interview question which asked to me(and my friends) while I am applying for new change with java profile.

            Right now I am adding only question will add ans in time to time.

 
Multi threading :  

1.   What is context switching in multi-threading?  

Ans . Switching context from one thread to another thread is called context switching. Mostly OS uses round robin preempted mechanism for context switching.
Context switching should not be very frequently, it may degrade performance, because it will waste more time in switching context instead doing actual processing in threads


 2. Difference between deadlock and livelock,  starvation?

DeadLock - It’s situation where one thread waiting for a resource that is locked by other resources.

Livelock -  Scenario is same like deadlock but the basic difference is that in this case both thread pretend to solve deadlock issue . Eg two mens stuck in tunnel in which at one time only one can pass.

Starvation - Starvation is case where one thread get neglected by thread manager 


3. What thread-scheduling algorithm is used in Java?

Java does not its own scheduling algorithm, it uses underlying operating system thread scheduling algorithms. Operating system uses Round Robin scheduling , Preemptive strategy for scheduling threads 


4. What is thread-scheduler in Java?
    Thread scheduler is part of OS which which mainly control thread execution.
    There is no guarantee that which runnable thread will be chosen to run by thread schedule.


 5. How do you handle unhandled exception in thread?

Ans : To handle unhandled exception we need to add own uncaughtExceptionHandler.
If we haven't implemented any handler then it will throw exception like below
                Exception in thread "Thread-0" java.lang.RuntimeException at Main$1.run(Main.java:11) at java.lang.Thread.run(Thread.java:619)

Thread t = new Thread(new Runnable()
 {
   public void run()
    {
      throw new RuntimeException();
 } });
 t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {   
  public void uncaughtException(Thread t, Throwable e)
 {
        System.out.println("exception " + e + " from thread " + t);
} });  
     t.start();


To set handler for all threads use a static method Thread.setDefaultUncaughtExceptionHandler.

6. What is thread-group, why it's advised not to use thread-group in Java? 

Ans. When you want to execute bunch of thread at once rather than individual then Thread group comes handy.
It’s provide a mechanism for collecting multiple threads into a single object .


The runtime system puts a thread into a thread group during thread construction.


-you cannot move a thread to a new group after the thread has been created


public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable target, String name)


Example ::
ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads");
Thread myThread = new Thread(myThreadGroup, "a thread for my group");

7. Why Executor framework is better than creating and managing thread by application
 
8.  Difference between Executor and Executors in Java?
  
9. How to find which thread is taking maximum cpu in windows and Linux server?.

10. What is ThreadLocal class used for ?
Ans. It’s  alternative way to get ThreadSafety in java. It’s eliminate synchronization requirement by sharing explicit copy of object to each thread



11.
How will you design your own custom thread pool in Java ? Don't use the One provided by JDK ?


 Ans. Need to follow below steps. 
 
1)-  Take variable blockingQueue (To save task).
2)- variable like list of type thread
3)- Boolean to check status of thread
4)- Create parameterized constructor   with value of task and thread
5)- Create Enque and Deque Method for same
 

12. Why wait, sleep, notify and notifyAll methods are in Object class not in Thread class?

13. Implement runnable functionality for your own.
14. If any thread have class level locking as well as instance level locking then both are mutually exclusive or not ?

15 what is difference between yield() and joins().

16. What are the thread state.

17. Best way to handle exception thrown by Callable in multi threading?
18. Difference between Countdown Latch and Countdown Barrier.  

19.Sleep VS wait?
  
20. How do you make a class synchronized ?

21. Best way to handle exception using callable? 

22. Implement BlockingQueue to solve producer consumer problem ?

23. Implementation of countDownLatch?

  
 

Java Collection and DataStructure Interview Questions







1. What is the strategy to handle ConcurrentModificationException in your Java program.

2. How hashmap identify index for element to insert?

3. What is  default size of bucket in hashmap? and formula of rehash size?
4. Comparable VS Comparator
5. Write Comparator for employee class having id and name?
6. ArrayList VS LinkedList
7. Can we add null to TreeSet? if No why?

8.
   ArrayList<String> s = new ArrayList<String>(); 
   ArrayList<Integer> s1 = new ArrayList<Integer>();

    System.out.println(s1.equals(s));

why ans is always equals
 

9. Implement own linked list.

10. Implement own linked list.

11. What is the difference between HashMap and Synchronized map.

12. how does blocking queue works? 

13. Which collection  should use where you keep elements like list. With out using AL or LL ? 

14. How to write your own doubly link list? How do you handle boundary conditions? 

15. Why java have “for loop”, foreach loop, iterator and ListIterator for traversing ArrayList,
  List out difference between them and give valid reason what you prefer.


Ans
 for loop - Good to traversing Arraylist only, If you are not sure underlying data structure do not use for loop for traversing as for linked list N^2 time complexity
For Each Loop - can call methods of element

Iterator : 
// 1 - can call methods of element // 2 - can use iter.remove() to remove the current element from the list

ListIterator :
// 1 - can call methods of element // 2 - can use iter.remove() to remove the current element from the list // 3 - can use iter.add(...) to insert a new element into the list // between element and iter->next() // 4 - can use iter.set(...) to replace the current element




16. What will be behavior of a Java Program where infinite recursion takes place with limited Stack memory ? Does the program complete or Stackoverflow exception is thrown ?

17. How to handle multiple request using concurrency utilities?
 

Web Service interview In java



1. How you can return attachment of file as soap response.
2. How you can encrypt information of soap response.
3. why soap why not rest
4. How do u handle security in web service.
5. how you can store shared  httpseession
6. what version you used  of rest and soap web service
7. what authentication mechanism you used im rest and soap
8. can you send file via rest

Spring , Struts and hibernate Question



Spring ::


1)- How Spring Transaction Works
2)- Spring MVC architecture.
3)- Internal implementation of bean factory
4)- how DI work and why it comes in picture
5)- What is global session
6)- Autowiring by name, type?
7)- Spring bean scopes?
8)- which design pattern is spring based on ?
9)- Can a JSP be used as controllor in MVC architecture ? If NO, why ?
10)-How does Spring AOP works?
11)- Autowiring types and their differences
12)- how many instance will be created if we declare two different bean id pointing to same class
13)- If a bean is singleton in spring does it produce a new instance if I use that with new operator in plain java file
14)- how will u ensure that there is no any circular dependency
15)-Which proxy used by Spring

Struts ::

1. Explain struts architecture
2. how to implement own interceptor
3. How param interceptor works in struts?
4. How to get form values from client in our action class in struts?
5. What is TokenInterceptor in struts and how it works internally, where it keeps tokens?
6. How you can migrate struts1.2 to struts 2.
7.  How interceptor and actioninvocation works with each other
8.  how do u handle transaction ?difference between require new and nested

Hibernate ::

1. how connection pool works , if you have created pool with size 10 and in your system 15 user comes concurrent. So how it handle.

2. Different Type of Interface in Hibernate.

3.What is transaction.

4. session.save() VS session.persistent();
5.  session.update() VS session.merge().
6. How to create alias in hibernate?
7. How cache works in hibernate(first and second level).
8.
<bean id="student" class="com.example.model.Student" scope="singalton">
        <property name="address">
            <bean class="com.example.model.Address" scope="prototype">
                <property name="address" value="Noida K-Block" />
            </bean>
        </property>
        </bean>
       b. <bean id="student" class="com.example.model.Student" scope="prototype">
        <property name="address">
            <bean class="com.example.model.Address" scope="singalton">
                <property name="address" value="Noida K-Block" />
            </bean>
        </property>
        </bean>

what is difference between a and b?

9. lazy loading and inverse true work in hibernate.

10. What is two phase commit.
11. what are the elements in hibernate xml.
12. explain hib inheritence till db layer
13.Write criteria query to fetch only 3 columns from table like if we have table with column name     
       transId, transName, StuId, StuName, EnrollId, EnollName.
From above 6 column I need to fetch only transId, StuId and EnrollId using criteria.


Projection API is used to fetch any number of columns from table.

Criteria criteria = session.createCriteria(UserInfo.class);
    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.property("firstName"), "firstName");
    proList.add(Projections.property("lastName"), "lastName");
    criteria.setProjection(proList);
    criteria.list(),

will return list of objects with only two columns.
we can transfer this result to our Custom object using transformation like:
List<UserDTO> list = criteria.setResultTransformer(Transformers.aliasToBean(UserDTO.class))
      .list();
UserTDO is custom object with firstName and lastName properties and their getter setter.


ProjectionList is necessary when we want to get multiple column. We can add Projections directly to criteria but if we add two Projections without  ProjectionList it will override previously added Projection and only one last added projection will be applied.
NOTE: one more important thing if we want to transform result to our Custom object the second parameter on ProjectionList’s add method should be same as the property name in custom object, otherwise it is not required.

puzzles and Use Case





1)-  puzzle- 3 heads 5 hats 2 black and 3 white
    They all stand in line like 3 can see both 2 can see 1 and 1 can see wall, 3rd one is saying that he know what color of hat he have , You need to figure out he is true or bluff,
They can't touch them self or talk

2)- Write a program to list all files which have name started with ‘a’ and ends with ‘txt’
i. There should be a flag to on/off recursive search.
ii. There should be specific timeout in seconds and program should stop searching            after timeout.
iii. Write junit test cases for testing the program.


3)- String s = “helloasgjhshellohjhsd9helloghsaghhello”;
    calculate how many times “hello” is present in s?

Write a program for finding largest palindrome from a string pattern.

4)- A puzzle was asked “we have a car which had 5 tyres(4 in use and 1 spare). The car had traveled 20,000 miles and all of its tyres has covered equal amount of distance and all the tyres has reached their maximum limit and thus all are busted. What is the maximum limit of each tyre ”.


5)- Write a code for stack using linked list(when writing any code keep the boundary conditions in mind)


6)- Write a high performance file search utility program . You are required to write a program that takes command line arguments and searches the required file in the current folder and the sub folders . Search could be for files or folders or both . Below are the four parameters that would be passed . You are also required to so proper exception handling and you code must be optimized as much as possible .

1) A top folder name : Folder from where search would begin. (Ex : C:/MyFolder )

2) Search Option (File /Folder /Both )

3) Search Pattern : A regular expression : (*my*.txt )

4) Timeout in seconds : once the operation reaches this timeout search should be stopped saying " Could not complete operation " and results obtained till then must be returned .

7)-  Write a program to verify that any given  String having perfect open and close bracket

like String temp = “{fgfgfgfgfg(ffgfg)fgfgfg(fgfgfg}fgfgfg)fgfgfgfg[fgfgfgf]fgfgfggfgfg]gfgfg”;

8)- Remove number at odd position in an array of 10 numbers.



9)- Implement Binary Tree with using any class like node.


10)- how to remove duplicate words from a large file?


11)-
Write code for : two strings are given ,find out if first string is subsequence of other string
like : frstString ="AXY",secString="ADXCPY"
output wil be :true frstString is subsequence of other String

Big Data General Errors and Fix





Issue A)- Incompatible clusterIDs in Hadoop :  Some time you get below error in your logs , in this case you will not find datanode as running instance.

Error Stack - Incompatible clusterIDs in /usr/local/hadoop_store/hdfs/datanode: namenode clusterID = CID-52c3b330-d913-461d-8a5a-03c1659390bd; datanode clusterID = CID-bfea0588-2680-43cb-aa69-d5464168ca88
    at org.apache.hadoop.hdfs.server.datanode.DataStorage.doTransition(DataStorage.java:646)
    at org.apache.hadoop.hdfs.server.datanode.DataStorage.addStorageLocations(DataStorage.java:320)


                                                           Fix : 
ClusterIDs of datanodes and namenodes should match, then only can datanodes communicate with namenode. 

When first time you run your hadoop instance (using start-all.sh or other way) you can see datanode is in running state, but after that if you format your name node then  new ClusterID will be assigned for namenodes  and ClusterIDs in datanodes won't match.

You can locate a VERSION files in your /usr/local/hadoop_store/hdfs/datanode/current/ (datanode directory ).

You can fix above issue by two way

1)-  If you dont want to delete data of datanode then go to  /usr/local/hadoop_store/hdfs/datanode/current/  open version file and update clusterID value with updated one (as mention in error trace).

2)- If you are not ok with above apporoach you can execute below commands to generate new clusterId.

   a)- Stop all HDFS services.
   b)- rm -rf /usr/local/hadoop_store/hdfs/datanode/* 
   c)- rm -rf /usr/local/hadoop_store/hdfs/namenode/*
   d)-format hdfs again (hadoop namenode -format )


Issue B)- java.lang.IncompatibleClassChangeError: Found class jline.Terminal, but interface was expected .


                                          Fix : 
  a)- Open profile file(or any file where you stored path info of hive) -> sudo nano /etc/profile
  b)- add line at bottom of file -> export HADOOP_USER_CLASSPATH_FIRST=true
  c)- execute command -> source /etc/profile
  d)- type hive and hit Enter.

Now it should working fine and you able to see hive pointer. like
hive>

Issue C)- Exception in thread "main" java.lang.RuntimeException: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: ${system:java.io.tmpdir%7D/$%7Bsystem:user.name%7D


                                        Fix :
1)- execute command -> sudo nano hive-site.xml
2)- update below highlighted 3 property value with your created directory

<property>
<name>hive.exec.scratchdir</name>
    <value>/usr/local/hive_data</value>
    <description>HDFS root scratch dir for Hive jobs which gets created with write all (733) permission. For each connecting user, an HDFS scratch dir: ${hive.exec.scratchdir}/&lt;username&gt; is created,$
</property>

<property>
    <name>hive.exec.local.scratchdir</name>
    <value>/usr/local/hive_data</value>
    <description>Local scratch space for Hive jobs</description>
</property>

<property>
    <name>hive.downloaded.resources.dir</name>
    <value>/usr/local/hive_data/${hive.session.id}_resources</value>
    <description>Temporary local directory for added resources in the remote file system.</description>
</property> 

this will solve your above exception, 



Issue D)- java.io.IOException: Unable to initialize any output collector.
 at org.apache.hadoop.mapred.MapTask.createSortingCollector(MapTask.java:412)
at org.apache.hadoop.mapred.MapTask.access$100(MapTask.java:81)
at org.apache.hadoop.mapred.MapTask$NewOutputCollector.<init>(MapTask.java:695)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:767)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158).


To fix this issue you can do two things,

a)- Increase io.sort.mb value
<property> <name>io.sort.mb</name> <value>800</value> </property>

b)- Go to you userlogs and check syslog of all created folder, As in several cases(like in my case there are some issue with the program that cause above issue to me)


Thanks :)