Anda di halaman 1dari 34

How HashMap works in Java How HashMap works in Java or sometime how get method work in HashMap is common

interview questions now days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or midsenior level java interviews. Questions start with simple statement "Have you used HashMap before" or "What is HashMap? Why do we use it Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt null while hashtable doesn't, HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc. This shows that person has used hashMap and quite familiar with the functionality HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interview here you and come back with questions like "Do you Know how hashMap works in Java or "How does get () method of HashMap works in Java" And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc. But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java. But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g "What will happen if two different objects have same hashcode? Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say "Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list." great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this. But story does not end here and final questions interviewer ask like "How will you retreive if two different objects have same hashcode? Hmmmmmmmmmmmmm Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retrieves object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail. But those bunch of people who remember this key information will say that after finding

bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer. In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap. Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys. Now if you clear all this java hashmap interview question you will be surprised by this very interesting question "What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?". Until you know how hashmap works exactly you won't be able to answer this question. if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location. If you manage to answer this question on hashmap in java you will be greeted by "do you see any problem with resizing of hashmap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java. So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer :) I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified Concept of hashing Collision resolution in HashMap Use of equals () and hashCode () method and there importance? Benefit of immutable object? race condition on hashmap in Java Resizing of Java HashMap Just to summarize here are the answers which does makes sense for above questions How HashMAp works in Java HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list. Also hashMap stores both key+value tuple in every node of linked list. What will happen if two different HashMap key objects have same hashcode? They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.

How to avoid deadlock in Java Threads How to avoid deadlock in Java is one of the question which is flavor of the season for multithreading , asked more at a senior level and with lots of follow up questions , though question looks very basic but most of developer get stuck once you start going deep. questions starts with "What is deadlock ?" answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking. How do you detect deadlock in Java ? though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful. other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object. other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object. once you answer this , they may ask you to write code which will result in deadlock ? here is one of my version public void method1(){ synchronized(String.class){ System.out.println("Aquired lock on String.class object"); synchronized (Integer.class) { System.out.println("Aquired lock on Integer.class object"); } } } public void method2(){ synchronized(Integer.class){ System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) { System.out.println("Aquired lock on String.class object"); } } } If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thead 1 aquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen. now interviewer comes to final part , one of the most important in my view , How to fix deadlock ? or How to avoid deadlock in Java ? if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is the fixed version.

public void method1(){ synchronized(Integer.class){ System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) { System.out.println("Aquired lock on String.class object"); } } } public void method2(){ synchronized(Integer.class){ System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) { System.out.println("Aquired lock on String.class object"); } } }

Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further. Example of Synchronization in Java using synchronized method and block Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multithreaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile. Concurrent access of sharedobjects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads. Why do we need Synchronization in Java? If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is read only or immutable object you don't need synchronization despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don't require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time. In Summary Java Synchronized Keyword provides following functionality essential for concurrent programming : 1) synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race. 2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don't use synchronized or volatile keyword. 3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock at this point it reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.

Synchronized keyword in Java Prior to Java5 synchronized keyword in java was only way to provide synchronization of shared object. Any code written in synchronized block in java will be mutual 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 but we can not have synchronized variable in java. Using synchronized keyword with variable is illegal and will result in compilation error. Instead of java synchronized variable you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and dont cache it locally. Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method. Since java synchronization comes with cost of performance we need to synchronize only part of code which absolutely needs to be synchronized.

Example of synchronized method in Java Using synchronized keyword along with method is easy just apply synchronized keyword in front of method. What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current object (this). So its possible that both static and non static java synchronized method running in parallel. This is the common mistake a naive developer do while writing java synchronized code. public class Counter{ private static int count = 0; public static synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } } In this example of java synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on same object and can run in parallel which results in getting incorrect count. Here getCount() will lock in Counter.class object while setCount() will lock on current object (this). To make this code properly synchronized in java you need to either make both method static or non static or use java synchronized block instead of java synchronized method. Example of synchronized block in Java Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then java synchronized block will throw a NullPointerException. public class Singleton{ private static volatile Singleton _instance; public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton.class){ if(_instance == null) _instance = new Singleton(); }

} return _instance; } This is a classic example of double checked locking in Singleton. In this example of java synchronized code we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance because if you make whole method synchronized every call of this method will be blocked while you only need to create instance on first call. To read more aboutSingleton in Java see here. Important points of synchronized keyword in Java 1. Synchronized keyword in Java is used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently. 2. You can use java synchronized keyword only on synchronized method or synchronized block. 3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception. 4. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method. 5.java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock. 6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws NullPointerException if myInstance is null. 7. One Major disadvantage of java synchronized keyword is that it doesn't allow concurrent read which you can implement using java.util.concurrent.locks.ReentrantLock. 8. One limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that. 9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only. 10. Java synchronized block is better than java synchronized method in java because by using synchronized block you can only lock critical section of code and avoid locking whole method which can possibly degrade performance. A good example of java synchronization around this concept is getInstance() method Singleton class. See here. 11. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object. 12. From java 5 after change in Java memory model reads and writes are atomic for all variables declared using volatile keyword (including long and double variables)

