Thursday, May 23, 2013

Vector vs ArrayList in Java

http://javarevisited.blogspot.kr/2011/09/difference-vector-vs-arraylist-in-java.html


ArrayList and Vectorare two of most used class on java collection package and difference between Vector and ArrayList is one of the most frequently asked java interview question on first round or phone interview. Though it’s quite a simple question in my opinion but knowledge of when to use Vector over ArrayList or does matter if you are working on a project. In this article we will some point based difference between Vector and ArrayList in Java and trying to understand the concept behind those differences. Ultimate goal is to familiarize yourself with distinguish property of ArrayList and Vector. By the way Java 5 adds another implementation of List interface which is similar to Vector and ArrayList but provides better concurrency access than Vector, its called CopyOnWriteArrayList. By the way this is the third article on discussing about Collection interview question, Difference between LinkedList and ArrayList and List vs Set are other popular interview questions based upon collection framework in Java.


Before seeing differences between Vector and ArrayList, let's see some similarities between these two and why we can use ArrayList in place of Vector on certain scenario.

ArrayList vs Vector in Java1) Vector and ArrayListare index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
3) Both Iterator and ListIterator returned by ArrayList and Vector are fail-fast.
4) ArrayList and Vector also allows null and duplicates.


Vector vs ArrayList in Java

Now let's see some key difference between Vector and ArrayList in Java, this will decide when is the right time to use Vector over ArrayList and vice-versa. Differences are based upon properties like synchronization, thread safety, speed, performance , navigation and Iteration over List etc.

1) Synchronization and thread-safety

First and foremost difference between Vector and ArrayList is that Vector is synchronized and ArrayList is not, what it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which makes it thread-safe and allows it to be used safely in a multi-threaded and concurrent environment. On the other hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment. This is also a popular interview question on thread, where people ask why ArrayList can not be shared between multiple threads.

2) Speed and Performance

ArrayList is way faster than Vector. Since Vector is synchronized and thread-safe it pays price of synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes it obvious choice in a single-threaded access environment. You can also use ArrayList in a multi-threaded environment if multiple threads are only reading values from ArrayList or you can create read only ArrayList as well.

3) Capacity

Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.

4) Enumeration and Iterator

Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to Iterator and ListIterator returned by ArrayList. I have discussed this point in detail on my post What is difference between Iterator and Enumeration, you can also look there.

5) Legacy

Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to implement List interface so that it could become part of collection framework

After considering these points about both Vector and ArrayList , my conclusion is use ArrayList wherever possible and avoids use of Vector until you have no choice. Think for CopyOnWriteArrayList over Vector, if you have multiple readers and few writers because it can provide thread-safety without impacting performance too much.


Read more: http://javarevisited.blogspot.com/2011/09/difference-vector-vs-arraylist-in-java.html#ixzz2Tf6PZouD

HowTo: ListView, Adapter, getView and different list items’ layouts in one ListView

http://android.amberfog.com/?p=296


I was surprised that getViewTypeCount() is so rarely overrided (codesearch). If you are an expert in this – this post is not for you:-)

ListView and Adapter Basics

How it works:
  1. ListView asks adapter “give me a view” (getView) for each item of the list
  2. A new View is returned and displayed
Next question – what if we have one billion items? Create new view for each item? The answer is NO:-) Android caches views for you.
There’s a component in Android called “Recycler”. I drawed a picture based on Romain Guy presentation at Google IO ’09.
  1. If you have 1 billion items – there are only visible items in the memory + view in recycler.
  2. ListView asks for a view type1 first time (getView) x visible items. convertView is null in getView – you create new view of type1 and return it.
  3. ListView asks for a view type1 when one item1 is outside of the window and new item the same type is comming from the bottom. convertView is not null = item1. You should just set new data and return convertView back. No need to create view again.
Let’s write a simple code and put System.out to the getView:

public class MultipleItemsList extends ListActivity {
 
