Tag Archives: java

Closure in Java

According to Tom Hawtin

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.

Pasted from <http://en.wikipedia.org/wiki/Closure_%28computer_science%29>

 JSR Proposal: Closures for Java

Summary: Add support so programs can operate on an arbitrary block of code with parameters, and simplify the use of methods that receive such blocks.

This JSR provides support for operating on an arbitrary “block of Java code”, or body, which is either a statement list, an expression, or a combination of both. We call the mechanism a closure expression. Wrapping statements or an expression in a closure expression does not change their meaning, but merely defers their execution. Evaluating a closure expression produces a closure object. The closure object can later be invoked, which results in execution of the body, yielding the value of the expression (if one was present) to the invoker. A closure expression can have parameters, which act as variables whose scope is the body. In this case the invoker of the closure object must provide compatible arguments, which become the values for the parameters.

In addition, this JSR may support a new invocation statement for methods that accept a closure to simplify their use in common cases.

Pasted from <http://www.javac.info/consensus-closures-jsr.html>

Since Java 1.1, anonymous inner class have provided this facility in a highly verbose manner. They also have a restriction of only being able to use final (and definitely assigned) local variables. (Note, even non-final local variables are in scope, but cannot be used.)

Java SE 8 is intended to have a more concise version of this for single-method interfaces*, called “lambdas”. Lambdas have much the same restrictions as anonymous inner classes, although some details vary randomly.

Lambdas are being developed under Project Lambda and JSR 335.

*Originally the design was more flexible allowing Single Abstract Methods (SAM) types. Unfortunately the new design is less flexible, but does attempt to justify allowing implementation within interfaces.

Pasted from <http://stackoverflow.com/questions/5443510/closure-in-java-7

References:

http://tronicek.blogspot.ae/2007/12/java-closures-tutorial.html

Bringing Closures to Java 5, 6 and 7 – http://mseifed.blogspot.se/2012/09/bringing-closures-to-java-5-6-and-7.html

Page Visitors: 299

Java Interview Questions – Java Concepts

  • What are the different types of memory areas allocated by JVM?
    • Class (Method) Area – stores per-class structures like fields, method data, method code and constant pool.
    • Heap – runtime area where the actual objects reside.
    • Stack – holds local variables and partial results and plays a pivotal role in method invocation and return. For each thread created, private JVM stack is being created and maintained. It stores each method invocation in the form of a frame and its destroyed soon after the method invocation is complete.
    • Program Counter (PC) Register – it contains the currently executed Java Virtual Machine instruction.
    • Native Method Stack – contains all the native method used in the application.
  • What makes Java software-based platform to be called as “write once run anywhere”?

Because of the program being compiled into bytecode and this bytecode being run inside a runtime environment (JVM) makes this software-based platform able to run on top of other hardware-based platforms. The JVM though is platform dependent and is available for various hardware-platforms available.

  • Does Java support multiple inheritance?

Theoretically on the class level Java doesn’t support multiple inheritance to avoid complexity and with the aim of simplifying the language. Having said that using interfaces it does support multiple inheritance and is widely used.

  • What is Association, Aggregation and Composition?

I wouldn’t want to reinvent and write answer for this question, rather I would point you directly to this link here.

  • What is meant by Abstraction, Generalization, Realization and Dependency?

Again read the link here and you will get all the relevant details.

Page Visitors: 439

Java Interview Questions – Error and Exception Handling

  • What is Exception chaining in Java?

One of the important exception handling concept in Java when a different exception is thrown in response to an actual exception. This in turn will create a chain of exceptions. This is commonly used to wrap a checked exception to unchecked exception under various scenarios and such coding prevails when actually writing a framework in which case a known checked exception is thrown as an unchecked framework exception. Even though new exception is thrown, as a best practise always include the root cause (exception) in the newly created exception class.

  • With regards to JDK7 there is a new feature with regards to Exception handling. Can you detail this?

There are numerous small and medium new features on JDK7 which are very useful. Some of them with regards to error and exception handling is as detailed below:-

    • Multiple exception handling in one catch block

Reduces code cluttering and are more readable.

    •  ARM (Automatic Resource Management) blocks

As the name suggests it is capable of automatically handling resources on behalf of you, also known popularly as try with resource. Takes lot of botheration away from developers. Below is the example from oracle java docs:

Page Visitors: 1620

Java Interview Questions – Collections

  • What is the key requirement for an object to be used as a key in hash based collection e.g. HashMap or Hashtable or ConcurrentHashMap?

The object should implement both equals() and hashcode() methods.

  • What are immutable classes in Java? How to make immutable class in Java?

Immutable classes are classes, whose objects once created cannot be modified once created. Any modification to these immutable objects will result in another immutable object. Example classes are String and StringBuffer classes in Java.

