Wednesday, 27 June 2012
Java 8 : Project Lambda : To Multicore and Beyond
Java 8 - Project Lambda
What is project lambda:
Project lambda is the project to enable lambda expressions in java language syntax. Lambda expressions are major syntax in functional programming languages like lisp. Groovy would be the closest relative of java that has support for lambda expressions, also known as closures.
It is a block of code that can be assigned to a variable or passed as an argument to a method or passed as an argument to another lambda expression just like any other data
The main motivation behind supporting this in java is to remove a lot of boiler plate code in using certain API that require some code from the API user, but end up using inner classes just because of java's syntax requirements.
The syntax is indeed much simpler than that for creating anonymous classes. The syntax mainly is of this form:
argumentList -> body
The argumentList is just like java method argument list - comma separated and enclosed in parentheses, with one exception - if there is only one argument, the parentheses are optional. Also it is optional to mention the types of the arguments. In case the types are not specified, they are inferred. The body can be of two types - expression body and code block body. An expression body is just a valid java expression that returns a value. A code block body contains a code block just like a method body. The code block body has the same syntax as the method body including the mandatory pair of braces.
Project Lambda: To Multicore and Beyond
Where are we?
· Multicore hardware is now the default
· Moore’s law delivering more cores, not faster cores
· We must learn to write software that parallelizes gracefully
· All components of the Java SE platform – language, libraries, and VM – are co-evolving to meet the challenge
Goal: To achieve parallel computation when we invoke the methods through Lambda Expression

PFA.. for detail implementation
What is project lambda:
Project lambda is the project to enable lambda expressions in java language syntax. Lambda expressions are major syntax in functional programming languages like lisp. Groovy would be the closest relative of java that has support for lambda expressions, also known as closures.
It is a block of code that can be assigned to a variable or passed as an argument to a method or passed as an argument to another lambda expression just like any other data
The main motivation behind supporting this in java is to remove a lot of boiler plate code in using certain API that require some code from the API user, but end up using inner classes just because of java's syntax requirements.
The syntax is indeed much simpler than that for creating anonymous classes. The syntax mainly is of this form:
argumentList -> body
The argumentList is just like java method argument list - comma separated and enclosed in parentheses, with one exception - if there is only one argument, the parentheses are optional. Also it is optional to mention the types of the arguments. In case the types are not specified, they are inferred. The body can be of two types - expression body and code block body. An expression body is just a valid java expression that returns a value. A code block body contains a code block just like a method body. The code block body has the same syntax as the method body including the mandatory pair of braces.
Project Lambda: To Multicore and Beyond
Where are we?
· Multicore hardware is now the default
· Moore’s law delivering more cores, not faster cores
· We must learn to write software that parallelizes gracefully
· All components of the Java SE platform – language, libraries, and VM – are co-evolving to meet the challenge
Goal: To achieve parallel computation when we invoke the methods through Lambda Expression

