Q. Why do interviewers like multi-threading interview questions? A. Because it is not easy, but very essential to write scalable and high throughput systems.

If you are going for Java interviews to work on large scale systems, expect multi-threading interview questions. These are more beginner or fresher level questions and if you are already good with the basics, try more intermediate to advanced level coding questions and answers on Java multi-threading at Java multi-threading-1 | Java multi-threading-2

Q. What is the difference between processes and threads? A. A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.

A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.

Q. Explain different ways of creating a thread?A. Threads can be used by either

Q. Which one would you prefer and why?A. The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the threads are started in each of the different cases as shown in the code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior. By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.

Runnable — A thread becomes runnable when you call the start( ), but does not necessarily start running immediately. It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.

Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.

Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.

Blocked on synchronization: will move to running when a lock is acquired.

Dead: The thread is finished working.

Thread.State enumeration contains the possible states of a Java thread in the underlying JVM. These thread states are possible due to Java's following thread concepts:

The objects can be shared and modified (i.e. if mutable) by any threads.

The preemptive nature of the thread scheduler can swap threads on and off cores in a multi-core CPU machine at any time.

This means the methods can be swapped out while they are running. Otherwise a method in an infinite loop will clog the CPU forever leaving the other methods on different threads to starve.

To prevent thread safety issues, the methods and block of code that has vulnerable data can be locked.

This enables the threads to be in locked or waiting to acquire a lock states.

The threads also get into the waiting state for I/O resources like sockets, file handles, and database connections.

The threads that are performing I/O read/write operations can not be swapped. Hence, they need to either complete to the finished state with success/failure or another thread must close the socket for it to get to the state of dead or finished. This is why proper service timeout values are necessary to prevent the thread to get blocked for ever in an I/O operation, causing performance issues.

The threads can be put to sleep to give other threads in waiting state an opportunity to execute.

Q. What is the difference between yield and sleeping? What is the difference between the methods sleep( ) and wait( )? A. When a task invokes yield( ), it changes from running state to runnable state. When a task invokes sleep ( ), it changes from running state to waiting/sleeping state.

The method wait(1000) causes the current thread to wait up to one second a signal from other threads. A thread could wait less than 1 second if it receives the notify( ) or notifyAll( ) method call. The call to sleep(1000) causes the current thread to sleep for t least 1 second.

Q. Why is locking of a method or block of code for thread safety is called "synchronized" and not "lock" or "locked"?A. When a method or block of code is locked with the reserved "synchronized" key word in Java, the memory (i.e. heap) where the shared data is kept is synchronized. This means,

When a synchronized block or method is entered after the lock has been acquired by a thread, it first reads any changes to the locked object from the main heap memory to ensure that the thread that has the lock has the current info before start executing.

After the synchronized block has completed and the thread is ready to relinquish the lock, all the changes that were made to the object that was locked is written or flushed back to the main heap memory so that the other threads that acquire the lock next has the current info.

This is why it is called "synchronized" and not "locked". This is also the reason why the immutable objects are inherently thread-safe and does not require any synchronization. Once created, the immutable objects cannot be modified.

Q. How does thread synchronization occurs inside a monitor? What levels of synchronization can you apply? What is the difference between synchronized method and synchronized block? A. In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level (coarse grained lock – can affect performance adversely) or block level of code (fine grained lock). Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization. The block level is more efficient because it does not lock the whole method.

The JVM uses locks in conjunction with monitors. A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. For static methods, you acquire a class level lock.

When to use a builder design pattern? real life tips

Interview questions relating to design patterns are very popular in job interviews. Even if this topic is not covered in rare occassions, you can bring it up yourself to open-ended questions to impress your interviewers.Q. What are the key difference(s) between a factory and a builder design patterns?A. The builder design patternbuilds an object over several steps. It holds the needed state for the target item at each intermediate step. The StringBuilder is a good example that goes through to produce a final string. Here is a real world example that shows how builders are used instead of constructors to create Immutable objects. Creating immutable objects where applicable is a development best practice.

To construct a complex object. For example, to construct XML DOM objects and any other hierachichal objects. You have to create plenty of nodes and attributes to get your final object.

