SringSring

Thursday, 6 August 2015

Spring Web Flow Docs.

Spring Web Flow Docs.
-----------------------
1) Defining Flows
1.1) What is a flow?
A flow encapsulates a reusable sequence of steps that can execute in different contexts.

1.2) What is the makeup of a typical flow?
In Spring Web Flow, a flow consists of a series of steps called "states". Entering a state typically results
in a view being displayed to the user. On that view, user events occur that are handled by the state.
These events can trigger transitions to other states which result in view navigations.
1.3) How are flows authored?
Flows are authored by web application developers using a simple XML-based flow definition language.
1.4)   Essential language elements?
flow
Every flow begins with the following root element:
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/springwebflow-2.0.xsd">
</flow>
All states of the flow are defined within this element. The first state defined becomes the flow's starting point.

view-state
Use the view-state element to define a step of the flow that renders a view:
<view-state id="enterBookingDetails" />

By convention, a view-state maps its id to a view template in the directory where the flow is located. For example,
the state above might render /WEB-INF/hotels/booking/ enterBookingDetails.xhtml if the flow itself was located in the
/WEB-INF/hotels/booking directory.
     
transition
Use the transition element to handle events that occur within a state:
<view-state id="enterBookingDetails">
<transition on="submit" to="reviewBooking" />
</view-state>
These transitions drive view navigations.

end-state
Use the end-state element to define a flow outcome:
<end-state id="bookingCancelled" />
When a flow transitions to a end-state it terminates and the outcome is returned.

Example:
<flow xmlns="http://www.springframework.org/schema/webflow"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/webflow
  http://www.springframework.org/schema/webflow/springwebflow-2.0.xsd">
<view-state id="enterBookingDetails">
<transition on="submit" to="reviewBooking" />
</view-state>
<view-state id="reviewBooking">
          <transition on="confirm" to="bookingConfirmed" />
  <transition on="revise" to="enterBookingDetails" />
   <transition on="cancel" to="bookingCancelled" />
</view-state>
<end-state id="bookingConfirmed" />
<end-state id="bookingCancelled" />
</flow>

1.5) Actions
Most flows need to express more than just view navigation logic. Typically they also need to invoke business services  of the application or other actions.

 Within a flow, there are several points where you can execute actions. These points are:
• On flow start
• On state entry
• On view render
• On transition execution
• On state exit
• On flow end
Actions are defined using a concise expression language. Spring Web Flow uses the Unified EL by default. The next few sections will cover the essential language elements for defining actions.

evaluate :
The action element you will use most often is the evaluate element. Use the evaluate element to evaluate an expression at a point within your flow. With this single tag you can invoke methods on Spring beans or any other flow variable. For example:
<evaluate expression="entityManager.persist(booking)" />

Assigning an evaluate result :
If the expression returns a value, that value can be saved in the flow's data model called flowScope:
<evaluate expression="bookingService.findHotels(searchCriteria)" result="flowScope.hotels"/>

Converting an evaluate result :
If the expression returns a value that may need to be converted, specify the desired type using the result-type attribute:
   <evaluate expression="bookingService.findHotels(searchCriteria)" result="flowScope.hotels" result-type="dataModel"/>

1.6) Input/Output Mapping
Each flow has a well-defined input/output contract. Flows can be passed input attributes when they start, and can return output attributes when they end.
  <input name="hotelId" type="long" value="flowScope.hotelId" required="true" />
        Make it input Name , type , corresponding value and is mandatory field.

<end-state id="bookingConfirmed">
<output name="bookingId" />
</end-state>

1.7) Variables
A flow may declare one or more instance variables. These variables are allocated when the flow starts. Any @Autowired transient references the variable holds are also rewired when the flow resumes.
var   :  Use the var element to declare a flow variable:
<var name="searchCriteria" lass="com.mycompany.myapp.hotels.search.SearchCriteria"/>
Make sure your variable's class implements java.io.Serializable, as the instance state is saved between flow requests.

Variable Scopes:
Web Flow can store variables in one of several scopes:

