Showing posts with label java interview questions. Show all posts
Showing posts with label java interview questions. Show all posts

Friday, August 31, 2018

scrum interview questions


What is “Agile”

It’s a set of guidelines that helps you deliver useful, valuable increments of software to customers at the end of each sprint (like two weeks). It is done by constantly re-prioritizing the backlog of requirements and reviewing incremental progress with the product owner.

What are the differences between Agile and traditional project management (Waterfall)?

Agile encourages that a little of everything, including design, development, and testing is done at the same time. Conversely, the traditional approach to projects closes and completes one phase before the next begins. Agile encourages short, frequent feedback loops and embraces changes to requirements. In Waterfall, feedback is usually not collected until the very end of the project, and changes are discouraged

When should you use Waterfall over Scrum?
Use waterfall if the requirements are simple, predictable, fully defined and understood, and will not change.

Name some other Agile frameworks.
such as Kanban, Test Driven Development, and Feature Driven Development.

What are the most important components of Agile?

    Daily stand-up meetings.

    CRC (Class Responsibilities and Collaborators) cards

    timeboxed task boards.

    TDD (Test Driven Development), Continuous Integration, regular code reviews, pair programming, automated builds, continuous deployment and delivery, etc.

    You have iteration planning meetings and carry out iterative development.



How study Board can be defined in agile?

A Story Board is a visual representation of a software project’s progress. There are generally four columns ‘To do’, In Progress’, ‘Test’, and ‘Done’. Different colored post, its notes are placed in each column indicating the progress of individual development items. A story board is typically used in agile development.



What do daily stand up meetings entail?

This meeting addresses SCRUM’s three questions listed below.
– What have you completed since the last meeting?
– What do you plan to complete by the next meeting?
– What is getting in your way?

What is the Daily Stand-Up?
Every day, preferably in the morning, the team meets for no more than 15 minutes to answer three questions:
What did you do yesterday?
What do you plan on doing today?
Are there any blocks or impediments that keep you from doing your work?
This Scrum ceremony is not meant to be a status meeting for stakeholders, but a way to energize the team and get them to set focus for the day.


What is a Release candidate?

A Release candidate is a build or version of software that can be released to production.

Further, testing such as UAT may be performed on this version of the product.



What is difference between Epic, User stories & Tasks?
Epic is a group of related user stories.
User Stories define the actual business requirement. Generally created by the business owner.
Task: To accomplish the business requirements, development team create tasks.



Explain Velocity in Agile?
Velocity is a metric that is calculated by addition of all efforts estimates associated with user stories completed in one iteration. It predicts how much work Agile can complete in a sprint and how much time will it require to complete a project.

What is velocity?
Velocity is the average number of points from that past 3 – 4 sprints. It is used to help predict when backlog items will be delivered.

How the velocity of sprint is measured?
If capacity is measured as a percentage of 40 hours weeks then
completed= story points * team capacity
If capacity is measured in man hours then
completed story points / team capacity.


Have you ever tracked velocity? How would you determine a teams Sprint velocity?
Team velocity is tracked, using the number of estimated story points, over the actual completed story points.
This can be measured on the burndown chart. You can guess your team velocity overtime, from the previous sprints

Explain what is a product backlog in Scrum?
Before the scrum sprint initiates, product owner reviews the list of all new features, change requests, enhancements and bug reports and determines the priority.

What type of metrics or reports have you used?
Sprint, release burn-down and burn-up charts are standard reports

What does a scrum burn down chart comprise?
A scrum burn down chart should consist of
    X-axis that displays working days
    Y-axis that displays remaining effort
    Ideal effort as guideline
    Real progress of effort

What is a burn-down chart?
A burn-down chart displays the amount of work a team has burned through—such as hours during the sprint

What is a retrospective?
A retrospective is a meeting to inspect and adapt the process

What is Scrum Sprint?
A Scrum Sprint is a regular, repeated work cycle in scrum methodology during which work is completed and made ready for review.
Generally, scrum sprints are less than 30 days long.

Describe what happens in the Sprint planning meeting.
In Sprint planning, the Product Owner presents the goal of the sprint and discusses the high priority product backlog items. The Delivery team then chooses the amount of work for the next sprin

What are the roles in Scrum?
Scrum prescribes only three roles: the Product Owner, Scrum Master, and the Delivery Team.
These roles should ideally be cross-functional and not shared among other projects.