Builder pattern makes your code more readable as explained in the article "Using Builders instead of Constructors to create Immutable objects". The article explains how you can create immutable objects in Java by using the builder design pattern as opposed to using multiple constructors, which is known as the "telescoping constructor anti pattern".Firstly, let's see what is not so elegant about using a constructor as shown below with a CashBalance object that takes 3 BigDecimal arguments. Then we will see how a builder class will make your code more intuitive.

Sep 18, 2013

AngularJS communicating between controllers

The previous posts covered AngularJS big picture : Overview and Working with Angular JS and jQuery UI : writing a custome directive. Let's look at inter controller communication in this blog post.Q. How do you communicate between controllers in AngularJS?A. There are scenarios where you want to communicate between controllers. For example, when the submit button is clicked on the parent controller, some values need to be passed to the child controller to show or hide a button in the child form. In AngularJS you can do this with $watch and $broadcast on the parent controller and $on on the child controller.

Sep 17, 2013

Sorting objects in a collection key in presenting those objects in GUI or report like PDF, etc. In Java you use a Comparator interface or the Comparable interface to define the custom sorting logic. I hava covered this in a number of following blog posts.

Recently, I had the opportunity to work with a number of Google Guava libraries and its comparator came handy to write a more concise code to get the same thing done. Working with Java Collection using Gauva was covered with examples.

Step 2: Here is a sample ReportKey value object class that uses Apache common librarie's utility methods for equals( ), hashCode( ), toString( ), and compareTo( ) methods. Implementing the Comparable interface and providing the compareTo method provides natural ordering for the ReportKey class. It is also a best pracrice to define your key class as an immutable object. Defensive copying is used to make it immutable.

Step 3: The above natual ordering sorts by clientId and valuationDate in ascending order. What if you ant to sort it by clientId in ascending order and by valuationDate in descending order? Here is sample anonymous class using Google's Gauva library.

Sep 16, 2013

AngularJS big picture : Overview

This is for the AngularJS starters. You will see handy diagrams and third-party links to get started with Angular JS, which is getting so much attention.Q. Can you give a big picture of AngularJS highlighting its key components?A. A good diagram is worth 1000 words.

Q. What is a scope in AngularJS?A. scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events.

Q. Can you explain the concept of scope hierachy? How many scopes can an application have?A. Each Angular application has exactly one root scope, but may have several child scopes. The application can have multiple scopes, because child controllers and some directives create new child scopes. When new scopes are created, they are added as children of their parent scope. This creates a hierarchical structure similar to the DOM where they're attached.

When Angular evaluates a bound variable like say {{firstName}}, it first looks at the scope associated with the given element for the firstName property. If no such property is found, it searches the parent scope and so on until the root scope is reached. In JavaScript this behaviour is known as prototypical inheritance, and child scopes prototypically inherit from their parents. The reverse is not true. I.e. the parent can't see it's children's bound properties.

Sep 12, 2013

AngularJS is a popular MVW (Model View Whatever) framework. Recently had an opportunity to test drive Angular JS for GUI development retrieving data via RESTful web service calls. The JavaScript based GUI frameworks like Angular JS, Backbone, etc will becom more poular and replace JSF. So, it really pays off to lean AngularJS if you like developing GUIs. If you go to YouTube, you will find a number of good beginner's tutorials to get started.

Q. What is a directive in AngularJS?A. Directives extends HTML. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behaviour, or transform the DOM. ng-app, ng-controller, ng-model, etc are directives. The directives can be placed in element names, attributes, class names, as well as comments. Directives are defined with camel cased names such as ngApp and invoked by translating the camel case name into snake case with these special characters :, -, or _. For example ng-ap p as in <html ng-app>

Q. When do you need to create your own directives? How will you go about creating a custom directive in AngularJS?A. There are instances where you want to use jQuery UI plugins. Reecently, I had to use the the jQuery Resizable plugin with angular to resize my TextArea in IE 8 as it is the standard browser used by our business and operational staff. Here are some code samples to get AngularJS and jQuery to work together. By default, the Angular JS is shipped with a lite version of jQuery, but not with the UI plugins.

Step 1: You need to define directives. Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. I am using RequireJS to manage dependencies. here is myTextAreaWithModel.js file

A theme is an objective that may span projects and products. Themes can be broken down into sub-themes, which are more likely to be product-specific. At its most granular form, a theme can be an epic.