To make an immutable class the class should be made final. All the fields in the class should also be made final and utmost care should be taken so as to ascertain that object reference must not leak during construction phase of the object.

  • What happens internally when you invoke get(Key key) method in hash based collections like HashMap and Hashtable?

The following steps happen:

      • The Key.hashcode() method gets invoked to get the bucket location in the array backed Hash collections.
      • In the backing array the keys and values are stored in an internal class called as Entry. If there is only one Entry at the bucket location, the value is returned. If due to some reasons two keys have same hashcode (this happens), the bucket location will have two entries and it forms a sort of a linked list data structure. In that case, it traverses through the list comparing keys in each entry using keys.equals() until it return true. Once true is returned, the value is returned.
  • Why should an object which is to be used as key in collection classes need to be immutable?

This is required because the hashcode() method when being called should always return the same value.

  • Have you heard of ConcurrentHashMap, if so what is it?

This is an alternative to Hashtable in Java and as the name suggests, it is synchronized, thread safe and highly usable in multi-threaded programming.

  • How to make HashMap synchronized in nature?

You can use Collections.synchronizedMap(HashMap). This will return a collection very much similar to Hashtable.

  • What are the difference/similarities between HashSet and TreeSet?

Some of the difference are:-

    • HashSet is faster than TreeSet with regards to performance.
    • HashSet doesn’t preserve ordering but TreeSet does.
    • HashSet allows null objects but TreeSet doesn’t.
    • HashSet is backed by HashMap and TreeSet is backed by TreeMap.

Some of the similarities are:-

    • Both are thread-safe and synchronized in nature.
    • Both implement Set interface

Reference:-

Awesome post (Hats Off) – http://java67.blogspot.ae/2013/07/15-advanced-core-java-interview-questions-answers-senior-experienced-5-6-years-programmers-developers.html

Page Visitors: 998

Spring Book – Chapter 17 – Messaging with Spring

Messaging is a method of communication between software components or applications. Messaging enables distributed communication that is “loosely coupled” (decoupled). A component sends a message to a destination, and the recipient can retrieve the message from the destination. The important thing here is that, the sender and the receiver do not have to be available at the same time in order to communicate with each other.

Java Message Service (JMS) defines a standard way for Java applications to create and exchange messages through a Message Oriented Middleware (MOM).

Messaging is one of the key components in any modern day application development. In this Chapter we will initially cover messaging concepts in some detail. Later on we will cover JMS and its components in detail. We will then deep-dive into the support provided by Spring in applying messaging to your application. We will then go through the transaction support by JMS and again what Spring has to offer in this space. Finally, the Chapter concludes with a discussion of Spring’s support in achieving global transactions in your application.

Messaging in General

Messaging systems are used to build highly reliable, scalable, and flexible distributed applications. A messaging system allows separate, uncoupled applications to reliably do the communication asynchronously. The messaging system architecture generally replaces the client/server model with a peer-to-peer relationship between individual components, where each peer can send and receive messages to and from other peers.

Messaging systems provide a host of powerful advantages over other, more conventional distributed computing models. Primarily, they encourage “loose coupling” between message consumers and message producers. Other advantages of messaging systems include high scalability, easy integration with other heterogeneous networks, and reliability due to lack of a single point of failure.

Messaging is another integration style as detailed in Chapter 6.  Systems exchange messages within each other using a component known  as a broker, which provides the necessary guarantee and services while using messaging along with capability of interfacing with other interfaces like JMS driver, AMQP (Advanced Message Queuing Protocol), Stomp (Simple Text Oriented Message Protocol), XMPP (Extensible Messaging and Presence Protocol) etc. These interfaces are often referred to as Message Oriented Middleware (MOM) and are available as commercial and open source products in the market. Figure 18-1 shows a diagram of a MOM-based messaging system.

fig18-01

Figure 18-1. Messaging using MOM

Message-oriented middleware (MOM) is software or hardware infrastructure supporting sending and receiving messages between distributed systems. MOM allows application modules to be distributed over heterogeneous platforms and reduces the complexity of developing applications that span multiple operating systems and network protocols, such as the following:

  • Simple (or Streaming) Text Orientated Messaging Protocol (STOMP) provides an interoperable wire format so that STOMP clients can communicate with any STOMP message broker to provide easy and widespread messaging interoperability among many languages, platforms and brokers.
  • Advanced Message Queuing Protocol (AMQP) is an open standard application layer protocol for message-oriented middleware. It’s a binary, application layer protocol, designed to efficiently support a wide variety of messaging applications and communication patterns.
  • Extensible Messaging and Presence Protocol (XMPP) is an open-standard communications protocol for message-oriented middleware based on XML (Extensible Markup Language). The protocol was originally named Jabber, and was developed by the Jabber open-source community.

Advantages of Messaging