What is the role of the Scrum Master?
The Scrum Master serves the team and shields them from any distractions that could prevent them from completing a sprint goal.
They also remove blocks, teach the team to become self-organized and serve as a coach who teaches Agile and Scrum values and principles

How many Scrum teams have you managed at one time?
Notice the use of the word “managed” versus “led.”  Scrum Masters do not manage, they lead teams.you may be required to lead more than one team

What are the artifacts of Scrum process?

Sprint backlog – The Sprint Backlog is the set of Product Backlog items selected for the Sprint, plus a plan for delivering the product Increment and realizing the Sprint Goal. The Sprint Backlog is a forecast by the Development Team about what functionality will be in the next Increment and the work needed to deliver that functionality into a “Done” Increment

Product backlog – The Product Backlog is an ordered list of everything that might be needed in the product and is the single source of requirements for any changes to be made to the product. The Product Owner is responsible for the Product Backlog, including its content, availability, and ordering.

Velocity chart- A velocity chart shows the sum of estimates of the work delivered across all iterations

Burn-down chart – It is a chart that shows how quickly you and your team are burning through your customer’s user stories. It shows the total effort against the amount of work we deliver on each iteration.



https://intellipaat.com/interview-question/agile-scrum-master-interview-questions/
https://www.glassdoor.com/Interview/us-project-manager-scrum-master-interview-questions-SRCH_IL.0,2_IN1_KO3,31.htm
https://easybacklog.com/
https://www.simplilearn.com/agile-scrum-master-interview-questions-article


  • What is Kanban? 

Kanban is a method for managing the creation of products with an emphasis on continual delivery while not overburdening the development team. Like Scrum, Kanban is a process designed to help teams work together more effectively.
Kanban is based on 3 basic principles:

    Visualize what you do today (workflow): seeing all the items in context of each other can be very informative
    Limit the amount of work in progress (WIP): this helps balance the flow-based approach so teams don€™t start and commit to too much work at once
    Enhance flow: when something is finished, the next highest thing from the backlog is pulled into play

https://www.versionone.com/what-is-kanban/

Tuesday, June 24, 2014

There are four different ways to create objects in java

  • There are four different ways to create objects in java

1. The new keyword
2. The Class.forName()
3. The clone() method
4. The object deserialization

https://www.linkedin.com/groups/What-are-all-different-ways-70526.S.5883998172040155140?view=&item=5883998172040155140&type=member&gid=70526&trk=eml-b2_anet_digest-null-75-null&fromEmail=fromEmail&ut=3f1ocViNIMOCg1

http://javabeginnerstutorial.com/core-java-tutorial/different-ways-to-create-an-object-in-java/

Tuesday, December 10, 2013

how to count rows in eclipse

how to count rows in  eclipse
\n[\s]*
counting empty lines
\n

Tuesday, April 23, 2013

What will happen if we don’t override the hashcode method?



  • What will happen if we don’t override the hashcode method?


If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

JVM assigns unique hashcode value to each object when they are created in memory
if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.

equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?
The answer to the question is for the hash technique based data structures like HashMap and HashTable.

every object is placed in Hash bucket depending on the hashcode they have
It is not necessary that every different object must have different hashcode
hashcode is used to narrow the search result

When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and
if yes then it checks for the equals() method.
If two objects are same then HashMap will not add that key
instead it will replace the old value by new one.

http://shivasoft.in/blog/java/what-is-the-need-to-override-hashcode-and-equals-method/

Thursday, March 7, 2013

immutable class



  • What is immutable class in Java

Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. best example to understand immutable and mutable objects are, String and StringBuffer.
Since String is immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating substring from String, all result in a new objects.
While in case of mutable object like StringBuffer, any modification is done on object itself and no new objects are created.
Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.

advantages
1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.
3) Immutable object boost performance of Java application by reducing synchronization in code.

disadvantages
Since immutable object can not be reused and they are just a use and throw.
String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection

http://javarevisited.blogspot.com/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html#ixzz2Mry69OKV



  • What is immutable object? Can you write immutable object?
You need to make class final and all its member final so that once objects gets created no one can modify its state.
You can achieve same functionality by making member as non final but private and not modifying them except in constructor

How to create and export PDF files in Java



  • How to create and export PDF files in Java