and simple atomic variable access is more efficient instead of accessing these variables via synchronized java code. But it requires more care and attention from the programmer to avoid memory consistency errors. 13. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly. To know how to avoid deadlock in java see here. 14. According to the Java language specification you can not use java synchronized keyword with constructor its illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it. 15. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method. 16. Java.util.concurrent.locks extends capability provided by java synchronized keyword for writing more sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks. 17. java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory. 18. Important method related to synchronization in Java are wait(), notify() and notifyAll() which is defined in Object class. 19. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field : private String lock = new String("lock"); synchronized(lock){ System.out.println("locking on :" + lock); } any if you write synchronized code like above in java you may get warning "Synchronization on non-final field" in IDE like Netbeans and InteliJ 20. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance. instead of String object its advised to use new Object() for Synchronization in Java on synchronized block. private static final String LOCK = "lock"; //not recommended private static final Object OBJ_LOCK = new Object(); //better public void process() { synchronized(LOCK) { ........ } } 21. From Java library Calendar and SimpleDateFormat classes are not thread-safe and requires external synchronization in Java to be used in multi-threaded environment.

Probably most important point about synchronization in Java is that in the absence of synchronized keyword or construct compiler, JVM and hardware are free to make optimization, assumption, reordering or caching of code and variable which can cause

subtle concurrency bugs in code. By introducing synchronization may be either using volatile or synchronized keyword we instruct compiler or JVM to not to do that

Difference between HashMap and HashSet in Java HashMap vs HashSet is the most frequently asked question during any core java interview and interview is not said completed until they will not cover the Collection Framework and multi-threading interview and collections are uncompleted without Covering Hash Set and Hash Map. Both HashMap and HashSet are part of collection framework which allows us to work with collection of objects. Collection Framework has their own interfaces and implementation classes. Basically collection is divided as Set Interface, List and Queue Interfaces. All this interfaces have their own property also apart from they get from collection like Set allows Collection of objects but forbids duplicate value, List allows duplicate along with indexing.Queue woks on FCFS algorithm. First we have one look on What HashMap and Hashset is then will go for Differences between HashSet and HashMap What is HashSet in Java? HashSet is implementation of Set Interface which does not allow duplicate value all the methods which are in Collection Framework are also in Set Interface by default but when we are talking about Hash set the main thing is objects which are going to be stored in HashSet must override equals() andhashCode() method so that we can check for equality and no duplicate value are stored in our set.if we have created our own objects we need to implement hashCode() and equal() in such a manner that will be able to compare objects correctly when storing in a set so that duplicate objects are not stored,if we have not override this method objects will take default implementation of this method. public boolean add(Object o) Method is used to add element in a set which returns false if its a duplicate value in case of HashSet otherwise returns true if added successfully. What is HashMap? HashMap is a implementation of Map Interface, which maps a key to value.Duplicate keys are not allowed in a map.Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.HashMap allows null values and null keys.HashMap is not synchronized,but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our hashmap and one thread is structurally change our map. public Object put(Object Key,Object value) method is used to add element in map. You can read more about HashMap in my article How HashMap works in Java and Difference between HashMap and hashtable in Java Difference between HashSet and HashMap in Java Following are some differences between HashMap and Hashset:

Hash Map HashMap is a implementation of Map interface HashMap Stores data in form of key value pair

Hash Set HashSet is an implementation of Set Interface HashSet Store only objects

Put method is used to add element in map In hash map hashcode value is calculated using key object

HashMap is faster than hashset because unique key is used to access object

Add method is used to add element is Set Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality ifit returns false that means two objects are different. HashSet is slower than Hashmap

What is the difference between Enumeration and Iterator ? What are differences between Enumeration and Iterator This question is from early ages of interview , I have not seen this question on recent interviews but it was common during 2006-2007 , now days questions like implementation of HashMap, ConcurrentHashMap etc has take its place, nonetheless its very useful to know fundamental difference between Iterator and Enumeration . Some time its also asked as Iterator vs Enumeration or Enumeration vs Iterator which is same. important point to note is that both Iterator and Enumeration provides way to traverse or navigate through entire collection in java Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0 while iterator was introduced later. Iterator can be used with Java arraylist, java hashmap keyset and with any other collection classes. Another similarity between Iterator and Enumeration in Java is that functionality of Enumeration interface is duplicated by the Iterator interface. Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist. Also Iterator is more secure and safe as compared to Enumeration because it does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java. In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison: Enumeration hasMoreElement() nextElement() N/A Iterator hasNext() next() remove() So Enumeration is used when ever we want to make Collection objects as Read-only. How to implement Thread in JAVA In my opinion Thread is the most wonderful feature of JAVA and I remember when I started learning JAVA in one of programming class in India how important Thread was portrait and how much emphasis given on clear understanding of multi threading. Its indeed still popular and one of most sought after skill in JAVA.