Flow Scope:
Flow scope gets allocated when a flow starts and destroyed when the flow ends. With the default implementation,  any objects stored in flow scope need to be Serializable.
View Scope:
                     View scope gets allocated when a view-state enters and destroyed when the state exits. View scope is only  referenceable from within a view-state. With the default implementation, any objects stored in view scope need to be Serializable.
Request Scope :
Request scope gets allocated when a flow is called and destroyed when the flow returns.
Flash Scope :
Flash scope gets allocated when a flow starts, cleared after every view render, and destroyed when the flow ends.
With the default implementation, any objects stored in flash scope need to be Serializable.
Conversation Scope :
Conversation scope gets allocated when a top-level flow starts and destroyed when the top-level flow ends.
Conversation scope is shared by a top-level flow and all of its sub flows. With the default implementation,
conversation scoped objects are stored in the HTTP session and should generally be Serializable to account
for typical session replication.

1.8) Calling Subflows :
A flow may call another flow as a subflow. The flow will wait until the subflow returns, then respond to the subflow outcome.
  subflow-state
Use the subflow-state element to call another flow as a subflow:
<subflow-state id="addGuest" subflow="createGuest">
<transition on="guestCreated" to="reviewBooking">
<evaluate expression="booking.guests.add(currentEvent.attributes.guest)" />
</transition>
<transition on="creationCancelled" to="reviewBooking" />
</subflow-state>

   Passing a subflow input : Use the input element to pass input to the subflow:
<subflow-state id="addGuest" subflow="createGuest">
<input name="booking" />
<transition to="reviewBooking" />
</subflow-state>
Mapping subflow output  : Simply refer to a subflow output attribute by its name within a outcome transition:
<transition on="guestCreated" to="reviewBooking">
<evaluate expression="booking.guests.add(currentEvent.attributes.guest)" />
</transition>

    Final Example :

            <flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/springwebflow-
2.0.xsd">
<input name="hotelId" />
<on-start>
<evaluate expression="bookingService.createBooking(hotelId, currentUser.name)" result="flowScope.booking" />
</on-start>
<view-state id="enterBookingDetails">
<transition on="submit" to="reviewBooking" />
</view-state>
<view-state id="reviewBooking">
<transition on="addGuest" to="addGuest" />
<transition on="confirm" to="bookingConfirmed" />
<transition on="revise" to="enterBookingDetails" />
<transition on="cancel" to="bookingCancelled" />
</view-state>
<subflow-state id="addGuest" subflow="createGuest">
<transition on="guestCreated" to="reviewBooking">
<evaluate expression="booking.guests.add(currentEvent.attributes.guest)" />
</transition>
<transition on="creationCancelled" to="reviewBooking" />
</subflow-state>
<end-state id="bookingConfirmed" >
<output name="bookingId" value="booking.id" />
</end-state>
<end-state id="bookingCancelled" />
</flow>


2) Expression Language (EL) :

EL is used for many things within a flow including:
1. Access client data such as declaring flow inputs or referencing request parameters.
2. Access data in Web Flow's RequestContext such as flowScope or currentEvent.
3. Invoke methods on Spring-managed objects through actions.

4. Resolve expressions such as state transition criteria, subflow ids, and view names.

  2.1)   Expression types : 
          Standard Expressions:   The first and most common type of expression is the standard expression. Such expressions are evaluated directly by the EL and need not be enclosed in delimiters like #{}.  Ex :    <evaluate expression="searchCriteria.nextPage()" />

         Template expressions :    The second type of expression is a template expression. A template expression allows mixing of literal text with one or more standard expressions. Each standard expression block is explicitly surrounded with the #{} delimiters.
For example: <view-state id="error" view="error-#{externalContext.locale}.xhtml" />

 List of implicit variables:
1) flowScope   :   Use flowScope to assign a flow variable. Flow scope gets allocated when a flow starts and destroyed when the flow ends. With the default implementation, any objects stored in flow scope need to be Serializable.
  <evaluate expression="searchService.findHotel(hotelId)" result="flowScope.hotel" />