There are lots of open source library that lets you play with the pdf files in java
http://mrbool.com/how-to-create-and-export-pdf-files-in-java/27343#ixzz2MrralrNH

Tuesday, March 5, 2013

What is the difference between javac and the Eclipse compiler?


What is the difference between javac and the Eclipse compiler?


Eclipse's built-in compiler is based on IBM's Jikes java compiler.
(Note that Eclipse also started its life at IBM).
It is completely independent of Sun's Java compiler in the JDK;

Another difference is that the Eclipse Compiler allows for incremental builds from within the Eclipse IDE, i.e. all code is compiled as soon as you finish typing.
The fact that Eclipse comes with its own compiler is also apparent because you can write, compile, and run Java code in Eclipse without even installing the Java SDK.
Few examples where ECJ is preferred over javac - Apache Tomcat uses ECJ to compile JSPs, IntelliJ IDEA has support ECJ, as of GCJ 4.3, GCJ integrates with ECJ, Liferay Builds with ECJ


An incremental Java compiler. Implemented as an Eclipse builder, it is based on technology evolved from VisualAge for Java compiler. In particular, it allows to run and debug code which still contains unresolved errors.
http://stackoverflow.com/questions/3061654/what-is-the-difference-between-javac-and-the-eclipse-compiler

how to compile java file without javac command?


how to compile java file without javac command?

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "yourClass.java");

The compiler is a command line tool but can also be invoked using the Java Compiler API.
The compiler accepts source code defined by the Java Language Specification (JLS) and produces class files defined by the Java Virtual Machine Specification (JVMS)
http://docs.oracle.com/javase/7/docs/technotes/guides/javac/index.html


  • ECJ - Eclipse Compiler for Java

Eclipse provides and uses its own compiler that is not javac

    The Eclipse compiler is used inside the IDE (Eclipse)
    The Eclipse compiler can also be used as a pure batch compiler outside of Eclipse


  • OpenJDK is the only open-source Java SE implementation

http://openjdk.java.net



  • The GNU Compiler for the JavaTM Programming Language

GCJ is a portable, optimizing, ahead-of-time compiler for the Java Programming Languag
http://gcc.gnu.org/java/

Tuesday, February 12, 2013

Difference between ArrayList vs LinkedList



  • Difference between ArrayList vs LinkedList 


1) Data Structure
ArrayList Array
LinkedList LinkedList

2) LinkedList implements Deque
LinkedLis implements deque and list interfaces

7) Memory
LinkedList uses a wrapper object, Entry,  which is a static nested class for storing data and two nodes next and previous while ArrayList just store data in Array. So memory requirement seems less in case of ArrayList than LinkedList except the case where Array performs re-size operation, when it copies content from one Array to another.
If Array is large enough it may take lot of memory at that point and trigger Garbage collection, which can slow response time.

http://java67.blogspot.com/2012/12/difference-between-arraylist-vs-LinkedList-java.html

Monday, January 14, 2013

What's the difference between throw, throwable & throws?



throw and throws are java keywords and Throwable is a super class for errors and exceptions.
Only the objects of the Throwable can be thrown by the “throws” or “throw” statement.

throws :
used on the method to specify than an exception(s) can be thrown. The throws clause tells the complier that this particular exception would be handled by the calling method.

throw :
it is a statement to throw the exception when certain condition is failed or other logic had returned exception. This can be used in any part of code where you feel a specific exception needs to be thrown to the calling method

http://www.linkedin.com/groups/Whats-difference-between-throw-throwable-70526.S.200485518?view=&srchtype=discussedNews&gid=70526&item=200485518&type=member&trk=eml-anet_dig-b_pd-ttl-cn&ut=17ZTwoVDpUpBA1

Friday, November 23, 2012

10 Object Oriented Design principles Java programmer should know


10 Object Oriented Design principles Java programmer should know