In this core java tutorial I will share my experience on different way of implementing Thread in Java; this is also a very common core java interview question and asked mostly during junior level java interview. There are two ways of implementing threading in JAVA 1) By extending java.lang.Thread class, or 2) By implementing java.lang.Runnable interface. Before we go into implementation details I just like to cover when we use thread? so we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface. Actually public void run () method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically. I remember by first java multi threading example which was an animation program where multiple threads were used in Applet to create animation of words falling from top left, middle and top right of the page. That was pretty exciting at that time because till then I only know program which takes input from command prompt and print output on command prompt. So now the interview question "Which way of implementing Thread is better? Extending Thread class or implementing Runnable method? In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us. Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface. till then we have just created a thread , Thread will not start until you call the start() method of java.lang.Thread class. When we call start () method Java Virtual machine execute run () method of that Thread class into separate Thread other than calling thread. Anybody guess what will happen if we call the run() method directly instead of calling start() method ? That another interesting interview question and answer is simple there would be any Error or Exception run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start () method twice in same Thread object e.g. mythread.start(); mythread.start();// this line will throw IllegalThreadStateException

//implementing Thread by extending Thread class class MyThread extends Thread{ public void run(){ System.out.println("I am executing by Thread: " + Thread.currentThread().getName()); } } //implementing Thread by implementing Runnable interface class MyRunnable implements Runnable{ public void run(){ System.out.println("I am executing by Thread: " + Thread.currentThread().getName()); }

} //starting Thread Thread mythread = new MyThread(); mythread.setName("T1"); Thread myrunnable = new Thread(new MyRunnable(),"T2"); mythread.start(); myrunnable.start(); TIP1: Its not guaranteed that mythread will start before myrunnable it depends upon Thread scheduler. TIP2: Thread will be said to go on dead state once execution of run () method finished and you cannot start that thread again. What is Race Condition in multithreading 2 Examples in Java Race condition in Java is a type of concurrency bug or issue which is introduced in your program because parallel execution of your program by multiple threads at same time, Since Java is a multi-threaded programming language hence risk of Race condition is higher in Java which demands clear understanding of what causes a race condition and how to avoid that. Anyway Race conditions are just one of hazards or risk presented by use of multi-threading in Java just like deadlock in Java. Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other. Classical example of Race condition is incrementing a counter since increment is not an atomic operation and can be further divided into three steps like read, update and write. if two threads tries to increment count at same time and if they read same value because of interleaving of read operation of one thread to update operation of another thread, one count will be lost when one thread overwrite increment done by other thread. atomic operations are notsubject to race conditions because those operation cannot be interleaved. This is also a popular multithreading interview questions during core java interviews. In this article we will see how to find race condition in Java and two sample code patterns which often causes race conditions in Java. How to find Race Conditions in Java Finding Race conditions in any language is most difficult job and Java is no different, though since readability of Java code is very good and synchronized constructs are well defined heaps to find race conditions by code review. finding race conditions by unit testing is not reliable due to random nature of race conditions. since race conditions surfaces only some time your unit test may passed without facing any race condition. only sure shot way to find race condition is reviewing code manually or using code review tools which can alert you on potential race conditions based on code pattern and use of synchronization in Java. I solely rely on code review and yet to find a suitable tool for exposing race condition in java. Code Example of Race Condition in Java Based on my experience in Java synchronization and where we use synchronized keyword I found that two code patterns namely "check and act" and "read modify write" can suffer race condition if not synchronized properly. both cases rely on natural assumption that a single line of code will be atomic and execute in one shot which is wrong e.g. ++ is not atomic. "Check and Act" race condition pattern classical example of "check and act" race condition in Java is getInstance() method of Singleton Class, remember that was one questions which we have discussed on 10 Interview questions on Singleton pattern in Java as "How to write thread-safe Singleton in Java". getInstace() method first check for whether instance is null and than initialized the instance and return to caller. Whole purpose of Singleton is that getInstance should always return same instance of Singleton. if you call getInstance() method from two thread

simultaneously its possible that while one thread is initializing singleton after null check, another thread sees value of _instance reference variable as null (quite possible in java) especially if your object takes longer time to initialize and enters into critical section which eventually results in getInstance()returning two separate instance of Singleton. This may not happen always because a fraction of delay may result in value of _instance updated in main memory. here is a code example public Singleton getInstance(){ if(_instance == null){ //race condition if two threads sees _instance= null _instance = new Singleton(); } } an easy way to fix "check and act" race conditions is to synchronized keyword and enforce locking which will make this operation atomic and guarantees that block or method will only be executed by one thread and result of operation will be visible to all threads once synchronized blocks completed or thread exited form synchronized block. read-modify-update race conditions This is another code pattern in Java which cause race condition, classical example is the non thread safe counter we discussed in how to write thread safe class in Java. this is also a very popular multi-threading question where they ask you to find bugs on concurrent code. read-modify-update pattern also comes due to improper synchronization of non-atomic operations or combination of two individual atomic operationswhich is not atomic together e.g. put if absent scenario. consider below code if(!hashtable.contains(key)){ hashtable.put(key,value); } here we only insert object into hashtable if its not already there. point is both contains() and put() are atomic but still this code can result in race condition since both operation together is not atomic. consider thread T1 checks for conditions and goes inside if block now CPU is switched from T1 to thread T2 which also checks condition and goes inside if block. now we have two thread inside if block which result in either T1 overwriting T2 value or vice-versa based on which thread has CPU for execution. In order to fix this race condition in Java you need to wrap this code inside synchronized block which makes them atomic together because no thread can go inside synchronized block if one thread is already there. Java Web Services Interview Questions and Answers: Overview Q. What are the different application integration styles? A. There are a number of different integration styles like 1. Shared database 2. batch file transfer 3. Invoking remote procedures (RPC) 4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).

Q. What are the different styles of Web Services used for application integration? A. SOAP WS and RESTful Web Service

Q. What are the differences between both SOAP WS and RESTful WS? A.

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style. The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.

The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

Q. How would you decide what style of Web Service to use? SOAP WS or REST? A. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability. The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.

Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL) Do we need to support multiple data formats? Do we need to make AJAX calls? (REST can use the XMLHttpRequest) Is the call synchronous or asynchronous? Is the call stateful or stateless? (REST is suited for statless CRUD operations) What level of security is required? (SOAP WS has better support for security)

What level of transaction support is required? (SOAP WS has better support for transaction management) Do we have limited band width? (SOAP is more verbose) Whats best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)

