Introduction to features introduced in Java 7.
- JSR
334 – Small language Enhancements (Project Coin)
- JSR
203 – New I/O API For Java Platform (NIO.2)
- JSR
292 – Support For Dynamically Typed Language
- Miscellaneous
- Core
– Concurrency & Collection Updates
- Internationalization
- JDBC
– JDBC 4.1
- Swing.
- Networking.
- XML
JSR 334 – Small Language Enhancements (Project Coin)
• Underscores
in Numeric Literals
• Binary
integral literals
• Strings
in switch statement
• Improved
type inference for generic instance creation
• Multi
catch and more precise re-throw
• Try
with resources statement
Underscore Characters in Numeric Literals
• Underscore
character ( _ ) can be used between digits of numerical literal.
• Separates
groups of digits in numeric literals
• Improves
the readability of your code.
• Rules
for placing underscores:
• Allowed
between digits.
• Any
number of underscore characters can be placed.
• Not
allowed at the beginning or end of a number.
• Not
allowed adjacent to a decimal point in a floating point literal.
• Not
allowed prior to an F or L suffix.
• Examples
with the underscore in numeric literals:
int x1 = _52;
// Invalid; cannot put underscores at the beginning of a number
int x2 = 5_2;
// OK (decimal literal)
int x3 = 52_;
// Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;
// OK (decimal literal)
int x5 = 0_x52;
// Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;
// Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;
// OK (hexadecimal literal)
int x8 = 0x52_;
// Invalid; cannot put underscores at the end of a number
int x9 = 0_52;
// OK (octal literal)
int x10 = 05_2;
// OK (octal literal)
int x11 = 052_;
// Invalid; cannot put underscores at the end of a number
Binary Literals
• New
form “0b1”, in addition to the existing Decimal (1), Octal (01) and
Hexadecimal (0x1)
• Need/Benefits
of Binary Literals
• Improves
readability.
• Binary
literal can be used in switch statement.
• Feature
can be tested in same way as that of decimal, octal or hexadecimal
• Examples
byte bit8 =
(byte)0b0010_0001;
short bit16 = (short)0b1010_0001_0100_0101;
int bit32 = 0b1010_0001_0100_0101_1010_0001_0100_0101;
// B can be upper or lower case as x in "0x45".
int var4 = 0B101;
Using Strings in switch Statements
• Strings
in switch statement are compared using equals() method.
• Comparison
in switch statement is case sensitive
• NullPointerException
is thrown if given string (‘day’) is null.
public int getDay(String day) {
switch
(day) {
case “monday": return 1;
case “tuesday": return 2;
case “wednesday": return 3;
case “thursday": return 4;
case “friday": return 5;
case “saturday": return 6;
case “sunday": return 7;
default: return -1;
}
}
Try with resources statement
• Use
instead of finally block
• Resources
are closed upon completion of try block or when exception is thrown
• Resource
is any object that implements java.lang.AutoCloseable or java.io.Closeable
• Resource
is any object that must be closed when program ends.
• In
try with resources, catch and finally blocks are run after resources are
closed.
• Example:
pubic void dump(String f, String d) {
try (
// FileWriter
is resource.
// Res. Var.
Need to be initialized.
// Multiple
resources possible.
FileWriter
fw = new FileWriter(f); …) {
fw.write(d);
fw.flush()
} catch (IOException
e) {
log.error(e);
}
}
• Some
Examples of classes implementing java.lang.AutoCloseable or java.io.Closeable
java.nio.channels.FileLock
javax.imageio.stream.ImageInputStream
java.beans.XMLEncoder
java.beans.XMLDecoder
java.io.ObjectInput
java.io.ObjectOutput
javax.sound.sampled.Line
javax.sound.midi.Receiver
javax.sound.midi.Transmitter
javax.sound.midi.MidiDevice
java.util.Scanner
java.sql.Connection
java.sql.ResultSet
java.sql.Statement
Improved type inference for generic instance creation
• Diamond
Operator (<>)
• Consider
following lengthy statement
Map<String, List<String>> anagrams = new
HashMap<String, List<String>>();
Can be Simplified using diamond operator as given below
Map<String, List<String>> anagrams = new HashMap<>();
• Benefits
• Improves
inference for generic instance creation
• Brings
type inference to constructors that was available with methods.
• Reduces
verbosity by having the compiler infer parameter types for constructors of
generic classes.
Multi-catch & More Precise Re-throw
Single catch block can handle more than one type of
exception
|
|||
|
|||
Benefits:
• Improves
readability.
• Less
code when common exception handling code is required for 2 or more exception
types.
try {
//some code that can
throw FileNotFoundException or SocketException
} catch (FileNotFoundException | SocketException) {
throw new IOException(“Failed
to read file”);
}
• Bytecode
generated by compiling a catch block that handles multiple exception
types will be smaller (and thus superior) than compiling
many catch blocks that handle only one exception type each.
• The
Java SE 7 compiler performs more precise analysis of rethrown exceptions than
earlier releases of Java SE.
• This
enables you to specify more specific exception types in the throws clause
of a method declaration even if you are catching and throwing a generic type.
• In
other words, if you have a function that is declared to throw a Exception X you
can throw the supertype of X from this function.
// FirstException and SecondException inherit from
Exception.
public void
rethrowException(String exceptionName) throws FirstException,
SecondException {
try {
if
(exceptionName.equals("First")) {
throw
new FirstException();
}
else {
throw
new SecondException();
}
}
catch (Exception
fe) {
throw fe;
}
}
JSR 203 – New IO API For Java Platform (NIO.2)
• Path
interface
• Files
class.
• Support
for Symbolic Link & File Attributes
• File
Tree Walk
• File
System Change Notification
Path interface
• The
Path class is a programmatic representation of a path in the file system.
• Path
path = Paths.get(“/home/javaex”); // ON UNIX.
A Path instance
reflects the underlying platform. In the UNIX OS, a Path uses the UNIX syntax
(/home/joe/foo) and in Microsoft Windows, a Path uses the Windows syntax
(C:\home\joe\foo). A Path is system dependent. You cannot compare a Path from a
UNIX file system and expect it to match a Path from a Windows file system
Path interface – operations
• Creating
a Path
• Retrieving
Information About a Path
• toString(),
getFileName, getName(0), getNameCount, getRoot, getParent,…
• Removing
Redundancies from a Path
• Normalize()
• Converting
a Path
• toRealPath(),
to AbsolutePath(), toUri()
• Comparing
Two Paths
• startsWith(),
endsWith()
Files Class
This class offers a rich set of static methods for reading,
writing, and manipulating files and directories. The Files methods
work on instances of Path objects.
They are link aware
Files Class – Basic Operations
• exists(Path,
LinkOptions…), notExists()
• isReadable,
isWritable, isExecutable.
• Delete
• copy
• move
Files class : File attributes
• The Files class
includes methods that can be used to obtain a single attribute of a file, or to
set an attribute.
• Size,
isDirectory, isRegularFile, isSymbolicLink, isHidden, getPosixFilePermissions,
• getOwner,
• Files class
also provides API methods to fetch a file's attributes in one bulk
operation.
• readAttributes
Files : Reading, Writing, and Creating Files
• On
the far left of the diagram are the utility
methods readAllBytes, readAllLines, and the write methods,
designed for simple, common cases.
• To
the right of those are the methods used to iterate over a stream or lines of
text, such as newBufferedReader, newBufferedWriter,
then newInputStream and newOutputStream.
• These
methods are interoperable with the java.io package.
• To
the right of those are the methods for dealing
withByteChannels, SeekableByteChannels, and ByteBuffers, such as the newByteChannel method.
• Finally,
on the far right are the methods that use FileChannel for advanced
applications needing file locking or memory-mapped I/O.
NIO.2 Enhancements
– Symbolic Link & Hard Links
• Symbolic
Link / Soft Links
• Symbolic
link is special file that serves as reference to another file.
• Most
of operation on symbolic link file is transparent i.e. any operation on it is
redirected to the file to which it is referring.
• File
operation like ‘remove’ or ‘rename’ are however perform on file itself.
• NIO.2
API has support for Symbolic Link on Unix like OS as well as on Windows Vista
and newer Windows OS where Symbolic Link concept is supported.
• NIO.2
API also handles circular reference and avoid infinite loops.
• Hard
Links
• The
target of the link must exist.
• Hard
links are generally not allowed on directories.
• Hard
links are not allowed to cross partitions or volumes. Therefore, they cannot
exist across file systems.
• A
hard link is, for all intents and purposes, the same entity as the original file.
They have the same file permissions, time stamps, and so on. All attributes are
identical.
• ls
-li <filename> ( to get the hard
links for a file #1 )
• find
/dir -xdev -inum <inode_num> ( to get the hard links for a file #2 )
Soft and Hard Links – Operations
• Creating
a Symbolic Link
• Creating
a Hard Link
• Detecting
a Symbolic Link
• Finding
the Target of a Link
NIO.2 Enhancements
– File Tree Walk
• File
Tree Walk feature
• Facilitates
traversing directory & sub directories and apply common processing on files
or subset of files.
• Is
added by having utility method walkFileTree() in Files class
which recursively traverses directory tree given starting point.
• For
processing files user has to provide another argument which is instance of
class that implements FileVisitor interface. FileVisitor has
following methods;
• preVisitDirectory(),
postVisitDirectory(), visitFile(), visitFileFailed()
• FileVisitor
interface method returns instance of FileVisitResult class. File walking
process can be controlled by returning one of the following values;
• CONTINUE,
TERMINATE, SKIP_SUBTREE, SKIP_SIBLINGS
• Two
overloaded methods of walkFileTree() are given below;
• Files.walkFileTree(Path,
FileVisitor)
• Files.walkFileTree(Path,
Set<FileVisitOption>, int, FileVisitor)
//SimpleFileVisitor
provide default implementation for other FileVisitor methods.
public
static class PrintFiles extends SimpleFileVisitor<Path> {
//Print information about each type of
file.
@Override public FileVisitResult
visitFile(Path file, BasicFileAttributes attr) {
if (attr.isSymbolicLink()) {
System.out.format("Symbolic
link: %s ", file);
} else if (attr.isRegularFile()) {
System.out.format("Regular
file: %s ", file);
} else {
System.out.format("Other: %s
", file);
}
System.out.println("(" +
attr.size() + "bytes)");
return CONTINUE;
}
}
NIO.2 Enhancements
– File System Change Notification
• The
java.nio.file package has a WatchService API to support
file change notification.
• Main
goal here is to help with performance issues in applications that are currently
forced to poll the file system.
• User
can register directory/directories to watch and specify type of events to
monitor. Various types of events are -
ENTRY_CREATE - A directory entry is created.
ENTRY_DELETE - A directory entry is deleted.
ENTRY_MODIFY - A directory entry is modified.
OVERFLOW - Indicates that events might have been lost or
discarded. You do not have to register for the OVERFLOW event to receive it.
• Once
the event occurs, it is forwarded to registered process which is thread or pool
of threads for handling the event.
• Example
FileSystem fileSystem = FileSystems.getDefault()
WatchService wService = fileSystem.newWatchService();
Path dir = ...;
try {
dir.register(wService, ENTRY_CREATE, ENTRY_DELETE);
:
} catch (IOException x) {
System.err.println(x);
}
• First
step is to create WatchService using FileSystem’s newWatchService() method.
• Next
step is to register one or more objects with the WatchService. These objects
should implement Watchable interface. Java.nio.file.Path implements Watchable
interface.
• Example
for (;;) {
WatchKey key =
watcher.take();
for (WatchEvent
event : key.pollEvents()) {
String file =
event.context().toString();
if (event.kind()
== ENTRY_DELETE) {
System.out.println("Delete: " + file);
} if (event.kind()
== ENTRY_CREATE) {
System.out.println("Created: " + file);
}
}
boolean valid =
key.reset();
if (!valid) { break;
}
}
• Infinite
for loop waits for incoming events. When event occurs key is signaled and
placed into watcher queue.
• Inner
for loop retrieves pending events for the WatchKey & process as needed.
• Reset
key and resume waiting for the events.
JSR 292 – Support for Dynamically Typed Languages
Dynamically typed languages on the JVM
• Dynamically
typed languages don't provide type information until runtime.
• JRuby
, Jython, Groovy are dynamic languages which run on Java JVM. It means their
compilers generate bytecode which can be run on JVM.
• Why
do these need to run on JVM?
ü Can
be written once and run anywhere
ü Can
be run securely because of the Java sandbox security model
ü Concurrency
ü Garbage
collection
ü Optimization
ü Reflective
access to classes and objects
ü Easy
to package and deliver
Challenges of Compiling Dyn. Typed Languages
• JVM
requires the bytecode to exactly determine which method to link to
corresponding a specific method call.
• e.g
def
addtwo(a, b)
a
+ b;
end
• Java
compiler implements + with the iadd JVM instruction if the
types of a and b are int.
• Compiler
of dynamically typed languages do not know the types until runtime ( after the
compilation process is done )
Workflow
- Compiler
emits and invokedynamic bytecode with a bootstrap method specified.
- The
bootstrap method is provided by the compiler of the dynamically typed
language.
- When
the JVM encounters the invokedynamic bytecode, it calls the bootstrap
method which returns a CallSite object which is linked to a MethodHandle
which points to the function to be called.
- From
here on, whenever the JVM encounters the above invokedynamic instruction,
it directly calls the linked function bypassing the bootstrap process.
- More
optimized approach as compared to using Reflection (
java.lang.reflect.Method.invoke )
- New
package added : java.lang.invoke
Miscellaneous
- Internationalization.
- JDBC
– JDBC 4.1
- Concurrency
and Collections updates.
- Swing
- Networking
- XML
Internationalization
• Add
supports for Unicode 6.0
• Unicode
6.0 Summary
• Over
1000 additional symbols
• Support
for Emoji symbol that is important for mobile phones
• Support
for new official Indian currency symbol
• Support
for 222 additional CJK ideograph
• They
are in common use in China, Japan & Taiwan
• 603
additional characters for African language support
• Including
scripts – Tifinagh, Ethiopee & Barnum
• 3
additional scripts – Mandaic, Brahmi & Balnik
• Extensible
Support for ISO 4217 Currency Codes
• Currency
codes are identified by ISO 4217, an external agency.
• With
Java SE 7, it is possible to accommodate new currencies without requiring a new
release of JDK.
• Default
currency at runtime can be overridden by creating properties file in
JAVA_HOME/lib/currency.properties
The value contains 3 comma separated parts of ISO 4217
currency values. E.g.
# Sample currency property for Japan
JP=JPZ,999,0
• New
API for this feature includes methods like
getAvailableCurrencies
– Returns the set of available currencies.
getNumericCode
– Returns the ISO 4217 numeric code of this currency
getDisplayName
– Gets the name suitable for displaying this currency for the default locale.
getDisplayName(Locale)
– Gets the name suitable for displaying the specified locale.
JDBC 4.1
• Add
supports for JDBC 4.1
• JDBC
4.1 Summary
• Supports
try-with-resources statement to automatically close JDBC resources.
• The
introduction of the RowSetFactory interface and the RowSetProvider class, which
enable you to create all types of row sets supported by your JDBC driver
• RowSetFactory
factory = new RowSetProvider.newFactory();
• RowSetFactory
has methods
• createCachedRowSet()
• createFilteredRowSet()
• createJdbcRowSet()
• createJoinRowSet()
• createWebRowSet()
Concurrency – Intro
• The
fork/join framework is an implementation of the ExecutorService interface that
helps you take advantage of multiple processors.
• It
is designed for work that can be broken into smaller pieces recursively.
• The
goal is to use all the available processing power to make your application
wicked fast.
• As
with any ExecutorService, the fork/join framework distributes tasks to worker
threads in a thread pool.
• The
fork/join framework is distinct because it uses a work-stealing algorithm.
• Worker
threads that run out of things to do can steal tasks from other threads that
are still busy.
Concurrency – ForkJoinPool
• The
center of the fork/join framework is the ForkJoinPool class, an extension of
AbstractExecutorService.
• ForkJoinPool
implements the core work-stealing algorithm and can execute ForkJoinTasks.
Concurrency – ThreadLocalRandom
• A
random number generator isolated to the current thread.
• Like
the global Random generator used by the Math class,
a ThreadLocalRandom is initialized with an internally generated seed
that may not otherwise be modified.
• When
applicable, use of ThreadLocalRandom rather than
shared Random objects in concurrent programs will typically encounter
much less overhead and contention.
• Use
of ThreadLocalRandom is particularly appropriate when multiple tasks
(for example, each a ForkJoinTask) use random numbers in parallel in
thread pools.
• Usages
of this class should typically be of the
form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long,
etc).
• When
all usages are of this form, it is never possible to accidently share
a ThreadLocalRandom across multiple threads.
Collection Updates
• A TransferQueue
is a refinement of BlockingQueue in which producers may wait for
consumers to receive elements.
• A TransferQueue may
be useful for example in message passing applications in which producers
sometimes (using method transfer(E)) await receipt of elements by
consumers invoking take or poll, while at other times enqueue
elements (via method put) without waiting for receipt.
Swing – Jlayer and LayerUI classes.
• The
JLayer class is flexible and powerful
decorator for Swing components. It enables you to draw on components and
respond to component events without modifying the underlying component
directly.
• The
LayerUI class helps us to respond to events.
• Suppose
you want to do some custom drawing atop a JButton object (decorate the JButton
object). The component you want to decorate is the target.
• Create the target component.
• Create an instance of a LayerUI subclass to
do the drawing.
• Create a JLayer object that wraps the
target and the LayerUI object.
• Use the JLayer object in your user
interface just as you would use the target component.
Transparent and non-rectangular shaped windows
Windows with transparency and
non-rectangular shape are supported
Networking – SDP
• Java
7 now supports the Sockets Direct Protocol (SDP) for applications deployed in
the Solaris Operating System ("Solaris OS") and on Linux operating
systems.
• SDP
used for high performance computing environments, where the capacity to move
data across a network quickly and efficiently is a requirement.
• One
of the most important features of this technology is Remote Direct Memory
Access (RDMA). RDMA enables moving data directly from the memory of one
computer to another computer, bypassing the operating system of both computers
and resulting in significant performance gains.
• There
are no API changes required in your code to take advantage of the SDP protocol:
the implementation is transparent and is supported by the classic networking
(java.net) and the New I/O (java.nio.channels) packages.
• We
just need a configuration file which has text similar to :
• #
Use SDP when connecting to the http server on examplecluster
• connect
examplecluster.foo.com 80
• SDP
support is disabled by default. To enable SDP support, set
the com.sun.sdp.conf system property by providing the location of the
configuration file.
XML stack
This release contains Java
API for XML Processing (JAXP) 1.4.5, supports Java Architecture for XML Binding (JAXB)
2.2.3, and supports Java API for XML Web
Services (JAX-WS) 2.2.4
No comments:
Post a Comment