Object oriented design principle 1 -  DRY (Don't repeat yourself)
Object oriented design principle 2 - Encapsulate what varies
Object oriented design principle 3 - Open Closed principle
Object oriented design principle 4 - Single Responsibility Principle (SRP)
Object oriented design principle 5 - Dependency Injection or Inversion principle
Object oriented design principle 6 - Favour Composition over Inheritance
Object oriented design principle 7 - Liskov Substitution Principle (LSP)
Object oriented design principle 8 - Interface Segregation principle (ISP)
Object oriented design principle 9 - Programming for Interface not implementation
Object oriented design principle 10 - Delegation principle

http://javarevisited.blogspot.com/2012/03/10-object-oriented-design-principles.html#ixzz2D4RM6ys7


  • In software engineering, don't repeat yourself (DRY) is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

http://en.wikipedia.org/wiki/DRY_code

Wednesday, November 7, 2012

JPA vs Hibernate


Many enterprise Java developers use lightweight persistent objects provided by open-source frameworks or Data Access Objects instead of entity beans: entity beans and enterprise beans had a reputation of being too heavyweight and complicated, and one could only use them in Java EE application servers. Many of the features of the third-party persistence frameworks were incorporated into the Java Persistence API, and as of 2006 projects like Hibernate (version 3.2) and Open-Source Version TopLink Essentials have become implementations of the Java Persistence API.

JPA is really a specification
Hibernate provides an implementation of the JPA specification. Vendors providing EJB3.0 containers will also be providing an implementation of the JPA spec, so that means Sun and IBM WebSphere and Oracle and all the other handsome players in the industry will provide an implementatio
http://www.coderanch.com/t/218819/ORM/databases/Hibernate-vs-JPA


What is JPA?

JPA is a framework for managing relational data for Java. It can be used with applications utilizing JSE (Java Platform, Standard Edition) or JEE (Java Platform, Enterprise Edition). Its current version is JPA 2.0, which was released on 10 Dec, 2009. JPA replaced EJB 2.0 and EJB 1.1 entity beans (which were heavily criticized for being heavyweight by the Java developer community). Although entity beans (in EJB) provided persistence objects, many developers were used to utilizing relatively lightweight objects offered by DAO (Data Access Objects) and other similar frameworks instead. As a result, JPA was introduced, and it captured many of the neat features of the frameworks mentioned above


What is Hibernate?

Hibernate is a framework that can be used for object-relational mapping intended for Java programming language. More specifically, it is an ORM (object-relational mapping) library that can be used to map object-relational model in to conventional relational model. In simple terms, it creates a mapping between Java classes and tables in relational databases, also between Java to SQL data types. Hibernate can also be used for data querying and retrieving by generating SQL calls. Therefore, the programmer is relieved from the manual handling of result sets and converting objects. Hibernate is released as a free and open source framework distributed under GNU license. An implementation for JPA API is provided in Hibernate 3.2 and later versions.



What is the difference between JPA and Hibernate?

JPA is a framework for managing relational data in Java applications, while Hibernate is a specific implementation of JPA (so ideally, JPA and Hibernate cannot be directly compared). In other words, Hibernate is one of the most popular frameworks that implements JPA. Hibernate implements JPA through Hibernate Annotation and EntityManager libraries that are implemented on top of Hibernate Core libraries. Both EntityManager and Annotations follow the lifecycle of Hibernate. The newest JPA version (JPA 2.0) is fully supported by Hibernate 3.5. JPA has the benefit of having an interface that is standardized, so the developer community will be more familiar with it than Hibernate. On the other hand, native Hibernate APIs can be considered more powerful because its features are a superset of that of JPA.

http://www.differencebetween.com/difference-between-jpa-and-vs-hibernate/#ixzz2BXu2zE00

Statement vs Prepared Statement



  • Statement vs Prepared Statement 


A prepared statement performs the following checks:

    Makes sure that the tables and columns exist
    Makes sure that the parameter types match their columns
    Parses the SQL to make sure that the syntax is correct
    Compiles and caches the compiled SQL so it can be re-executed without repeating these steps


http://stackoverflow.com/questions/8959036/statement-vs-prepared-statement-in-terms-of-precompilation



  • The prepared statement concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.


The advantages of Prepared Statements are:

    As the execution plan get cached, performance will be better.
    It is a good way to code against SQL Injection as escapes the input values.
    When it comes to a Statement with no unbound variables, the database is free to optimize to its full extent. The individual query will be faster, but the down side is that you need to do the database compilation all the time, and this is worse than the benefit of the faster query.

http://webmoli.com/2008/10/23/back-to-basics-statement-vs-prepared-statement/

Tuesday, October 23, 2012

reserved words in java?


The table below lists all the words that are reserved:

abstract assert boolean break byte case
catch char class const* continue default
double do else enum extends false
final finally float for goto* if
implements import instanceof int interface long
native new null package private protected
public return short static strictfp super
switch synchronized this throw throws transient
true try void volatile while
*Even though goto and const are no longer used in the Java programming language, they still cannot be used.

http://java.about.com/od/javasyntax/a/reservedwords.htm

Where is deployment descriptor file located?



  • Deployment descriptor

For web applications, the deployment descriptor must be called web.xml and must reside in the WEB-INF directory in the web application root.

For Java EE applications, the deployment descriptor must be named application.xml and must be placed directly in the META-INF directory at the top level of the application .ear file.
http://en.wikipedia.org/wiki/Deployment_descriptor

Friday, October 12, 2012

What is downcasting in java?


Suppose we have the following Java code in which a downcast is being performed:


class Parent{ /* ... */}

class ChildClass extends Parent { /* ... */ }

public class Tester {

     public static void main (String args[ ]) {
 
      Parent p = new Parent ( );
   
      /*this is a downcast since the Parent class
        object, "p" is being cast to a ChildClass type,
        and ChildClass derives from the Parent class */
   
      ChildClass c = (ChildClass) p;

     }
}



So, in downcasting, you are going down the inheritance diagram by taking an object of a base class (at the top), and then trying to convert into the type of one of the derived classes (going down)

ChildClass c = (ChildClass) p;

So, what happens when the code in our example above is run?

The code above will actually compile, but at runtime it will throw a Runtime Exception (a java.lang.ClassCastException).

If a Java expert would look at the code in our example up above, he or she would definitely know that the code would not work at run-time. So, why does it even compile? Well, remember that the compiler sees things differently from humans – and it thinks that the programmer knows what he is doing. But, in any case, the error is found at run time. By having the cast there (remember the cast is the “(ChildClass) p”), we are telling the compiler that we really do actually want to do this – it is not just a mistake in typing. So, the compiler trusts our judgement. But at runtime Java finds out that the object “p” is of the “ParentClass” type, and it will throw a Runtime Exception.

What if there was no type cast in the code above?
Suppose there is no type cast, and the critical line of code above is changed so that it looks like this:
ChildClass c =  p;

Then this code would give a compile time error instead of a runtime error – because there is no way that an object of the Parent class can ever be downcast to an object of it’s child class.

Is downcasting ever allowed in Java, and when would it be necessary?
Yes, downcasting is allowed in Java – if it wasn’t then the code up above would always return an error at compile time, not just at run-time.

Downcasting is very useful when you need to compare one object to another. An example would help clarify – take a look at the code below:




http://www.programmerinterview.com/index.php/java-questions/downcasting-in-java/





  • Downcasting


In object-oriented programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.
In other words, when a variable of the base class (parent class) has a value of the derived class (child class), downcasting is possible.

For example in Java:

public class Parent{}
public class Child extends Parent(){}

public static void main(String args[]){
    Parent parent = new Child();              // Parent is parent class of Child, parent variable holding value of type Child
    Child child = (Child)parent;              // This is possible since parent object is currently holding value of Child class
}



Most often, you will encounter a need to do downcasting when passing a value in a parameter. So, in another example, let's say we have method objectToString that takes Object which we assume the parameter myObject is String type.

public String objectToString(Object myObject){
    return (String)myObject; //This will only work when the myObject currently holding value is string.
}

public static void main(String args[]){
    String result = objectToString("My String"); //This will work since we passed in String, so myObject has value of String.
    Object iFail = new Object();
    result = objectToString(iFail);              //This will fail since we passed in Object which does not have value of String.
}


The danger of downcasting in this approach is that it's not compile time check, but rather it is run time check



http://en.wikipedia.org/wiki/Downcasting

Wednesday, August 29, 2012

what's scanner class?


The Scanner class is a class in java.util, which allows the user to read values of various types

Class Constructors

There are two constructors that are particularly useful: one takes an InputStream object as a parameter and the other takes a FileReader object as a parameter.

Scanner in = new Scanner(System.in);  // System.in is an InputStream
Scanner inFile = new Scanner(new FileReader("myFile"))

http://www.cs.utexas.edu/users/ndale/Scanner.html

Tuesday, August 14, 2012

hibernate interview questions



  • What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.


  • What are the ORM levels ?

  Pure relational (stored procedure.)
  Light objects mapping (JDBC)
  Medium object mapping
  Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)


  • What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.


  • Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
  Improved productivity
  High-level object-oriented API
  Less Java code to write
  No SQL to write

  Improved performance
  Sophisticated caching
  Lazy loading
  Eager loading

  Improved maintainability
  A lot less code to write
  Improved portability
  ORM framework generates database-specific SQL for you



  • What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.


  • What are the most common methods of Hibernate configuration?