Q. What tools do you use to test your Web Services? A. SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.

Q. What is the difference between SOA and a Web service? A. SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs). Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.

Q. Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI and DCOM? A. The traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use. Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.

Q. What are the different approaches to developing a SOAP based Web service? A. 2 approaches.

The contract-first approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract.

The contract-last approach where you define the Java classes first and then generate the contract, which is the WSDL file from the Java classes. Note: The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses.

Q. What are the pros and cons of each approach, and which approach would you prefer? A. Contract-first Web service

PROS:

Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients. Developers can work simultaneously on client and server side based on the contract both agreed on. You have full control over how the request and response messages are constructed -- for example, should "status" go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the "status" would be generated as "attribute" instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc CONS:

More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.

Developers need to learn XSDs and WSDLs in addition to just knowing Java.

Contract-last Web service PROS:

Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.

The learning curve and development time can be smaller compared to the Contract-first Web service. CONS:

The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.

In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.

So, which approach will you choose? The best practice is to use "contract-first", and here is the link that explains this much better with examples --> contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the "contract-first". You will have to decide what is most appropriate based on your requirements, tool sets you use, etc. JavaScript Interview Questions and Answers: Overview Like me, many have a love/hate relationship with JavaScript. Now a days, JavaScript is very popular with the rich internet applications (RIA). So, it really pays to know JavaScript. JavaScript is a client side (and server side with node.js) technology that is used to dynamically manipulate the DOM tree. There are a number of JavaScript based frameworks like jQuery available to make your code more cross browser compatible and simpler. Firstly, it is much easier to understand JavaScript if you stop comparing it with Java or understand the key differences. Both are different technologies. If you need more motivation to learn JavaScript, look at the Node.js, which is a software system designed for writing highly-scalable internet applications in JavaScript, using event-driven, asynchronous I/O to minimize overhead. Q. What is the difference between Java and JavaScript? A. Don't be fooled by the term Java in both. Both are quite different technologies. The key differences can be summarized as follows:

JavaScript variables are dynamically typed, whereas the Java variables are statically typed.

? 1 2 3 4 var var var var myVar1 myVar2 myVar3 myVar4 = = = = "Hello"; //string type 5; //number type new Object( ); //empty object type {}; //empty object type -- JSON (JavaScript Object Notation) style.

In JavaScript properties and methods are dynamically added, whereas Java uses a template called a class. ThemyVar3 empty object dynamically adds properties and a method.

? 1 2 3 4 5 6 myVar3.firstName = "Test1"; // add a property to object myVar3.lastName = "Test2"; // add a property to object // add a method myVar3.someFunction = function( ) { //. }

JavaScript function can take variable arguments. You can call the function shown below as myFunction( ), myFunction(20), or myFunction(20,5).