PFA.. for detail implementation
Why do we go for JTA
If, however, you
are accessing two different databases, or two different resources—JDBC and JMS,
for example—and you want the operations performed by both resources to be part
of the same transaction, then you have to use the Java Transaction API (JTA) to group all the operations into a single
transaction.
Best Way to Implement Singleton in 1.5 and above
class SingleTon implements
Serializable {
public static final
SingleTon INSTANCE = new
SingleTon();
private
SingleTon() {
}
String name;
public
String getName() {
return name;
}
public void
setName(String name) {
this.name =
name;
}
private
Object readResolve() { //To Maintain
Single Instance even in de-serialization
return INSTANCE;
}
}
public class OldSingleTone
{
public static void
main(String... args) {
SingleTon single =
SingleTon.INSTANCE;
single.setName("BNP ");
System.out.println(single.getName());
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------
In Java 1.5
enum SingleTon {
INSTANCE;
String name;
public
String getName() {
return name;
}
public void
setName(String name) {
this.name =
name;
}
}
public class
OldSingleTone {
public static void
main(String... args) {
SingleTon single =
SingleTon.INSTANCE;
single.setName("BNP ");
System.out.println(single.getName());
}
}
------------------------------------------------------------------------------------------
If you want a SingleTon class as
Serializable you need to override readResolve Method but in Enum its too
simple.....
"a
single-element enum type is the best way to implement a singleton."
Note : Enums are inherently
Serializable... (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html)
What would be the alternative for XML in future
JavaScript Object Notation
The successor to
XML in the browser, JSON aspires to be nothing more than a simple and elegant
data format for the exchange of information between the browser and server; and
in doing this simple task it will usher in the next version of the World Wide
Web itself.
Creating A New Object
The old way to
create a new object was to use the new keyword.
var myJSON = new Object();
This method has
been deprecated now in favor of simply defining an empty object with squigly
braces…
var myJSON = {};
Objects as Data
<?xml
version="1.0"?>
<myFirstJSON>
<firstName>John</firstName>
<lastName>Doe</lastName>
<age>23</age>
</myFirstJSON>
We could represent the xml in the following
JSON Format.
var
myFirstJSON = { "firstName" : "John",
"lastName" : "Doe",
"age" : 23 };
We could access it using the Object Name
document.writeln(myFirstJSON.firstName); // Outputs
John
document.writeln(myFirstJSON.lastName); // Outputs
Doe
document.writeln(myFirstJSON.age);
// Outputs 23
In XML you have to use parser to retrieve the
data and it takes more processing time.
This object
has 3 properties or name/value pairs. The name is a string -- in our example,
firstName, lastName, and age. The value can be any Javascript
object (and remember everything in Javascript is an object so the value can be
a string, number, array, function, even other Objects) -- In this example our
values are John, Doe, and 23. John and Doe are strings but age is a number and
as you can see this is not a problem.
var employees = {
"accounting" : [ // accounting is an array in employees.
{ "firstName" :
"John", // First element
"lastName" :
"Doe", //Instead of XPATH employees.accounting[0].lastName
"age"
: 23 },
{ "firstName" :
"Mary", // Second Element
"lastName" :
"Smith", //Instead
of XPATH employees.accounting[1].lastName
"age"
: 32 }
], // End "accounting" array.
"sales"
: [ // Sales is another array in employees.
{ "firstName" :
"Sally", // First Element
"lastName" :
"Green", //Instead
of XPATH employees.sales[0].lastName
"age"
: 27 },
{ "firstName" :
"Jim", // Second Element
"lastName" :
"Galley",
//Instead of XPATH employees.sales[1].lastName
"age"
: 41 }
] // End "sales" Array.
} // End Employees
In XML
Representation
<employees>
<accounting>
<firstName>John</firstName>
<lastName>Doe</lastName> <!-- Xpath //employees/accounting[0]/lastName -->
<age>23</age>
</accounting>
<accounting>
<firstName>Mary</firstName>
<lastName>Smith</lastName> <!-- Xpath
//employees/accounting[1]/lastName -->
<age>32</age>
</accounting>
<sales>
<firstName>Sally</firstName>
<lastName>Green</lastName> <!-- Xpath
//employees/sales[0]/lastName -->
<age>27</age>
</sales>
<sales>
<firstName>Jim</firstName>
<lastName>Gallery</lastName> <!-- Xpath
//employees/sales[1]/lastName -->
<age>41</age>
</sales>
</employees>
Accessing Data In JSON
var
myObject = { 'color' : 'blue',
'animal' : {'dog' : 'friendly' } //Instead of
XPATH myObject.animal.dog
};
<myObject>
<color>blue</color>
<animal>
<dog>friendly</dog> <!-- //XPath //myObject/color/animal/dog
-->
</animal>
</myObject>
Receiving JSON via AJAX
var
JSONFile = "someVar = { 'color' : 'blue' }"; //
example of what is received from the server.
eval(JSONFile); //
Execute the javascript code contained in JSONFile.
document.writeln(someVar.color); //
Outputs 'blue'
JSON Via Callback
function
processData(incommingJSON) {
document.writeln(incommingJSON.color); // Outputs
'blue'
}
// example of what is received from
the server...
var JSONFile = "processData( {
'color' : 'blue' } )";
eval(JSONFile);
Retrieving JSON Data via Ajax
function processData(JSONData) {
alert(JSONData.color);
}
var ajaxRequest = new ajaxObject('http://www.somedomain.com/getdata.php');
ajaxRequest.callback = function
(responseText) {
eval(responseText);
}
ajaxRequest.update();
// In this example we assume the server sends back the
following data file
// (which the ajax
routine places in responseText)
//
// processData( { "color" : "green" }
)
Howto Send JSON Data To The Server
var
toServer = employees.toJSONString();
document.writeln(toServer);
Outputs:
{"accounting":[{"firstName":"John","lastName":"Doe","age":23},{"firstName":"Mary","lastName":"Smith","age":32}],"sales":[{"firstName":"Sally","lastName":"Green","age":27},{"firstName":"Jim","lastName":"Galley","age":41}]}
JSON
Security
http://www.fortify.com/landing/downloadLanding.jsp?path=%2Fpublic%2FJavaScript_Hijacking.pdf
JSON Best Practices
Never Trust The
Browser
Keep Data Clean
(Don't embed functions in your JSON data)
Avoid Third Party
JSON
Authenticate on
the server side all JSON data requests (make sure they're on your site)
Use SSL (Browser
Encryption) for sensitive data.
The future of JSON
In 2008 most browsers will be able to parse JSON
and to convert any variable into JSON. There is also an upcoming standard (also
from Douglas Crockford) which will enable a browser to securely request a
JSONfile from outside the current domain. When both of these technologies have
been implemented, we will be entering the world of Web 3.0 where any browser
can request any JSON published data anywhere in the world and manipulate it to
its own ends without the need to involve any proxy servers.
Tips & Trick of Java Comparator
When compartor return 1, swap happen and for -1 swap not happen.
What happen when it return 0?
Based on the collection we use, its action change
If we use List, its not changing the order and if its a Set it
eliminates the record.
public class Test
{
public static void
main(String[] args) throws Exception {
Comparator
c = new Comparator<String>() {
@Override
public int
compare(String first, String second) {
return 0;
}
};
Set<String>
comp = new TreeSet<String>(c);
comp.add("A");
comp.add("C");
comp.add("B");
System.out.println("Comp
: " + comp);
}
}
Result
Comp : [A]
Subscribe to:
Posts (Atom)