2) viewScope   : Use viewScope to assign a view variable. View scope gets allocated when a view-state enters and destroyed when the state exits. View scope is only referenceable from within a view-state. With the default implementation, any objects stored in view scope need to be Serializable.
<on-render>
<evaluate expression="searchService.findHotels(searchCriteria)" result="viewScope.hotels"
result-type="dataModel" />
</on-render>
3) requestScope : Use requestScope to assign a request variable. Request scope gets allocated when a flow is called and destroyed when the flow returns.
      <set name="requestScope.hotelId" value="requestParameters.id" type="long" />
4) flashScope : Use flashScope to assign a flash variable. Flash scope gets allocated when a flow starts, cleared after every view render, and destroyed when the flow ends. With the default implementation, any objects stored in flash scope need to be Serializable.
<set name="flashScope.statusMessage" value="'Booking confirmed'" />
5) conversationScope : Use conversationScope to assign a conversation variable. Conversation scope gets allocated when a top-level flow starts and destroyed when the top-level flow ends. Conversation scope is shared by a top-level flow and all of its subflows. With the default implementation, conversation scoped objects are stored in the HTTP session and should generally be Serializable to account for typical session replication.
<evaluate expression="searchService.findHotel(hotelId)" result="conversationScope.hotel" />
6) requestParameters: Use requestParameters to access a client request parameter:
       <set name="requestScope.hotelId" value="requestParameters.id" type="long" />
7) currentEvent   : Use currentEvent to access attributes of the current Event:
        <evaluate expression="booking.guests.add(currentEvent.attributes.guest)" />
8) currentUser: Use currentUser to access the authenticated Principal:
<evaluate expression="bookingService.createBooking(hotelId, currentUser.name)"
result="flowScope.booking" />
9) messageContext : Use messageContext to access a context for retrieving and creating flow execution messages, including error and success messages. See the MessageContext Javadocs for more information.
<evaluate expression="bookingValidator.validate(booking, messageContext)" />
10) resourceBundle : Use resourceBundle to access a message resource.
<set name="flashScope.successMessage" value="resourceBundle.successMessage" />
11) flowRequestContext : Use flowRequestContext to access the RequestContext API, which is a representation of the current flow request. See the API Javadocs for more information.
12) flowExecutionContext : Use flowExecutionContext to access the FlowExecutionContext API, which is a representation of the current flow state. See the API Javadocs for more information.
13) flowExecutionUrl : Use flowExecutionUrl to access the context-relative URI for the current flow execution view-state.
14) externalContext :Use externalContext to access the client environment, including user session attributes.

<evaluate expression="searchService.suggestHotels(externalContext.sessionMap.userProfile)"
result="viewScope.hotels" />


Wednesday, 5 August 2015

Service-Oriented Architecture (SOA)

A service-oriented architecture (SOA) is an architectural pattern in computer software design in which application components provide services to other components via acommunications protocol, typically over a network. The principles of service-orientation are independent of any vendor, product or technology.[1]
A service is a self-contained unit of functionality, such as retrieving an online bank statement.[2] By that definition, a service is a discretely invokable operation. However, in the Web Services Definition Language (WSDL), a service is an interface definition that may list several discrete services/operations. And elsewhere, the term service is used for a component that is encapsulated behind an interface. This widespread ambiguity is reflected in what follows.


The Open Group's definition is:
Service-Oriented Architecture (SOA) is an architectural style that supports service-orientation. Service-orientation is a way of thinking in terms of services and service-based development and the outcomes of services.
A service:
Is a logical representation of a repeatable business activity that has a specified outcome (e.g., check customer credit, provide weather data, consolidate drilling reports)
Is self-contained
May be composed of other services
Is a “black box” to consumers of the service

Overview