    private MyCustomAdapter mAdapter;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new MyCustomAdapter();
        for (int i = 0; i < 50; i++) {
            mAdapter.addItem("item " + i);
        }
        setListAdapter(mAdapter);
    }
 
    private class MyCustomAdapter extends BaseAdapter {
 
        private ArrayList mData = new ArrayList();
        private LayoutInflater mInflater;
 
        public MyCustomAdapter() {
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
 
        public void addItem(final String item) {
            mData.add(item);
            notifyDataSetChanged();
        }
 
        @Override
        public int getCount() {
            return mData.size();
        }
 
        @Override
        public String getItem(int position) {
            return mData.get(position);
        }
 
        @Override
        public long getItemId(int position) {
            return position;
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            System.out.println("getView " + position + " " + convertView);
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item1, null);
                holder = new ViewHolder();
                holder.textView = (TextView)convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.textView.setText(mData.get(position));
            return convertView;
        }
 
    }
 
    public static class ViewHolder {
        public TextView textView;
    }
}
Run the program and see what happens:
getView was called 9 times. convertView is null for all visible items
02-05 13:47:32.559: INFO/System.out(947): getView 0 null
02-05 13:47:32.570: INFO/System.out(947): getView 1 null
02-05 13:47:32.589: INFO/System.out(947): getView 2 null
02-05 13:47:32.599: INFO/System.out(947): getView 3 null
02-05 13:47:32.619: INFO/System.out(947): getView 4 null
02-05 13:47:32.629: INFO/System.out(947): getView 5 null
02-05 13:47:32.708: INFO/System.out(947): getView 6 null
02-05 13:47:32.719: INFO/System.out(947): getView 7 null
02-05 13:47:32.729: INFO/System.out(947): getView 8 null
Then scroll the list slightly down (until item 10 appears):
convertView is still null because there is still no view in the recycler (border of item1 is still visible at the top:))
02-05 13:48:25.169: INFO/System.out(947): getView 9 null
Let’s scroll list a little more:
Bingo! convertView is not null: item1 goes off the screen directly to the Recycler and item11 is created based on item1.
02-05 13:48:42.879: INFO/System.out(947): getView 10 android.widget.LinearLayout@437430f8
scroll more just to check what hapens:
02-05 14:01:31.069: INFO/System.out(947): getView 11 android.widget.LinearLayout@437447d0
02-05 14:01:31.142: INFO/System.out(947): getView 12 android.widget.LinearLayout@43744ff8
02-05 14:01:31.279: INFO/System.out(947): getView 13 android.widget.LinearLayout@43743fa8
02-05 14:01:31.350: INFO/System.out(947): getView 14 android.widget.LinearLayout@43745820
02-05 14:01:31.429: INFO/System.out(947): getView 15 android.widget.LinearLayout@43746048
02-05 14:01:31.550: INFO/System.out(947): getView 16 android.widget.LinearLayout@43746870
02-05 14:01:31.669: INFO/System.out(947): getView 17 android.widget.LinearLayout@43747098
02-05 14:01:31.839: INFO/System.out(947): getView 18 android.widget.LinearLayout@437478c0
02-05 14:03:30.900: INFO/System.out(947): getView 19 android.widget.LinearLayout@43748df0
02-05 14:03:32.069: INFO/System.out(947): getView 20 android.widget.LinearLayout@437430f8
convertView is not null as we expected. After item11 goes off the screen, it view (@437430f8) comes as convertView for item 21. simple.

Different list items’ layouts

Let’s move to the “more complicated” example. How about to add separator somewhere to the list.
You should do the following:
  1. Override getViewTypeCount() – return how many different view layouts you have
  2. Override getItemViewType(int) – return correct view type id by position
  3. Create correct convertView (depending on view item type) in getView
Simple, isn’t it? Code snippet:
public class MultipleItemsList extends ListActivity {
 