The most common methods of Hibernate configuration are:
  Programmatic configuration
  XML configuration hibernate.cfg.xml (or hibernate.properties)
 
 

  • How do you configure Hibernate?


The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

• hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

• Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files


http://www.javalobby.org/java/forums/t104442.html




  • hibernate optimistic vs pessimistic locking


How does one handle the fact that 2 people want to update the same record at the same time?

1. Do Nothing
- User 1 reads a record
- User 2 reads the same record
- User 1 updates that record
- User 2 updates the same record
User 2 has now over-written the changes that User 1 made. They are completely gone, as if they never happened. This is called a 'lost update'.

2. Lock the record when it is read. Pessimistic locking
- User 1 reads a record *and locks it* by putting an exclusive lock on the record (FOR UPDATE clause)
- User 2 attempts to read *and lock* the same record, but must now wait behind User 1
- User 1 updates the record (and, of course, commits)
- User 2 can now read the record *with the changes that User 1 made*
- User 2 updates the record complete with the changes from User 1
The lost update problem is solved. The problem with this approach is concurrency. User 1 is locking a record that they might not ever update. User 2 cannot even read the record because they want an exclusive lock when reading as well.

3. Use Optimistic Locking. Optimistic locking does not use exclusive locks when reading. Instead, a check is made during the update to make sure that the record has not been changed since it was read. This can be done by checking every field in the table
*Most* people implement this, instead, through a single column, usually called timestamp. This column is used *for no other purpose* than implementing optimistic concurrency. It can be a number or a date. The idea is that it is given a value when the row is inserted. Whenever the record is read, the timestamp column is read as well. When an update is performed, the timestamp column is checked. If it has the same value at UPDATE time as it did when it was read, then all is well, the UPDATE is performed and *the timestamp is changed!*. If the timestamp value is different at UPDATE time, then an error is returned to the user - they must re-read the record, re-make their changes, and try to update the record again