Services are unassociated, loosely coupled units of functionality that are self-contained. Each service implements at least one action, such as submitting an online application for an account, retrieving an online bank statement or modifying an online booking or airline ticket order. Within an SOA, services use defined protocols that describe how servicespass and parse messages using description metadata, which in sufficient details describes not only the characteristics of these services, but also the data that drives them. Programmers have made extensive use of XML in SOA to structure data that they wrap in a nearly exhaustive description-container. Analogously, the Web Services Description Language (WSDL) typically describes the services themselves, while SOAP (originally Simple Object Access Protocol) describes the communications protocols. SOA depends on data and services that are described by metadata that should meet the following two criteria:
  1. The metadata should be provided in a form that software systems can use to configure dynamically by discovery and incorporation of defined services, and also to maintain coherence and integrity. For example, metadata could be used by other applications, like a catalogue, to perform auto discovery of services without modifying the functional contract of a service.
  2. The metadata should be provided in a form that system designers can understand and manage with a reasonable expenditure of cost and effort.
The purpose of SOA is to allow users to combine together fairly large chunks of functionality to form ad hoc applications built almost entirely from existing software services. The larger the chunks, the fewer the interfaces required to implement any given set of functionality; however, very large chunks of functionality may not prove sufficiently granular for easy reuse. Each interface brings with it some amount of processing overhead, so there is a performance consideration in choosing the granularity of services.
SOA as an architecture relies on service-orientation as its fundamental design principle. If a service presents a simple interface that abstracts away its underlying complexity, then users can access independent services without knowledge of the service's platform implementation


SOA framework

SOA-based solutions endeavour to enable business objectives while building an enterprise-quality system. SOA architecture is viewed as five horizontal layers:[7]
  1. Consumer Interface Layer – These are GUI for end users or apps accessing apps/service interfaces.
  2. Business Process Layer – These are choreographed services representing business use-cases in terms of applications.
  3. Services – Services are consolidated together for whole-enterprise in-service inventory.
  4. Service Components – The components used to build the services, such as functional and technical libraries, technological interfaces etc.
  5. Operational Systems – This layer contains the data models, enterprise data repository, technological platforms etc.
There are four cross-cutting vertical layers, each of which are applied to and supported by each of the following horizontal layers:
  1. Integration Layer – starts with platform integration (protocols support), data integration, service integration, application integration, leading to enterprise application integration supporting B2B and B2C.
  2. Quality of Service – Security, availability, performance etc. constitute the quality of service parameters which are configured based on required SLAs, OLAs.
  3. Informational – provide business information.
  4. Governance – IT strategy is governed to each horizontal layer to achieve required operating and capability model.

Principles

There are no industry standards relating to the exact composition of a service-oriented architecture, although many industry sources have published their own principles. Some of these [12][13][14][15] include the following:
  • Standardized service contract: Services adhere to a communications agreement, as defined collectively by one or more service-description documents.
  • Service loose coupling: Services maintain a relationship that minimizes dependencies and only requires that they maintain an awareness of each other.
  • Service abstraction: Beyond descriptions in the service contract, services hide logic from the outside world.
  • Service reusability: Logic is divided into services with the intention of promoting reuse.
  • Service autonomy: Services have control over the logic they encapsulate, from a Design-time and a Run-time perspective.
  • Service statelessness: Services minimize resource consumption by deferring the management of state information when necessary[16]
  • Service discoverability: Services are supplemented with communicative meta data by which they can be effectively discovered and interpreted.
  • Service composability: Services are effective composition participants, regardless of the size and complexity of the composition.
  • Service granularity: A design consideration to provide optimal scope and right granular level of the business functionality in a service operation.
  • Service normalization: Services are decomposed or consolidated to a level of normal form to minimize redundancy. In some cases, services are denormalized for specific purposes, such as performance optimization, access, and aggregation.[17]
  • Service optimization: All else being equal, high-quality services are generally preferable to low-quality ones.
  • Service relevance: Functionality is presented at a granularity recognized by the user as a meaningful service.
  • Service encapsulation: Many services are consolidated for use under the SOA. Often such services were not planned to be under SOA.
  • Service location transparency: This refers to the ability of a service consumer to invoke a service regardless of its actual location in the network. This also recognizes the discoverability property (one of the core principle of SOA) and the right of a consumer to access the service. Often, the idea of service virtualization also relates to location transparency. This is where the consumer simply calls a logical service while a suitable SOA-enabling runtime infrastructure component, commonly a service bus, maps this logical service call to a physical service.