The main advantages of using messaging as an integration technology in your application can be summarized as below:

  • Platform Independence – one of the biggest advantages which messaging integration style brings onto table is communication and integration of heterogeneous platforms. Using messaging it is possible to integrate applications and systems which are implemented in completely different platforms. Even though we have many ways of integrating heterogeneous platforms like RPC-based, common database etc., only messaging truly provides a decoupled way of interaction between such disparate systems.
  • Network location Independence -messaging also provides capability of connections applications and systems in completely different networks with ease.
  • Architecture Flexibility and Agility – this very important advantage of messaging is achieved through level of abstraction and decoupling capabilities. Because of decoupled components, these can be replaced with a more capable component at a later stage with ease giving application flexibility and agility to changing business scenarios. In a typical messaging environment, the various components like producers, consumers and client components doesn’t need to know which programming language or platform these are written for, where they are located and even the protocol they used to communicate. These details are all abstracted away, making it more flexible from the architecture point of view.
  • Reduce system bottleneck – asynchronous nature of messaging is the key in avoiding system bottlenecks. Since messaging architecture gives your application asynchronous nature, your receivers need not keep up with the rate of requests coming in reducing the system bottlenecks. In a synchronous environment, your application would have resulted in system bottlenecks if the number of requests exceeds a particular amount which the consumer can consume and process.

Using traditional RPC-based technologies, there is a synchronous communication between a client and a server component. Also, communication between many to many can over a period of time turn into a mesh of one to one communication between various components as shown in Figure 18-2 below. This meshing can be troublesome from the application maintainability point of view.

Figure 18-2. Traditional RPC-based application component interaction

Figure 18-2. Traditional RPC-based application component interaction

On the other hand using a messaging style of integration allows adding a mediation layer between one or more consumers and one or more producers. This result in clear communication between various components which has a clear interface with other components interacts, making it easy to swap the various components according to application requirement. Figure 18-3 shows message-based component interaction.

Figure 18-3. Using messaging-based application component interaction

Figure 18-3. Using messaging-based application component interaction

Page Visitors: 16695

Spring and Hibernate Example

The beauty of Spring is that it can integrates well with most of the prevailing popular technologies, and in the case of ORM, it integrates well with Hibernate.

I have written a Spring Book and in Chapter 8 i explain Spring’s Data Access capabilities in detail. There is separate topics written on ORM integration and this specific heading namely “Spring and Hibernate” is dedicated for explaining this beautiful integration between two open-source framework.

Please visit Page 9 in Chapter 8 of my Spring Book for more details on the same.

This section of the chapter examines the means by which Spring can be integrated with Hibernate. I assume that the reader is somewhat familiar with Hibernate and by reading this far familiar with Spring Framework as well to some extend.

ORM is a piece of software/product for the representation and conversion of data between the database and the object-oriented programming language. Hibernate is a powerful technology for persisting data and is a clear winner in the ORM race as of now. However it hasn’t become a standard. It takes much of the database related boiler-plate code from the developers, thereby asking the developers to concentrate on the core business logic of the application and not with the error-prone SQL syntax. It also enables application to access data from any database in a platform-independent manner.

One of the problems with using Hibernate is that the client Application that accesses the database using Hibernate Framework has to depend on the Hibernate APIs. These objects will continue to get scattered across the code throughout the Application. Above all, the application code has to manually maintain and manage these objects. Here comes Spring to the rescue with its IoC container capable of configuring these objects using Spring configurations.

 

Page Visitors: 571

What is rt.jar? What constitutes JDK and JRE?

For a beginner, this will be one of the question which they might have. For an expert even though this is well known jar file in Java, very few will know as to what it is and why it is so important. This blog post is a very short post, just giving some details of what rt.jar is and what constitutes Java as a whole (JDK/JRE).

rt.jar contains all the RunTime classes that comprise the Java SE platform’s core API’s. In simple terms this is the jar which contains classes like java.lag.String, java.io package etc. The source code for these API’s can be found in src.zip file in JAVA_HOME.

Since all the classes in the rt.jar are known to the JVM, these classes tend to be left alone with various checks that JVM does while loading these classes onto it. This is also done for various performance reasons. These jars are loaded by primodial class loaders and that’s the reason these classes avoid the basic security checks which the JVM does for other jars/classes.

The base files and folders in the JDK/JRE is shown in the below figure.

JDK-JREFiles

Image Courtesy – docs.oracle.com

For more details on all the various files and directories comprising JDK and JRE, i would suggest going through the official Oracle documentation as follows:

http://docs.oracle.com/javase/6/docs/technotes/tools/windows/jdkfiles.html

As pointed out by one of the reader, since the above link is no longer maintained, the below link which details JDK 1.7 is given:

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdkfiles.html

 

Page Visitors: 8292