http://www.dbasupport.com/forums/showthread.php?7282-What-is-Optimistic-Locking-vs.-Pessimistic-Locking



You add a version field to your table and a version element to your mapping file. When you update a Hibernate object Hibernate will check the version values match. If they do the update is successful, and the version is incremented, if they are not Hibernate throws a StaleObjectException and you know that something else has updated your data.

Pessimistic locking is provided by specifying a LockMode when you get an object from the database.
Hibernate will use database specific SQL to lock the record (if your database supports it) such as "select ... for update".
Now nothing can update that record till you are finished.
http://www.coderanch.com/t/216247/ORM/databases/Optimistic-Pesimistic-locking


"Optimistic locking" is more scalable than pessimistic locking when dealing with a
highly concurrent environment

pessimistic locking is a better solution for situations where the possibility of simultaneous updates to the same data by multiple sources
(for example, different applications use same database to update) is common, hence making the possibility of "data clobbering" , a
likely scenario.

Pessimistic locking is when you want to reserve a record for exclusive update by
locking the database record(entire table). Hibernate supports pessimistic locking
(using the underlying database, not in-memory) via one of the following methods:

1. Session.get
2. Session.load
3. Session.lock
4. Session.refresh
5. Query.setLockMode


Optimistic locking means that you will not lock a given database record or table and
instead check a property of some sort (for example, a timestamp column) to
ensure the data has not changed since you read it. Hibernate supports this using a
version property, which can either be checked manually by the application or automatically
by Hibernate for a given session

http://javacompleteexamples.blogspot.com/2009/07/how-db-locking-system-works-in.html


Tuesday, July 3, 2012

What is synchronization?



  • What is synchronization? 

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.
In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.
Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.

Can a class be synchronized?
No

Tuesday, June 26, 2012

Difference Between List and ArrayList ?


List is an interface and ArrayList is an implementation of the List interface.
The arraylist class has only a few methods in addition to the methods available in the List interface
http://www.javabeat.net/qna/9-difference-between-list-and-arraylist-/