Web services approach

Web services can implement a service-oriented architecture.[19] They make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages. These services can represent either new applications or just wrappers around existing legacy systems to make them network-enabled.
Each SOA building block can play one or both of two roles:
  1. Service provider: The service provider creates a web service and possibly publishes its interface and access information to the service registry. Each provider must decide which services to expose, how to make trade-offs between security and easy availability, how to price the services, or (if no charges apply) how/whether to exploit them for other value. The provider also has to decide what category the service should be listed in for a given broker service and what sort of trading partner agreements are required to use the service. It registers what services are available within it, and lists all the potential service recipients. The implementer of the broker then decides the scope of the broker. Public brokers are available through the Internet, while private brokers are only accessible to a limited audience, for example, users of a company intranet. Furthermore, the amount of the offered information has to be decided. Some brokers specialize in many listings. Others offer high levels of trust in the listed services. Some cover a broad landscape of services and others focus within an industry. Some brokers catalog other brokers. Depending on the business model, brokers can attempt to maximize look-up requests, number of listings or accuracy of the listings. The Universal Description Discovery and Integration (UDDI) specification defines a way to publish and discover information about Web services. Other service broker technologies include (for example) ebXML (Electronic Business using eXtensible Markup Language) and those based on the ISO/IEC 11179 Metadata Registry (MDR) standard.
  2. Service consumer: The service consumer or web service client locates entries in the broker registry using various find operations and then binds to the service provider in order to invoke one of its web services. Whichever service the service-consumers need, they have to take it into the brokers, bind it with respective service and then use it. They can access multiple services if the service provides multiple services.

Web service protocols

Implementers commonly build SOAs using web services standards (for example, SOAP) that have gained broad industry acceptance after recommendation of Version 1.2 from the W3C[20] (World Wide Web Consortium) in 2003. These standards (also referred to as web service specifications) also provide greater interoperability and some protection from lock-in to proprietary vendor software. One can, however, implement SOA using any service-based technology, such as Jini, CORBA or REST.

Other SOA concepts

Architectures can operate independently of specific technologies and can therefore be implemented using a wide range of technologies, including:



Monday, 3 August 2015

SOA and API Management

API-Management-Invasion
Service Oriented Architecture (SOA) and Application Programming Interface (API) Management relate to each other in both complementary and contrasting ways. The fact that API is a much older term than SOA, but SOA came before API Management can make this relationship even more confusing, especially if focus is on the “API” part of API Management, when the “Management” part is what’s important. Let’s say that modern API management deals with SOA based APIs, but we still need the old-fashioned code library style APIs which run in the same process as the client code that uses them. SOA Governance is the part of SOA which has mostly evolved into API Management, but it’s important to remember that API Management cannot stand without the foundation of SOA.
SOA Governance has been about managing services within an enterprise, with an occasional exception of providing these services to business partners or consuming services provided by business partners. This includes service lifecycle management (designing, developing, testing, deploying, versioning and retiring), provisioning, security, mediation and other required aspects of governance.
API Management contains all the aspects of SOA Governance, but also adds things like Developer Portal and API Gateway. These are replacements/enhancements to traditional SOA Registry/Repository and ESB. They are motivated by exposing APIs to developers outside the enterprise and monetizing the APIs, but they are also beneficial within the enterprise. In fact, intra-enterprise use is the primary driver for adopting API Management today.
Some of the most important benefits of replacing traditional SOA Governance with the API Management approach do not come from any actual differences between the two, but from different architecture styles that are generally associated with each of these approaches.
Traditional SOA is generally associated with SOAP over HTTP or over JMS and XML payloads, while API Management is generally associated with REST over HTTP and JSON payloads. The interface of traditional SOA services was usually defined using WSDL, and while the latest version of WSDL can be used to define REST services, APIs are usually defined using WADL extended by particular API Management tools.
Architecture designs that are used with API Management usually also reject some old SOA concepts which experience has exposed as embellishments. These include things like service broker, UDDI, runtime binding of clients to service implementations, and ESBs that perform routing, choreography and transformation outside service implementations. The more modern architecture designs, usually associated with API Management, tend to use the “smart endpoints and dumb pipes” approach, where services are as decoupled and as cohesive as possible, and communicate over simple “dumb” mechanisms like HTTP and lightweight messaging. Message bus implementations are used for asynchronous message routing, and they are not ESBs that do all kinds of other “smart” things.