? 1 2 3 function myFunction( value ) { //.. do something here }

JavaScript has an implicit keyword known as the "arguments", which holds all the passed arguments. It also has a "length" property as in arguments.length to display the number of arguments. Technically an "arguments" is not an array as it does not have the methods like push, pop, or split that an array has. Here is an example.

? 1 2 3 4 5 6 7 8 9 10 myFunction(5,10,15,20); function myFunction(value) { //value is 5; //arguments[0] is 5 //arguments[1] is 10 //arguments[2] is 15 //arguments[3] is 20 //arguments.length is 4 }

JavaScript objects are basically like name/value pairs stored in a HashMap<string,object>. For example, a JavaScript object is represented in JSON style as shown below. ? 1 2 3 4 5 6 7 8 9 10 11 12

var personObj = { firstName: "John", lastName: "Smith", age: 25, printFullName: function() { document.write(this.firstName + " " + this.lastName); }, printAge: function () { document.write("My age is: " + this.age); } }

You can invoke the methods as shown below ? 1 2 3

personObj.printFullName(); personObj.printAge();

JavaScript functions are objects as well. Like objects, the functions can be stored to a variable, passed as arguments, nested within each other, etc. In the above example, nameless functions are attached to variables "printFullName" and "printAge" and invoked via these variables. A function that is attached to an object via a variable is known as a "method". So, printFullName and printAge are methods.

Technically, what is done with the "add" and "sum" functions is that we have created a new function object and attached them to the variables "add" and sum. As you can see in the example below, the "add" variable is assigned to variable "demo", and the function is invoked via demo(2,5) within the "sum" function. ? 1 2 3 4 5 6 7 8 9 10 11 function add(val1, val2) { var result = val1 + val2; alert("The result is:" + result); return result; } var demo = add; function sum() { var output = demo(5, 2); }

Now the above temp.js under tutorial/js folder can be invoked from an HTML file under tutorial/html as shown below. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loos <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script language="javascript" type="text/javascript" src="../js/temp.js"> </script> <title>Insert title here</title> </head> <body> <form id="evaluate1"> <input type="button" value="evaluate" onclick="sum()"/> <input type="button" value="evaluate2" onclick="demo(3,2)"/> <input type="button" value="evaluate3" onclick="add(2,2)"/> </form> </body> </html>

This demonstrates that the functions in JavaScript are objects, and can be passed around. Every function in JavaScript also has a number of attached methods including toString( ), call( ), and apply( ). For example, The temp2.js is stored under js_tutorial/js. ? 1 2 3 4 5 6 7 8 9 10 11 12 function add(val1, val2) { var result = val1 + val2; alert("Result is:" + result); return result; } var printAdd = add.toString(); //converts the "add" function to string. function demo() { alert(printAdd); //alerts the whole source code of the "add" function }

The demo function can be invoked from an html.The temp2.html is stored under js_tutorial/html. ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loos <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script language="javascript" type="text/javascript" src="../js/temp2.js"> </script> <title>Insert title here</title> </head> <body> <form id="evaluate1"> <input type="button" value="evaluate" onclick="demo()"/> </form> </body> </html>

The printAdd cannot be invoked from the HTML because this variable stores the string representation of the source code of the "add"function and not the function itself. JavaScript variables need to be treated like records stored in a HasMap and referenced by name, and not by memory address or pass-by-reference as in Java. The following code snippet demonstrates this.

? 1 2 3 4 5 var x = function () { alert("X"); } var y = x; x = function () { alert("Y"); }; y(); // alerts "X" and NOT "Y" x(); // alerts "Y"

Java does not support closure till atleast version 6. A closure is a function plus a binding environment. closures can be passed downwards (as parameters) or returned upwards (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active. JavaScript supports closure. In JavaScript a closure is created every time you create a function within a function. When using a closure, you will have access to all the variables in the enclosing (i.e. the parent) function.

? 1 2 3 4 5 6 7 8 9 10 11 var calculate = function(x) { var myconst = 2; return function(y) { return x + y + myconst; }; }

// has visibility to parent variable 'const'

var plus5 = calculate(5); //plus5 is now a closure alert(plus5(3)); //returns 10 i.e. x=5, y=3, myconst=2 alert(plus5(7)); //returns 14 i.e x=5, y=7, myconst=2 alert(plus5(10)); //returns 17 i.e x=5, y=10, myconst=2 Java programs can be single threaded or multi-threaded. JavaScript engines only have a single thread, forcing events like

Asynchronous UI Events like mouse click, focus, etc. It is asynchronous because you don't know when a user is going to click or change a text.


? 1 ?

Timer functions like

1var id = setTimeout(function, delay); // Initiates a single timer which will call the specified function after the 2var id = setInterval(function, delay); // Similar to setTimeout but continually calls the function (with a delay 3clearInterval(id); // Accepts a timer ID (returned by either of the aforementioned functions) an 4clearTimeout(id); Ajax responses asynchronously invoking a callback function when the response is sent back from the server. It is asynchronous because, you don't know how long a server will take to process the ajax request and then to send the response. to execute within the same thread. Even though all the above time based events appear to be run concurrently, they are all executed one at a time by queuing all these events. This also mean that if a timer is blocked from immediately executing, it will be delayed until the next possible point of execution making it to wait longer than the desired delay. This might also cause the intervals execute with no delay. Having said this, HTML5 specifies Web Workers, which is a standardized API for multithreading JavaScript code. Here are the key points to remember: 4. JavaScript variables are dynamically typed. 5. 6. In JavaScript properties and methods are dynamically added. JavaScript function can take variable arguments.

7. JavaScript objects are basically like name/value pairs stored in a HashMap<string,object>. 8. JavaScript functions are objects as well.

Here are some working examples: For the examples shown below, the HTML files are stored under /html sub-folder and JavaScript files are stored under /js sub-folder. The console.log() statements are written to your browser's web console. For example, in firefox, you can view the web console via tools - Web Developer - Web Console. Make sure that the version of Firefox you use has this option. The Web Console is handy for debugging as well.

Example 1: two input values are either added or concatenated depending on their types. If both values of type number then add them, otherwise just concatenate the values. Take note of the JavaScript keywords and functions like typeof, isNaN(..), Number(..), parseInt(..), etc. The "document" is part of the DOM tree representing an HTML document in memory. The method "getElementById(...)" will return the relevant "input" element from the DOM tree, and "value" will return the input value that was entered. ? 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loos 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 6 <script language="javascript" type="text/javascript" src="../js/evaluate1.js"> 7 </script> 8 9 <title>Insert title here</title> 10 </head> 11 <body> 12 13 <form id="evaluate1"> 14 15 <input id="val1" type="text" value="" />

16 <input id="val2" type="text" value="" /> 17 <input type="button" value="evaluate" onclick="addOrConcat()"/> 18 19 20 <p> 21 <div id="result"></div> 22 </p> 23 24 25 </form> 26 27 </body> 28 </html> ? 1 function addOrConcat() { 2 var val1 = document.getElementById("val1").value; //string 3 var val2 = document.getElementById("val2").value; //string 4 var result = document.getElementById("result"); //object 5 6 7 var ans = -1; //number 8 9 //if val1 and val2 are numbers, add them 10 if(!isNaN(val1) && typeof parseInt(val2) == 'number') { 11 ans = Number(val1) + Number(val2); //add numbers 12 }else { 13 ans = val1 + val2; //string concat 14 } 15 16 result.innerHTML = "Result is: " + ans; 17 //write to browser console. 18 console.log("val1 is of type " + typeof val1); 19 console.log("result is of type " + typeof result); 20 console.log("ans is of type " + typeof ans); 21 } Example 2: Very similar to Example 1, but uses objects, and passes the relevant values from the call within HTML itself. It also uses the toString( ) method to convert a function object to display its source code. ? 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loos 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 6 <script language="javascript" type="text/javascript" src="../js/evaluate3.js"> 7 </script> 8 9 <title>Insert title here</title> 10 </head> 11 <body> 12 13 <form id="evaluate1"> 14 15 <input id="val1" type="text" value="" /> 16 <input id="val2" type="text" value="" /> 17 <input type="button" value="evaluate" onclick="addOrConcat(document.getElementById('val1').val 18 19 20 <p> 21 <div id="result"></div> 22 </p> 23 24

25 </form> 26 27 </body> 28 </html> ? 1 function addOrConcat(val1,val2) { 2 3 var evalObj = new Object(); //create an empty object 4 5 evalObj.input1 = val1; // add a property of type string 6 evalObj['input2'] = val2; // add a property of type string 7 evalObj.result = document.getElementById("result"); // add a property of type object 8 9 //add a method 10 evalObj.evaluate = function() { 11 12 if(!isNaN(this.input1) && typeof parseInt(this.input2) == 'number') { 13 this.ans = Number(this.input1) + Number(this.input2); //add numbers 14 }else { 15 this.ans = evalObj.input1 + this.input2; //string concat 16 } 17 18 this.result.innerHTML = "Result is: " + this.ans; 19 20 } 21 22 evalObj.evaluate(); //call the method evaluate and "this" refers to evalObj 23 console.log(evalObj.evaluate.toString()); 24 25 } Example 3: Similar to Example 2, with minor modifications to the JavaScript file to demonstrate keywords like "arguments" ? 1 function addOrConcat() { 2 3 var evalObj = new Object(); // create an empty object 4 5 evalObj.input1 = arguments[0]; // this is value1 6 evalObj['input2'] = arguments[1]; // this is value2 7 evalObj.result = document.getElementById("result"); // add a property of type object 8 9 //add a method 10 evalObj.evaluate = function() { 11 12 if(!isNaN(this.input1) && typeof parseInt(this.input2) == 'number') { 13 this.ans = Number(this.input1) + Number(this.input2); //add numbers 14 }else { 15 this.ans = evalObj.input1 + this.input2; //string concat 16 } 17 18 this.result.innerHTML = "Result is: " + this.ans; 19 20 } 21 22 evalObj.evaluate(); //call the method evaluate and "this" refers to evalObj 23 console.log(evalObj.evaluate.toString()); 24 25 }

Service Oriented Architecture (SOA) Interview Questions


By admin - Posted on 26 August 2009

What are the main benefits of SOA ?

SOA helps create greater alignment between IT and line of business while generating more flexibility - IT flexibility to support greater business flexibility. Your business processes are changing faster and faster and global competition requires the flexibility that SOA can provide. SOA can help you get better reuse out of your existing IT investments as well as the new services you're developing today. SOA makes integration of your IT investments easier by making use of well-defined interfaces between services. SOA also provides an architectural model for integrating business partners, customers and suppliers services into an enterprises business processes. This reduces cost and improves customer satisfaction What is a reusable Service?

It is an autonomous, reusable, discoverable, stateless functionality that has the necessary granularity, and can be part of a composite application or a composite service. A reusable service should be identified with a business activity described by the service specifications (design-time contract). A service's constraints, including security, QoS, SLA, usage policies, may be defined by multiple run-time contracts, multiple interfaces (the WSDL for a SOAP Web Service), and multiple implementations (the code). A reusable service should be governed at the enterprise level throughout its entire lifecycle, from design-time through run-time. Its reuse should be promoted through a prescriptive process, and that reuse should be measured.
Talking about Service identification, which approach between top-down and bottom-up methodologies encourages re-use and mantainance ?

Since the top-down approach is business-driven it can be practical to separate the different concerns of business and IT on different plans, providing a common ground in between. So in most situations it the most appropriate if you want to improve reuse and ROI in the medium/long term. Anyway
How can you achieve loose coupling in a soa ?

One strategy for achieving loose coupling is to use the service interface (the WSDL for a SOAP Web Service) to limit this dependency, hiding the service implementation from the consumer. Loose coupling can be addressed by encapsulating the service

functionalities in a manner that limits the impact of changes to the implementation on the service interface. However, at some point you will need to change the interface and manage versioning without impacting service consumers, in addition to managing multiple security constraints, multiple transports, and other considerations Do you recall any pattern which could be use to leverage loose coupling ?

The Mediation pattern, using an enterprise service bus (ESB), will help in achieving this. Mediation will take loose coupling to the highest level. It will establish independence between consumers and providers on all levels, including message formats, message types (including SOAP, REST, XML, binary) and transport protocols (including HTTP, HTTPS, JMS). Architecturally speaking this means the separation of concerns between consumers and providers on the transport, message type, and message format levels. The Service of a SOA should be engineered as stateless or stateful ?

Service should be stateless. It may have a context within its stateless execution, but it will not have an intermediary state waiting for an event or a call-back. The retention of state-related data must not extend beyond a request/response on a service. This is because state management consumes a lot of resources, and this can affect the scalability and availability that are required for a reusable service. What is composition of a Service ?

Composition is the process by which services are combined to produce composite applications or composite services. A composite application consists of the aggregation of services to produce an enterprise portal or enterprise process. A composite service consists of an aggregation of services that produces another reusable service. It's just like combining electronic components to create a computer motherboard, and then using that motherboard in a computer. Think of the motherboard as a reusable composite service that is a component of the computer, and of the computer as the composite application.
How do I integrate my Legacy applications with SOA ?

Legacy applications are frequently at the core of your IT environment. With the right skills and tools, you need to identify discrete elements within your legacy applications and "wrap" them in standards-based interfaces and use them as services within your SOA. How does the ESB fits in this picture ?

The Enterprise Service Bus is a core element of any SOA. ESBs provide the "any to any" connectivity between services within your own company, and beyond your business to connect to your trading partners. But SOA does not stop at just implementing an ESB.

Depending on what your goals are, you may want to use an ESB to connect other services within your SOA such as information services, interaction services and business process management services. Additionally, you will need to consider development services and IT service management services. The SOA reference architecture can help you lay out an SOA environment that meets your needs and priorities. The ESB is part of this reference architecture and provides the backbone of an SOA but it should not be considered an SOA by itself. What are the common pitfalls of SOA ?

One of the most common pitfalls is to view SOA as an end, rather than a means to an end. Developers who focus on building an SOA solution rather than solving a specific business problem are more likely to create complex, unmanageable, and unnecessary interconnections between IT resources. Another common pitfall is to try to solve multiple problems at once, rather than solving small pieces of the problem. Taking a top-down approachstarting with major organization-wide infrastructure investmentsoften fails either to show results in a relevant timeframe or to offer a compelling return on investment. What's the difference between services and components? Services are logical grouping of components to achieve business functionality. Components are implementation approaches to make a service. The components can be in JAVA, C#, C++ but the services will be exposed in a general format like Web Services. What are ends, contract, address, and bindings? These three terminologies on which SOA service stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method. An Address indicates where we can find this service. Address is a URL, which points to the location of the service. Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created. Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.

The concept of SOA is nothing new, however why everyone started to talk about SOA only in the last years ?

Yes I agree the basic concept of SOA aren't new, however some technology technology changes in the last 10 years made service-oriented architecture more practical and applicable to more organizations than it was previously. Among this:
Universally-accepted industry standards such as XML, its many variants, and Webservices standards have contributed to the renewed interest in SOA. Data governance frameworks, which are important to a successful SOA implementation, have well test and refined over the years. A variety of enabling technologies and tools (e.g., modeling, development, infrastructure/middleware, management, and testing) have matured.

Understanding of business and business strategies has grown, shifting attention from technology to the people, cultural changes, and process that are key business success factors.

What is the most important skill you need to adopt SOA ? technical or cultural ? Surely cultural. SOA does require people to think of business and technology differently. Instead of thinking of technology first (e.g., If we implement this system, what kinds of things can we do with it?), practitioners must first think in terms of business functions, or services (e.g., My company does these business functions, so how can I set up my IT system to do those things for me most efficiently?).It is expected that adoption of SOA will change business IT departments, creating service-oriented (instead of technology-oriented) IT organizations.
Is SOA really needed on your opinion? SOA is not for everyone. While SOA delivers significant benefits and cost savings, SOA does require disciplined enforcement of centralized governance principals to be successful. For some organizations, the cost of developing and enforcing these principals may be higher than the benefits realized, and therefore not a sound initiative.

(B) What is SOA?


SOA stands for service oriented architecture. Before we define SOA lets first define a service. In real world service is what we pay for and we get the intended service. For instance you go to a hotel and order food. Your order first goes to the counter and then it goes to the kitchen where the food is prepared and finally the waiter serves the food.

Figure: - Hotel and services So in order to order a item from a hotel you need the three logical departments / services to work together (counter, kitchen and waiter). In the same manner in software world these services are termed as business services. They are self contained and logical. So let's first define a business service, SOA definition will be just an extension of the same. Definition of business service: - It's a logical encapsulation of self contained business functionality. For instance figure 'order system' shows a simple ordering system which is achieved by different services like payment gateway, stock system and delivery system coming together. All the services are self contained and logical. They are like black boxes. In short we do not need to understand the internal details of how the business service works. For the external world it's just a black box which takes messages and serves accordingly. For instance the 'payment gateway' business service takes message 'check credit' and gives out output does the customer have credit or not. For the 'order system' business service 'payment gateway' service is a black box.

Figure: - Order system Now let's revise some bullet points of SOA before we arrive to a definition of SOA. . SOA components are loosely coupled. When we say loosely coupled means every service is self contained and exist in alone logically. For instance we take the 'payment gateway' service and attach it to a different system. . SOA services are black boxes. In SOA services hide there inner complexities. They only interact using messages and send services depending on those messages. By visualizing services as black boxes services become more loosely coupled. . SOA service should be self defined: - SOA services should be able to define themselves. . SOA Services are maintained in a listing: - SOA services are maintained in a central repository. Applications can search the services in the central repository and use them accordingly. . SOA components can be orchestrated and linked to achieve a particular functionality . SOA services can be used/orchestrated in a plug and play manner. For instance figure 'Orchestration' shows two services 'Security service' and 'Order processing service'. You can achieve two types of orchestrations from it one you can check the user first and then process order or vice-versa. Yes you guessed right using SOA we can manage work flow between services in a loosely coupled fashion.

Figure: - Orchestration So let us define SOA. SOA is a architecture for building business applications using loosely coupled services which act like black boxes and can be orchestrated to achieve a specific functionality by linking together.

(I) In SOA do we need to build systems from scratch?


No. If you need to integrate or make an existing system as a business service, you just need to create loosely coupled wrappers which will wrap your custom systems and expose the systems functionality in generic fashion to the external world.

(I) Can you explain business layers and plumbing layers in SOA?
In SOA we can divide any architecture in two layers. The first which has direct relevance to business as it carries out business functions. The second layer is a technical layer which talks about managing computer resources like database, web server etc. This division is needed to identify a service. Consider the figure 'Simple order system'. It has various components which interact with each other to complete the order system functionality.

Figure: - Simple order System The simple order system can be divided in to two layers (see figure 'business and plumbing layer' one which is business related and second which is more technical related. You can see the plumbing layer consisting of data access layer , AJAX , yes more of technical stuff.

Figure: - Business layer and plumbing layer

(I) what's the difference between services and components?


Services are logical grouping of components to achieve business functionality. Components are implementation approaches to make a service. The components can be in JAVA, C#, C++ but the services will be exposed in a general format like Web Services.

(A) Can you describe the complete architecture of SOA?


Figure 'Architecture of SOA' shows a complete view of a SOA. Please note this architecture diagram is not tied up with implementation of Microsoft, IBM etc. It's a general architecture. Any vendor who implements SOA needs to fulfill the below SOA components. How they do it is completely their own technological implementation.

Figure: - Architecture of SOA The main goal of SOA is to connect disparate systems. In order that these disparate system work they should messages to each other. ESB (Enterprise service bus) acts like a reliable post office which guarantees delivery of messages between systems in a loosely coupled manner. ESB is a special layer which delivers messages between applications. In the figure we have shown a huge plump pipe. It's not hardware or some wire etc. It's a group of components/software which helps you to send and receive messages between the disparate applications. Do not try to code your own ESB, you can think of buying one from Microsoft, IBM, Oracle, progress etc. SOA registry is like a reference database of services. It describes what each services do, where are they located and how can they communicate. It's a central reference of metadata for services. SOA workflow allows us to define work flow using the services in SOA registry. We will read more about BPM in the further questions. Service broker reads the work flow and takes services from the SOA registry and ties them together. Service brokers are normally middleware like EAI (Enterprise application Integration) products. You can get a list of decent EAI from Sun, Microsoft, and IBM etc. Process manager is nothing but the collection of SOA registry, SOA workflow and service broker. SOA supervisor is traffic cop ensuring that services do not have issues. It deals mainly with performance issues of the system so that appropriate service levels are met. If any of the

services have performance problems it sends messages to the proper infrastructure to fix the issue. Note: - The above explanation is of general architecture for SOA. Any vendor (Microsoft, IBM, SUN etc) who gives solution for SOA should have the above components in some or other manner. As this is a Software architecture book, we will not be covering specific vendor implementation. We would advise the reader to map the same to their vendor products for better understanding.

(I) Can you explain a practical example in SOA?

(I) What are ends, contract, address, and bindings?


These three terminologies on which SOA service stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:. Contract (What) Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method. . Address (Where) An Address indicates where we can find this service. Address is a URL, which points to the location of the service. . Binding (How) Bindings determine how this end can be accessed. It determines how communications is

done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created. Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.

Figure: - Endpoint Architecture Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract.

(I) Are web-services SOA ?


SOA is a thinking, it's an architectural concept and web service is one of the technical approach to complete it. Web services are the preferred standards to achieve SOA. . In SOA we need the services to be loosely coupled. A web service communicates using SOAP protocol which is XML based which is very loosely coupled. It answers the what part of the service. . SOA services should be able to describe themselves. WSDL describes how we can access the service. . SOA services are located in a directory. UDDI describes where we can get the web service. This nothing but implementation of SOA registry.

Anda mungkin juga menyukai