Sunday, January 22, 2012

Functional Programming on the JVM

Java8 Lambda Expression
Java has finally realized the power of writing code in functional style and is going to support the concept of closures starting from Java8. JSR 335 - Lambda Expressions for the JavaTM Programming Language aims to support programming in a multicore environment by adding closures and related features to the Java language. So it will finally be possible to pass around functions similar to variables in pure Java code.
Currently if someone wants to try out and play around lambda expressions, Project Lambda of OpenJDK provides prototype implementation of JSR-335. Following code snippet should run fine with OpenJDK Project Lambda compiler.

ExecutorService executor = Executors.newCachedThreadPool();

executor.submit(() -> {System.out.println("I am running")})
 
As can be seen above, a closure(function) has been passed to executor's submit method. It does not take any argument and hence empty brackets () have been placed. This function just prints "I am running" when executed. Just as we can pass functions to function, it will also be possible to create closure within functions and return closure from function. I would recommend to try out OpenJDK to get a feel of lambda expressions which is going to be part of Java8.

Conclusion

So this was all about functional programming, it's concepts, benefits and options available on JVM to write function code. Functional programming requires a different mind-set and can be very useful if used correctly. Functional Programming along with Object Oriented Programming can be a jewel in crown. As discussed there are various options available to write code in functional style that can be executed on JVM. Choice depends on various factors and there is no one language that can be considered best in all aspects. However one thing is for sure, going forward we are going to see more and more usage of functional programming.
 

Saturday, January 21, 2012

Functional Programming on the JVM

Groovy
Groovy is again a dynamic language with some support for functional programming. Amongst the 3 languages, Groovy can be considered weakest in terms of functional programming features. However because of it's dynamic nature and close resemblance to Java, it has been widely accepted and considered good alternative to Java. Groovy does not provide immutable objects out of the box but has excellent support for higher order functions. Immutable objects can be created with annotation @Immutation, but it's far less flexible than immutablity support in Scala and Clojure. In Groovy functions can be passed around just as any other variable in the form of Closures. The same example in Groovy can be written as follows

def numbers = [1,2,3,4,5,6,7,8,9,10]

def total = numbers.inject(0){a,b ->

    a+b
}
 
However the point to be noted is that variables "numbers" and "total" are not immutable and can be modified at any point of time. Hence writing multithreaded code can be a bit challenging. But Groovy does provide the concept of Actors, Agents and DataFlow variables via library called GPars(Groovy Parallel System) which reduces the challenges associated with multithreaded code to a greater extent.

Friday, January 20, 2012

Functional Programming on the JVM

Clojure

Clojure is a dynamic language with an excellent support for writing code in functional style. It is a dialect of "lisp" programming language with an efficient and robust infrastructure for multithreaded programming. Clojure is predominantly a functional programming language, and features a rich set of immutable, persistent data structures. When mutable state is needed, Clojure offers a software transactional memory system and reactive Agent system that ensure clean, correct multithreaded designs. Apart from this since Clojure is a dynamic language, it allows to modify class definition at run time by adding new methods or modifying existing one at run time. This makes it different from Scala which is a statically typed language.
Immutability is in the root of Clojure. To create immutable list just following needs to be done. By default list in Clojure is immutable, so does not require any extra effort.

(def numbers (list 1 2 3 4 5 6 7 8 9 10))
 
To add numbers without maintaining state, reduce function can be used as mentioned below
 