An epic is a group of related user stories. An epic needs to be broken down into a user story before it is sized using fibonacci number (eXtra Smal [XS=1 pt] Small [S = 2 pt], Medium [M = 3], Large (L = 5), XtraLarge (XL = 8) , XtraXtraLarge [XXL = 13pts], XtraXtraXtraLarge [XXXL = 21 pts] ) and introduced into a sprint. The sizing is similar to the T-shirt sizes. These points are also known as the velocity points to monitor progress.

A user story is an Independent, Negotiable, Valuable, Estimatable, Small, Testable requirement, which is abbreviated to “INVEST”. Even though stories are independent, they have no direct dependencies with other requirements and user stories may be combined into epics when represented on a product road map. User stories need to be defined prior to sprint planning in ABC (Accelerated Business Case) sessions where the development teams, QA (i.e. testing) teams and product managers can use them to discuss, size and prioritise at sprint-level. User stories will often be broken down into tasks during the sprint planning Process unless the stories are small enough to be consumed on their own. Tools like "MindMap" is used to capture the stories in the form of COS (i.e. Condition Of Staisfaction).

The sized cards are prioritized interms of its value add to achieve the MVP (Minimum Viable Product) defined by the product manager and the business owners.

Q. How is an agile project monitored for progress?A. Any one who has worked on an agile project would have come across thes key terms:

Colocation

Frequent delivery

Daily standups

Timeboxed tasks

The best evidence that a software project is on track is working software, preferably deployed to production.

Secondly, a burn down chart is used to present the progress to the management. Each sprint is basically 2 weeks and this is plotted on the X axis. The Y axis will have the velocity points. In each Sprint depending on the team size, a number of sized up cards are picked and the individual points are added up. For example say, 40 points. This chart is about how quickly you burn through the stories. These graphs can be plotted manually or via tools like Excel spreadsheet or JIRA.

Velocity is the key to agile project management.

Q. What are different roles in an agile project?A.

Mandatory roles:

Team lead: This role, called “Scrum Master” in Scrum or team coach or project lead in other methodsTeam member: This role, sometimes referred to as developer or programmer, is responsible for the creation and delivery of a system. This includes modeling, programming, testing, and release activities, as well as others.Product owner: The product owner is responsible for the prioritized work item listStakeholder: is anyone who is a direct user, indirect user, manager of users, senior manager, and operations staff member.

Optional roles that are typically adopted only on very complex projects

Technical experts: Sometimes the team needs the help of technical experts, such as build masters to set up their build scripts or an agile DBA to help design and test their database.Domain experts: Sometimes the product owner will sometimes bring in domain experts to work with the teamIndependent tester: to validate functional and non-functional testing. For example, security testing, performance testing, cross browser compatibility testing, etc.

Sep 9, 2013

Web (i.e. HTTP) security vulnerabilities - HttpOnly attribute

Q. What do you understand by the term "HttpOnly" attribute in HTTP cookies?A. Here is a sample PEN test report comment:

"During the application test, it was detected that the tested web application set a session cookie without the "HttpOnly" attribute. Since this session cookie does not contain the "HttpOnly" attribute, it might be accessed by a malicous script injected to the site (i.e XSS), and its value can be stolen. Any information stored in session tokens may be stolen and used later for identity theft or user impersonation"

When you tag a cookie with the "HttpOnly" flag, it tells the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly forbidden. This will works woth a modern web browser that supports and actually implements "HttpOnly" functionality correctly. The most modern browsers do support the "HttpOnly" flag. This flag will make more difficult to pull off XSS attacks.

Q. What do you understand by the term "Secure" attribute in HTTP cookies?A. Here is a sample PEN test report comment:

"During the application test, it was detected that the tested web application set a cookie without the "secure" attribute, during an encrypted session. Since this cookie does not contain the "secure" attribute, it might also be sent to the site during an unencrypted session. Any information such as cookies, session tokens or user credentials that are sent to the server as clear text, may be stolen and used later for identity theft or user impersonation."

Remedy: Basically the only required attribute for the cookie is the "name" field. Common optional attributes are: "comment", "domain", "path", etc. The "secure" and "HttpOnly" attributes must be set accordingly in order to prevent a cookie from being sent unencrypted or modified respectively.

Tip: You can use the Firefox plugin Fire cookie to view these attributes.