Interface design in SOA is usually based on a small set of known clients and their needs/requirements in order to implement some business process(es). With API management, interfaces are designed with specific clients and uses in mind, but also with an expectation that they may be accessed by other clients and used in ways that have not even been imagined yet. This leads to simpler and better service and interface design, and may be the most significant contribution of API Management to SOA.

Friday, 31 July 2015

Fail Fast Vs Fail Safe Iterator In Java

Difference between Fail fast and fail safe iterator  or  Fail fast vs Fail Safe iterator is one of those questions which are  used to test your knowledge about the topic Concurrency.
Before we discuss in detail about fail safe iterator and fail fast iterator in addition to  their comparison , we should understand the termConcurrent Modification .

What is Concurrent Modification ?

When one or more thread is iterating over the collection, in between, one thread changes the structure of the collection (either adding the element to the collection or by deleting the element in the collection or by updating the value at particular position in the collection) is known as Concurrent Modification

Difference between Fail Fast iterator and Fail Safe iterator

Fail fast Iterator

Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. 

Fail-fast iterator can throw ConcurrentModificationException in two scenarios :



difference between fail fast iterator and fail safe iterator
Single Threaded Environment
  
After the creation of the iterator , structure is modified at any time by any method other than iterator's own remove method. 
  
Multiple Threaded Environment 

 If one thread is modifying the structure of the collection while other thread is iterating over it .


According to  Oracle docs , the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. 


Interviewer : How  Fail  Fast Iterator  come to know that the internal structure is modified ?

Iterator read internal data structure (object array) directly . The internal data structure(i.e object array) should not be modified while iterating through the collection. To ensure this it maintains an internal  flag "mods" .Iterator checks the "mods" flagwhenever it gets the next value (using hasNext() method and next() method). Value ofmods flag changes whenever there is an structural modification. Thus indicating iterator to throw ConcurrentModificationException.


Fail Safe Iterator :

Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure.  So , original data structure remains  structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.

Two  issues associated with Fail Safe Iterator are :

1. Overhead of maintaining the copied data structure i.e memory.

2.  Fail safe iterator does not guarantee that the data being read is the data currently in the original data structure. 

According to Oracle docs , fail safe iterator is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don’t want to synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove(), set(), and add()) are not supported. These methods throw UnsupportedOperationException.



Example of Fail Fast Iterator and Fail Safe Iterator



import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FailFastExample
{
    
    
    public static void main(String[] args)
    {
        Map<String,String> premiumPhone = new HashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
        
        Iterator iterator = premiumPhone.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
        
    }
    
}

Output :


iPhone 
Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$KeyIterator.next(Unknown Source)
        at FailFastExample.main(FailFastExample.java:20)


Fail Safe Iterator Example :


import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;


public class FailSafeExample
{
    
    
    public static void main(String[] args)
    {
        ConcurrentHashMap<String,String> premiumPhone = 
                               new ConcurrentHashMap<String,String>();
        premiumPhone.put("Apple", "iPhone");
        premiumPhone.put("HTC", "HTC one");
        premiumPhone.put("Samsung","S5");
        
        Iterator iterator = premiumPhone.keySet().iterator();
        
        while (iterator.hasNext())
        {
            System.out.println(premiumPhone.get(iterator.next()));
            premiumPhone.put("Sony", "Xperia Z");
        }
        
    }
    
}

Output :


S5
HTC one
iPhone


Recap : Difference between Fail Fast Iterator and Fail Safe Iterator 


Fail Fast IteratorFail Safe Iterator
Throw ConcurrentModification ExceptionYesNo
Clone objectNoYes
Memory OverheadNoYes
ExamplesHashMap,Vector,ArrayList,HashSet
CopyOnWriteArrayList,
ConcurrentHashMap