(reduce + 0 '(1 2 3 4 5 6 7 8 9 10))
 
As can be seen, adding list of numbers just requires one line of code without mutating any state. This is the beauty about functional programming languages and plays an important role for parallel execution.

Thursday, January 19, 2012

Functional Programming on the JVM

Scala
Scala is a statically typed multi-paradigm programming language designed to integrate features of object oriented programming and functional programming. Since it is static, one cannot change class definition at run time i.e. one cannot add new methods or variables at run-time. However Scala does provide functional programming concepts i.e. immutability, higher-order functions, nested functions etc. Apart from supporting Java's concurrency model, it also provides concept of Actor model out of the box for event based asynchronous message passing between objects. The code written in Scala gets compiled into very efficient bytecode which can then be executed on JVM.
Creating immutable list in Scala is very simple and doesn't require any extra effort. "val" keyword does the trick.
 
val numbers = List(1,2,3,4)

Functions can be passed as arguments. Let's see this with an example.
Suppose we have a list of 10 numbers and we want to calculate sum of all the numbers in list.

val numbers = List(1,2,3,4,5,6,7,8,9,10)

val total = numbers.foldLeft(0){(a,b) =>

    a+b

}
As can be seen in above example, we are passing a function to add two variables "a" and "b" to another function "foldLeft" which is provided by Scala library on collections. We have also not used any iteration logic and temporary variable to calculate the sum. "foldLeft" method eliminates the need to maintain state in temporary variable which would have otherwise be required if we were to write this code in pure Java way (as mentioned below).
 

int total = 0;

for(int number in numbers){

    total+=number;

}
Scala function can easily be executed in parallel without any need for synchronization since it does not mutate state.
This was just a small example to showcase the power of Scala as functional programming language. There are whole lot of features available in Scala to write code in functional style.
 

Wednesday, January 18, 2012

Functional Programming on the JVM

JVM based Functional Programming Languages
There are many JVM based languages which supports functional programming paradigm. However I intend to limit discussion around following.
  • Scala
  • Clojure
  • Groovy
  • Lambda Expressions in Java 8
Lambda Expressions is not a programming language but a feature that will be supported in Java8. The reason for including it in this article is to emphasize on the fact that going forward Java will also support writing code in functional style.

Tuesday, January 17, 2012

Functional Programming on the JVM

What is Functional Programming?
Functional Programming is a concept which treats functions as first class citizens. At the core of functional programming is immutability. It emphasizes on application of functions in contrast to imperative programming style which emphasizes on change in state. Functional programming has no side effects whereas programming in imperative style can result in side-effects. Let's elaborate more on each of these characteristics to understand the concept behind functional programming.
  • Immutable state - The state of an object doesn't change and hence need not be protected or synchronized. That might sound a bit awkward at first, since if nothing changes, one might think that we are not writing a useful program. However that's not what immutable state means. In functional programming, change in state occurs via series of transformations which keeps the object immutable and yet achieves change in state.
  • Functions as first class citizens - There was a major shift in the way programs were written when Object oriented concepts came into picture. Everything was conceptualized as object and any action to be performed was treated as method call on objects. Hence there is a series of method calls executed on objects to get the desired work done. In functional programming world, it's more about thinking in terms of communication chain between functions than method calls on objects. This makes functions as first class citizens of functional programming since everything is modelled around functions.
  • Higher-order functions - Functions in functional programming are higher order functions since following actions can be performed with them.
1.      Functions can be passed within functions as arguments.
2.      Functions can be created within functions just as objects can be created in functions
3.      Functions can be returned from functions
  • Functions with no side-effects - In functional programming, function execution has no side-effects. In other words a function code will always return same result for same argument when called multiple times. It doesn't change anything outside its boundaries and is also not affected by any external change outside it's boundary. It doesn't change input value and can only produce new output. However once the output has been produced and returned by function, it also becomes immutable and cannot be modified by any other function. In other words, they support referential transparency i.e. if a function takes an input and returns some output, multiple invocation of that function at different point of time will always return same output as long as input remains same. This is one of the main motivations behind using functional language as it makes easy to understand and predict behaviour of program.
Characteristics like immutability and no side-effects are extremely helpful while writing multi-threaded code and developers need not to worry for synchronizing the state. Hence functional code is very easy to distribute across multiple cores as they don't have any side effects.

Monday, January 16, 2012

Functional Programming on the JVM

Why Functional Programming?
Computers of current era are shipped with multicore processors. Going forward the number of processors in a machine is only going to increase. The code we write today and tomorrow will probably never run on a single processor system. In order to get best out of this, software must be designed to make more and more use of concurrency and hence keep all available processors busy. Java does provide concurrency concepts like threads, synchronization, locks etc. to execute code in parallel. But shared memory multi-threading approach in Java causes more trouble than solving the problem.
Java based functional programming languages like Scala, Clojure, Groovy etc. looks into these problems with a different angle and provides less complex and less error-prone solutions as compared to imperative programming. They provide immutability concepts out of the box and hence eliminate need of synchronization and associated risk of deadlocks or livelocks. Concepts like Actors, Agents and DataFlow variables provide high level concurrency abstraction and makes very easy to write concurrent programs

Sunday, January 15, 2012

Functional Programming on the JVM

Introduction
In recent times, many programming languages that run on JVM have emerged. Many of these languages support the concept of writing code in a functional style. Programmers have started realizing the benefits of functional programming and are beginning to rediscover the powerful style of this programming paradigm. The emergence of multiple languages on JVM have only helped to reignite the strong interest in this paradigm.
Java at its core is an imperative programming language. However in recent past many new languages like Scala, Clojure, Groovy etc. have become popular which supports functional programming style and yet run on JVM. However none of these languages can be considered as pure functional language since all of them allow Java code to be called from within them and Java on its own is not a functional language. Still they have different degree of support for writing code in functional style and have their own benefits. Functional programming requires different kind of thinking and has its own advantages as compared to imperative programming.
It seems that Java has also realized functional programming advantages and is slowly inching towards it. First sign of this can be seen in the form of Lambda Expressions that will be supported in Java 8. Although it's too early to comment on this as the draft for Java 8 is still under review and is expected to be released next year, but it does show that Java has plans of supporting functional programming style going forward.
In this article we will first discuss what functional programming is and how it is different from imperative programming. Later we will see where does each of the above mentioned Java based programming languages i.e. Scala, Clojure and Groovy fits in the world of functional programming and what each of them has to offer. And at the last we will sneak-peak into Java 8's lambda expressions.

Saturday, January 14, 2012

Authentication in Web.xml

Authentication

A web container can authenticate a web client/user using either HTTP BASIC, HTTP DIGEST, HTTPS CLIENT or FORM based authentication schemes.

Use Case: We would like to utilize the browser authentication mechanism, HTTP BASIC as defined in the HTTP 1.0 specification.

The login-config.xml element in web.xml would look like the following:
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>default</realm-name>
</login-config>

Use Case: We would like to utilize HTTPS Client authentication mechanism that is based on digital certificates. The authentication is based on the user's X509 certificate. The login-config.xml element in web.xml would look like the following:

<login-config>
   <auth-method>CLIENT-CERT</auth-method>
   <realm-name>JMX Console</realm-name>
</login-config>

Use Case: We would like to utilize FORM based authentication mechanism. FORM based mechanism provides flexibility in defining a custom jsp/html page for login and another page to direct for errors during login. The login-config xml element in web.xml would look like the following:

<login-config>
   <auth-method>FORM</auth-method>
   <form-login-config>
       <form-login-page>/login.html</form-login-page>
      <form-error-page>/error.html</form-error-page>
   </form-login-config>
</login-config>

In this case, the html page for login is the login.html and if any errors are encountered (including failed login), the user is directed to error.html

Friday, January 13, 2012

Implement Security in Web.xml

Use Case:3 We would like to exclude a set of web resources from any access. This can arise when a certain portion of the web application needs to undergo some form of maintenance or is not applicable for a particular physical deployment of a generic web application. We will achieve this with authorization constraints that specify no roles.


<security-constraint>
   <display-name>excluded</display-name>
   <web-resource-collection>
      <web-resource-name>No Access</web-resource-name>
      <url-pattern>/excluded/*</url-pattern>
      <url-pattern>/restricted/employee/excluded/*</url-pattern>
      <url-pattern>/restricted/partners/excluded/*</url-pattern>
   </web-resource-collection>
   <web-resource-collection>
      <web-resource-name>No Access</web-resource-name>
      <url-pattern>/restricted/*</url-pattern>
      <http-method>DELETE</http-method>
      <http-method>PUT</http-method>
      <http-method>HEAD</http-method>
      <http-method>OPTIONS</http-method>
      <http-method>TRACE</http-method>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
   </web-resource-collection>
   <auth-constraint />
   <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
</security-constraint>

Thursday, January 12, 2012

Implement Security in Web.xml

Use Case2: HTTP GET operation on a set of web resources should be accessible only by an user with the role "Employee". We will achieve this with the specification of authorization constraints (auth-constraint element with the role-name element).
<security-constraint>
   <display-name>Restricted GET To Employees</display-name>
   <web-resource-collection>
      <web-resource-name>Restricted Access - Get Only</web-resource-name>
      <url-pattern>/restricted/employee/*</url-pattern>
      <http-method>GET</http-method>
   </web-resource-collection>
   <auth-constraint>
      <role-name>Employee</role-name>
   </auth-constraint>
   <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
</security-constraint>

Wednesday, January 11, 2012

Implement Security in Web.xml

In this section, we will look at specifying the security constraints for multiple use cases.

Use Case1: We would like to define a set of web resources that will have unchecked access. We will achieve this by omitting the authorization constrainsts (auth-constraint element).
<security-constraint>
   <web-resource-collection>
     <web-resource-name>All Access</web-resource-name>
     <url-pattern>/unchecked/*</url-pattern>
     <http-method>DELETE</http-method>
     <http-method>PUT</http-method>
     <http-method>HEAD</http-method>
     <http-method>OPTIONS</http-method>
     <http-method>TRACE</http-method>
     <http-method>GET</http-method>
     <http-method>POST</http-method>
   </web-resource-collection>
   <user-data-constraint>
     <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
</security-constraint>

Tuesday, January 10, 2012

Implement Security in web.xml

The deployment descriptor, web.xml is the most important Java EE configuration piece of Java EE Web applications. The security configuration in this descriptor drives the semantics and operation of web container security. Hence it is very critical that web developers and administrators understand the various combinations possible in the security configuration in this descriptor.

Security Constraints

Security Constraints are least understood by web developers, even though they are critical for the security of Java EE Web applications. Specifying a combination of URL patterns, HTTP methods, roles and transport constraints can be daunting to a programmer or administrator. It is important to realize that any combination that was intended to be secure but was not specified via security constraints, will mean that the web container will allow those requests. Security Constraints consist of Web Resource Collections (URL patterns, HTTP methods), Authorization Constraint (role names) and User Data Constraints (whether the web request needs to be received over a protected transport such as TLS). We will told you using 3 use cases.

Monday, January 9, 2012

Downcasting in Java

Downcasting

  • An upcast reference can be downcast to a subclass through explicit casting. For example:
    Employee e = new Manager(...);
    // ...
    Manager m = (Manager) e;
    • The object referenced must actually be a member of the downcast type, or else a ClassCastException run-time exception occurs.
  • You can test if an object is a member of a specific type using the instanceof operator, for example:
    if (obj instanceof Manager) { // We've got a Manager object }
public class EmployeeDemo {
    public static void main(String[] args) {
        final Employee e1 = new Employee("John", "555-12-345", "john@company.com");
        final Employee e2 = new Employee("456-78-901", 1974);
        e2.setName("Tom");
        Employee em = new Manager("Bob", "345-11-987", "Development");

        Employee.setBaseVacationDays(15);
        e2.setExtraVacationDays(5);
        em.setExtraVacationDays(10);

        if (em instanceof Manager) {
            Manager m = (Manager) em;
            m.setResponsibility("Operations");
        }

        e1.print("COOL EMPLOYEE");
        e2.print("START OF EMPLOYEE", "END OF EMPLOYEE");
        em.print("BIG BOSS");
    }
}
This would print:
BIG BOSS
Name: Bob
SSN: 345-11-987
Email Address: null
Year Of Birth: 0
Vacation Days: 25
Responsibility: Operations

Sunday, January 8, 2012

Upcasting in java

Upcasting

  • Once you have upcast an object reference, you can access only the fields and methods declared by the base class.
    • For example, if Manager is a subclass of Employee:
      Employee e = new Manager(...);
    • Now using e you can access only the fields and methods declared by the Employee class.
  • However, if you invoke a method on e that is defined in Employee but overridden in Manager, the Manager version is executed.
    • For example:
      public class A {
          public void print() {
              System.out.println("Hello from class A");
          }
      }
      public class B extends A {
          public void print() {
              System.out.println("Hello from class B");
          }
      }
      // ...
      A obj = new B();
      obj.print();
      In the case, the output is "Hello from class B".
From within a subclass, you can explicitly invoke a base class’s version of a method by using the super. prefix on the method call.

Saturday, January 7, 2012

Overriding vs. Overloading

Overriding vs. Overloading

  • The subclass can override its parent class definition of fields and methods, replacing them with its own definitions and implementations.
    • To successfully override the base class method definition, the subclass method must have the same signature.
    • If the subclass defines a method with the same name as one in the base class but a different signature, the method is overloaded not overridden.
  • A subclass can explicitly invoked an ancestor class’s implementation of a method by prefixing super. to the method call. For example:
    class Subclass extends ParentClass {
        public String getDescription() {
            String parentDesc = super.getDescription();
            return "My description\n" + parentDesc;
        }
    }
Consider defining a Manager class as a subclass of Employee:
public class Manager extends Employee {
    private String responsibility;

    public Manager(String name, String ssn, String responsibility) {
        super(name, ssn);
        this.responsibility = responsibility;
    }

    public void setResponsibility(String responsibility) {
        this.responsibility = responsibility;
    }

    public String getResponsibility() {
        return this.responsibility;
    }

    public void print(String header, String footer) {
        super.print(header, null);
        System.out.println("Responsibility: " + responsibility);
        if (footer != null) {
            System.out.println(footer);
        }
    }
}
Now with code like this:
public class EmployeeDemo {
    public static void main(String[] args) {
        …
        Manager m1 = new Manager("Bob", "345-11-987", "Development");
        Employee.setBaseVacationDays(15);
        m1.setExtraVacationDays(10);
        …
        m1.print("BIG BOSS");
    }
}
The output is:
BIG BOSS
Name: Bob
SSN: 345-11-987
Email Address: null
Year Of Birth: 0
Vacation Days: 25
Responsibility: Development
Note that the Manager class must invoke one of super’s constructors in order to be a valid Employee. Also observe that we can invoke a method like setExtraVacationDays() that is defined in Employee on our Manager instance m1.

Friday, January 6, 2012

Inheritance, Composition, and Aggregation

Inheritance, Composition, and Aggregation

  • Complex class structures can be built through inheritance, composition, and aggregation.
  • Inheritance establishes an “is-a” relationship between classes.
    • The subclass has the same features and functionality as its base class, with some extensions.
    • A Car is-a Vehicle. An Apple is-a Food.
  • Composition and aggregation are the construction of complex classes that incorporate other objects.
    • They establish a “has-a” relationship between classes.
    • A Car has-a Engine. A Customer has-a CreditCard.
  • In composition, the component object exists solely for the use of its composite object.
    • If the composite object is destroyed, the component object is destroyed as well.
    • For example, an Employee has-a name, implemented as a String object. There is no need to retain the String object once the Employee object has been destroyed.
  • In aggregation, the component object can (but isn’t required to) have an existence independent of its use in the aggregate object.
    • Depending on the structure of the aggregate, destroying the aggregate may or may not destroy the component.
    • For example, let’s say a Customer has-a BankAccount object. However, the BankAccount might represent a joint account owned by multiple Customers. In that case, it might not be appropriate to delete the BankAccount object just because one Customer object is deleted from the system.
Notice that composition and aggregation represent another aspect of encapsulation. For example, consider a Customer class that includes a customer’s birthdate as a property. We could define a Customer class in such a way that it duplicates all of the fields and methods from and existing class like Date, but duplicating code is almost always a bad idea. What if the data or methods associated with a Date were to change in the future? We would also have to change the definitions for our Customer class. Whenever a set of data or methods are used in more than one place, we should look for opportunities to encapsulate the data or methods so that we can reuse the code and isolate any changes we might need to make in the future.
Additionally when designing a class structure with composition or aggregation, we should keep in mind the principle of encapsulation when deciding where to implement functionality. Consider implementing a method on Customer that would return the customer’s age. Obviously, this depends on the birth date of the customer stored in the Date object. But should we have code in Customer that calculates the elapsed time since the birth date? It would require the Customer class to know some very Date-specific manipulation. In this case, the code would be tightly coupled –- a change to Date is more likely to require a change to Customer as well. It seems more appropriate for Date objects to know how to calculate the elapsed time between two instances. The Customer object could then delegate the age request to the Date object in an appropriate manner. This makes the classes loosely coupled –- so that a change to Date is unlikely to require a change to Customer.

Thursday, January 5, 2012

Static vs. Instance Methods

Static vs. Instance Methods

  • Static methods can access only static data and invoke other static methods.
    • Often serve as helper procedures/functions
    • Use when the desire is to provide a utility or access to class data only
  • Instance methods can access both instance and static data and methods.
    • Implement behavior for individual objects
    • Use when access to instance data/methods is required
  • An example of static method use is Java’s Math class.
    • All of its functionality is provided as static methods implementing mathematical functions (e.g., Math.sin()).
    • The Math class is designed so that you don’t (and can’t) create actual Math instances.
  • Static methods also are used to implement factory methods for creating objects, a technique discussed later in this class.
class Employee {
    String name;
    String ssn;
    String emailAddress;
    int yearOfBirth;
    int extraVacationDays = 0;
    static int baseVacationDays = 10;

    Employee(String name, String ssn) {
        this.name = name;
        this.ssn = ssn;
    }

    static void setBaseVacationDays(int days) {
        baseVacationDays = days < 10? 10 : days;
    }

    static int getBaseVacationDays() {
        return baseVacationDays;
    }

    void setExtraVacationDays(int days) {
        extraVacationDays = days < 0? 0 : days;
    }

    int getExtraVacationDays() {
        return extraVacationDays;
    }

    void setYearOfBirth(int year) {
        yearOfBirth = year;
    }

    int getVacationDays() {
        return baseVacationDays + extraVacationDays;
    }

    void print() {
        System.out.println("Name: " + name);
        System.out.println("SSN: " + ssn);
        System.out.println("Email Address: " + emailAddress);
        System.out.println("Year Of Birth: " + yearOfBirth);
        System.out.println("Vacation Days: " + getVacationDays());
    }
}
To change the company vacation policy, do Employee.setBaseVacationDays(15);
To give one employee extra vacation, do e2.setExtraVacationDays(5);

Wednesday, January 4, 2012

Static vs. Instance Data Fields

Static vs. Instance Data Fields

  • Static (or class) data fields
    • Unique to the entire class
    • Shared by all instances (objects) of that class
    • Accessible using ClassName.fieldName
    • The class name is optional within static and instance methods of the class, unless a local variable of the same name exists in that scope
    • Subject to the declared access mode, accessible from outside the class using the same syntax
  • Instance (object) data fields
    • Unique to each instance (object) of that class (that is, each object has its own set of instance fields)
    • Accessible within instance methods and constructors using this.fieldName
    • The this. qualifier is optional, unless a local variable of the same name exists in that scope
    • Subject to the declared access mode, accessible from outside the class from an object reference using objectRef.fieldName
Say we add the following to our Employee class:
static int vacationDays = 10;
and we print this in the Employee’s print() method:
System.out.println("Vacation Days: " + vacationDays);
In the EmployeeDemo’s main() method, we change vacationDays to 15:
Employee.vacationDays = 15;
Now, e1.print() and e2.print() will both show the vacation days set to 15. This is because both e1 and e2 (and any other Employee object) share the static vacationDays integer field.
The field vacationDays is part of the Employee class, and this is also stored on the heap, where it is shared by all objects of that class.
Static fields that are not protected (which we will soon learn how to do) are almost like global variables — accessible to anyone.
Note that it is possible to access static fields through instance variables (e.g., e1.vacationDays = 15; will have the same effect), however this is discouraged. You should always access static fields by ClassName.staticFieldName, unless you are within the same class, in which case you can just say staticFieldName.

Tuesday, January 3, 2012

Garbage Collection

Garbage Collection

  • Unlike some OO languages, Java does not support an explicit destructor method to delete an object from memory.
    • Instead, unused objects are deleted by a process known as garbage collection.
  • The JVM automatically runs garbage collection periodically. Garbage collection:
    • Identifies objects no longer in use (no references)
    • Finalizes those objects (deconstructs them)
    • Frees up memory used by destroyed objects
    • Defragments memory
  • Garbage collection introduces overhead, and can have a major affect on Java application performance.
    • The goal is to avoid how often and how long GC runs.
    • Programmatically, try to avoid unnecessary object creation and deletion.
    • Most JVMs have tuning parameters that affect GC performance.
Benefits of garbage collection:
  • Frees up programmers from having to manage memory. Manually identifying unused objects (as in a language such as C++) is not a trivial task, especially when programs get so complex that the responsibility of object destruction and memory deallocation becomes vague.
  • Ensures integrity of programs:
    • Prevents memory leaks — each object is tracked down and disposed off as soon as it is no longer used.
    • Prevents deallocation of objects that are still in use or have already been released. In Java it is impossible to explicitly deallocate an object or use one that has already been deallocated. In a language such as C++ dereferencing null pointers or double-freeing objects typically crashes the program.
Through Java command-line switches (java -X), you can:
  • Set minimum amount of memory (e.g. -Xmn)
  • Set maximum amount of memory (e.g. -Xmx, -Xss)
  • Tune GC and memory integrity (e.g. -XX:+UseParallelGC)
For more information, see: http://java.sun.com/docs/hotspot/VMOptions.html and http://www.petefreitag.com/articles/gctuning/

Monday, January 2, 2012

Accessing Objects through References

Accessing Objects through References

Employee e1 = new Employee();
Employee e2 = new Employee();

// e1 and e2 refer to two independent Employee objects on the heap

Employee e3 = e1;

// e1 and e3 refer to the *same* Employee object

e3 = e2;

// Now e2 and e3 refer to the same Employee object

e1 = null;

// e1 no longer refers to any object. Additionally, there are no references
// left to the Employee object previously referred to by e1. That "orphaned"
// object is now eligible for garbage collection.
[Note]Note
The statement Employee e3 = e2; sets e3 to point to the same physical object as e2. It does not duplicate the object. Changes to e3 are reflected in e2 and vice-versa.

Set Thread Name

package org.best.example;

    /*
            Set Thread Name Example
            This Java example shows how to set name of thread using setName method
            of Thread class.
    */
    
    public class SetThreadNameExample {
    
            public static void main(String[] args) {
                  
                    //get currently running thread object
                    Thread currentThread = Thread.currentThread();
                    System.out.println(currentThread);
                  
                    /*
                     * To set name of thread, use
                     * void setName(String threadName) method of
                     * Thread class.
                     */
                  
                    currentThread.setName("Set Thread Name Example");
                  
                    /*
                     * To get the name of thread use,
                     * String getName() method of Thread class.
                     */
                    System.out.println("Thread Name : "+ currentThread.getName());
            }
    }
    
    /*
    Output of the example would be
    Thread[main,5,main]
    Thread Name : Set Thread Name Example
    */

Sunday, January 1, 2012

Java Memory Model

Java Memory Model

  • Java variables do not contain the actual objects, they contain references to the objects.
    • The actual objects are stored in an area of memory known as the heap.
    • Local variables referencing those objects are stored on the stack.
    • More than one variable can hold a reference to the same object.
Figure 1. Java Memory Model
Java Memory Model


As previously mentioned, the stack is the area of memory where local variables (including method parameters) are stored. When it comes to object variables, these are merely references (pointers) to the actual objects on the heap.
Every time an object is instantiated, a chunk of heap memory is set aside to hold the data (state) of that object. Since objects can contain other objects, some of this data can in fact hold references to those nested objects.
In Java:
  • Object references can either point to an actual object of a compatible type, or be set to null (0 is not the same as null).
  • It is not possible to instantiate objects on the stack. Only local variables (primitives and object references) can live on the stack, and everything else is stored on the heap, including classes and static data.



Pause Thread Using Sleep Method

package org.best.example;

    /*
            Pause Thread Using Sleep Method Example
            This Java example shows how to pause currently running thread using
            sleep method of Java Thread class.
    */
    
    public class PauseThreadUsingSleep {
    
            public static void main(String[] args) {
                  
                    /*
                     * To pause execution of a thread, use
                     * void sleep(int milliseconds) method of Thread class.
                     *
                     * This is a static method and causes the suspension of the thread
                     * for specified period of time.
                     *
                     * Please note that, this method may throw InterruptedException.
                     */
                  
                    System.out.println("Print number after pausing for 1000 milliseconds");
                    try{
                          
                            for(int i=0; i< 5; i++){
                                  
                                    System.out.println(i);
                                  
                                    /*
                                     * This thread will pause for 1000 milliseconds after
                                     * printing each number.
                                     */
                                    Thread.sleep(1000);
                            }
                    }
                    catch(InterruptedException ie){
                            System.out.println("Thread interrupted !" + ie);
                    }
                  
            }
    }
    
    /*
    Output of this example would be
    
    Print number after pausing for 1000 milliseconds
    0
    1
    2
    3
    4
    */