    private MyCustomAdapter mAdapter;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAdapter = new MyCustomAdapter();
        for (int i = 1; i < 50; i++) {
            mAdapter.addItem("item " + i);
            if (i % 4 == 0) {
                mAdapter.addSeparatorItem("separator " + i);
            }
        }
        setListAdapter(mAdapter);
    }
 
    private class MyCustomAdapter extends BaseAdapter {
 
        private static final int TYPE_ITEM = 0;
        private static final int TYPE_SEPARATOR = 1;
        private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
 
        private ArrayList mData = new ArrayList();
        private LayoutInflater mInflater;
 
        private TreeSet mSeparatorsSet = new TreeSet();
 
        public MyCustomAdapter() {
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
 
        public void addItem(final String item) {
            mData.add(item);
            notifyDataSetChanged();
        }
 
        public void addSeparatorItem(final String item) {
            mData.add(item);
            // save separator position
            mSeparatorsSet.add(mData.size() - 1);
            notifyDataSetChanged();
        }
 
        @Override
        public int getItemViewType(int position) {
            return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
        }
 
        @Override
        public int getViewTypeCount() {
            return TYPE_MAX_COUNT;
        }
 
        @Override
        public int getCount() {
            return mData.size();
        }
 
        @Override
        public String getItem(int position) {
            return mData.get(position);
        }
 
        @Override
        public long getItemId(int position) {
            return position;
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            int type = getItemViewType(position);
            System.out.println("getView " + position + " " + convertView + " type = " + type);
            if (convertView == null) {
                holder = new ViewHolder();
                switch (type) {
                    case TYPE_ITEM:
                        convertView = mInflater.inflate(R.layout.item1, null);
                        holder.textView = (TextView)convertView.findViewById(R.id.text);
                        break;
                    case TYPE_SEPARATOR:
                        convertView = mInflater.inflate(R.layout.item2, null);
                        holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
                        break;
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.textView.setText(mData.get(position));
            return convertView;
        }
 
    }
 
    public static class ViewHolder {
        public TextView textView;
    }
}
Let’s run what we wrote. Yo will see separators after each 4-th item in the list.
In the log – nothing exceptional – all convertView is null for visible items both types.
02-05 15:19:03.080: INFO/System.out(1035): getView 0 null type = 0
02-05 15:19:03.112: INFO/System.out(1035): getView 1 null type = 0
02-05 15:19:03.130: INFO/System.out(1035): getView 2 null type = 0
02-05 15:19:03.141: INFO/System.out(1035): getView 3 null type = 0
02-05 15:19:03.160: INFO/System.out(1035): getView 4 null type = 1
02-05 15:19:03.170: INFO/System.out(1035): getView 5 null type = 0
02-05 15:19:03.180: INFO/System.out(1035): getView 6 null type = 0
02-05 15:19:03.190: INFO/System.out(1035): getView 7 null type = 0
02-05 15:19:03.210: INFO/System.out(1035): getView 8 null type = 0
02-05 15:19:03.210: INFO/System.out(1035): getView 9 null type = 1
Scroll list and see what happens:
02-05 15:19:54.160: INFO/System.out(1035): getView 10 null type = 0
02-05 15:19:57.440: INFO/System.out(1035): getView 11 android.widget.LinearLayout@43744528 type = 0
02-05 15:20:01.310: INFO/System.out(1035): getView 12 android.widget.LinearLayout@43744eb0 type = 0
02-05 15:20:01.880: INFO/System.out(1035): getView 13 android.widget.LinearLayout@437456d8 type = 0
02-05 15:20:02.869: INFO/System.out(1035): getView 14 null type = 1
02-05 15:20:06.489: INFO/System.out(1035): getView 15 android.widget.LinearLayout@43745f00 type = 0
02-05 15:20:07.749: INFO/System.out(1035): getView 16 android.widget.LinearLayout@43747170 type = 0
02-05 15:20:10.250: INFO/System.out(1035): getView 17 android.widget.LinearLayout@43747998 type = 0
02-05 15:20:11.661: INFO/System.out(1035): getView 18 android.widget.LinearLayout@437481c0 type = 0
02-05 15:20:13.180: INFO/System.out(1035): getView 19 android.widget.LinearLayout@437468a0 type = 1
02-05 15:20:16.900: INFO/System.out(1035): getView 20 android.widget.LinearLayout@437489e8 type = 0
02-05 15:20:25.690: INFO/System.out(1035): getView 21 android.widget.LinearLayout@4374a8d8 type = 0
convertView is null for separator view type until first separator is visible. When it goes off the screen – view also comes to the Recycler and convertView comes to play.
MultipleItemsList.zip – source code

Saturday, May 18, 2013

HttpUrlConnection is preferred to Apache HttpClient on Android from Gingerbread ?

FROM:
http://android-developers.blogspot.com/2011/09/androids-http-clients.html

Android’s HTTP Clients



Jesse Wilson [This post is by Jesse Wilson from the Dalvik team. —Tim Bray]

Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.
But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.

HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.
Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}
In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:
Accept-Encoding: gzip
Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.
Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.
We also made several improvements to HTTPS in Gingerbread. HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.
In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:
  • Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.
  • Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a 304 Not Modified status. If the content is unchanged it will not be downloaded!
  • Uncached responses are served from the web. These responses will get stored in the response cache for later.
Use reflection to enable HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:
private void enableHttpResponseCache() {
    try {
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        File httpCacheDir = new File(getCacheDir(), "http");
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
    } catch (Exception httpResponseCacheNotAvailable) {
    }
}
You should also configure your Web server to set cache headers on its HTTP responses.

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

15 Java Thread Interview Questions and answers asked in Investment Bank

This is really helpful in recapping your understanding of java thread.

FROM:
http://javarevisited.blogspot.sg/2011/07/java-multi-threading-interview.html


Thread interview questions Java
Multi-threading and concurrency questions are essential part of any Java interview. If you are going for any Java interview on any Investment bank for equities front office position expect lots of muti-threading interview questions on your way. Multi-threading and concurrency is a favorite topics on Investment banking specially on electronic trading development and they grill candidate on many confusing java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in Java because most of them are in business of performance. High volume and low latency Electronic trading System which is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview questions on Java asked on different on different time. I am not providing answer of these thread interview questions but I will give you hint whenever possible, some time hint is enough to answer. I will update the post further with detailed answers just like I did for 10 Singleton interview questions in Java recently. With introduction of concurrency package in Java 5 questions on concurrent utility and concurrent collections are on rise as well. ThreadLocal, BlockingQueue, Counting Semaphore and ConcurrentHashMap are popular among those.


15 Java Thread Interview Questions and answers

1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.


2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure likeConcurrentHashMap and conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any java multi-threading interview because now days Its heavily used to build cache for electronic trading system on client and exchange connectivity space.


3) What are differences between wait and sleep method in java?
Another frequently asked thread interview question in Java mostly appear in phone interview. Only major difference is wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for more differences


4) Write code to implement blocking queue in Java?
This is relatively tough java multi-threading interview question which servers many purpose, it checks whether candidate can actually write Java code using thread or not, it sees how good candidate is on understanding concurrent scenarios and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it you can ask him to write it again using new java 5 concurrent classes etc.


5) Write code to solve the Produce consumer problem in Java?
Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions How do you solve producer consumer problem in Java, well it can be solved in multiple way, I have shared one way to solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well.

6) Write a program which will result in deadlock? How will you fix deadlock in Java?
Java thread interview questions and answers This is my favorite java thread interview question because even though deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. see How to avoid deadlock in java for more information on deadlock in Java.


7) What is atomic operation? What are atomic operations in Java?
Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You can read more about java synchronization here.


8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java?
Thread questions based on volatile keyword in Javahas become more popular after changes made on it on Java 5 and Java memory model. It’s good to prepare well about how volatile variables ensures visibility, ordering and consistency in concurrent environment.


9) What is race condition? How will you find and solve race condition?
Another multi-threading question in Java which appear mostly on senior level interviews. Most interviewer grill on recent race condition you have faced and how did you solve it and some time they will write sample code and ask you detect race condition. See my post on Race condition in Java for more information. In my opinion this is one of the best java thread interview question and can really test the candidate's experience on solving race condition or writing code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency practices in Java'".


10) How will you take thread dump in Java? How will you analyze Thread dump?
In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful to analyze deadlock situations as well.


11) Why we call start() method which in turns calls run() method, why not we directly call run() method ?
Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread. Read my post Difference between start and run method in Thread for more details.


12) How will you awake a blocked thread in java?
This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing InterruptedException. See my post How to deal with blocking methods in Java for more information on handling blocked thread.



13) What is difference between CyclicBarriar and CountdownLatch in Java ?
New java thread interview questions mostly to check familiarity with JDK 5 concurrent packages. One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch.


14) What is immutable object? How does it help on writing concurrent application?
Another classic interview questions on multi-threading, not directly related to thread but indirectly helps a lot. This java interview question can become more tricky if ask you to write an immutable class or ask you Why String is immutable in Java as follow-up.


15) What are some common problems you have faced in multi-threading environment? How did you resolve it?
Memory-interference, race conditions, deadlock, live lock and starvation are example of some problems comes in multi-threading and concurrent programming. There is no end of problem if you get it wrong and they will be hard to detect and debug. This is mostly experienced based interview question on java thread instead of fact based.

These were my favorite Java thread interview questions and mostly asked on Investment banks. This list is by no means complete so please contribute some of interesting java thread questions you have faced during interview. Purpose of this article is to collect and share great interview questions on multi-threading concept which not only helps on interview but opens door for learning new threading concept.

Update:
One of Javarevisited reader, Hemant has contributed some more thread interview questions in Java, though he hasn’t provide answer and left that job for me, I will certainly do when time allows, just like I have recently updated 10 Singleton interview question in Java with answers. If you guys know answers of this java concurrency questions than please post as comment:

Here is his comment “Good questions on multi-threading though you may need to prepare more in order to clear any multi-threading interview, you need to be familiar with concept of immutability, thread-safety, race condition and many more. 10 or 15 question is good for quick recap but you at-least need to prepare more than 50 questions on threading and concurrency to perform better on Java interview. You can find some interesting thread question below which is no doubt highly popular –

1) Difference between green thread and native thread in Java?
2) Difference between thread and process?
3) What is context switching in multi-threading?
4) Difference between deadlock and livelock, deadlock and starvation?
5) What thread-scheduling algorithm is used in Java?
6) What is thread-scheduler in Java?
7) How do you handle un-handled exception in thread?
8) What is thread-group, why its advised not to use thread-group in Java?
9) Why Executor framework is better than creating and managing thread by application ?
10) Difference between Executor and Executors in Java?
10) How to find which thread is taking maximum cpu in windows and Linux server?

Apart from practicing these question answers, more important is to understand the concept behind these multi-threading questions simply mugging the answers of these thread interview questions is not going to help because there would be a lot of follow-ups based upon your answer and if you haven't master the particular thread topic it would be difficult to answer them.


Read more: http://javarevisited.blogspot.com/2011/07/java-multi-threading-interview.html#ixzz2Tf4TdfOg