JSE 8 was released in early 2014. In Java 8, the most talked-about lambda expressions were. It has many other important features, such as standard methods, feed API, and new date/time API.
We will explore these new features in Java 8 through examples.
- Lambda expression
- Functional interface
- Standard methods
- Date/time API changes
Lambda expressions are very well known to many of us who work in other popular programming languages, such as Scala. In the Java programming language, a lambda expression (or a lambda function) is simply an anonymous function, that is, a function with no name and no association with an identifier. They are saved exactly where they are needed, usually as parameters for another function.
Rules for writing lambda expressions:
- A lambda expression can have zero, one, or more parameters in it.
- The type of parameters can be declared explicitly or derived from the context.
- Several parameters are enclosed in mandatory brackets and separated by commas. Empty brackets are used to represent an empty parameter set.
- If there is only one parameter and its type is derived, there is no need to use parentheses. for example. a -> returns a * a.
- The lambda expression body can contain zero, one, or more instructions.
- If the body of the lambda expression contains a single statement, the braces are not required and the return type of the anonymous function is the same as that of the body expression. If there is more than one statement in the body, they must be placed in parentheses.
Functional interfaces are also called interfaces of individual abstract methods (SAM interfaces). As the name suggests, they allow for exactly an abstract method in itself. Java 8 features an annotation, @FunctionalInterface, which can be used for errors at the compiler level when the interface you note violates the functional interface contracts.
Note that a functional interface is also valid if the @FunctionalInterface annotation is omitted. This is used only to tell the compiler to use a single abstract method within the interface.
Since the standard methods are not abstract, you can add as many as you like to the function interface.
Another important point to keep in mind is that if an interface declares an abstract method that overrides one of the public methods of java.lang.Object, it also does not count for the number of abstract methods in the interface, as each Implementation of the interface will be a Java implementation .lang.Object or elsewhere. Learning Java8 can be much more fruitful if you give it a try by visiting Java Classes in Pune
Java 8 does not allow adding abstract methods to interfaces. These methods must be declared as standard methods. Standard methods were introduced in Java 8 to enable lambda expression functionality.
Using standard methods, you can add new functionality to your library’s interfaces and provide binary compatibility with code written for older versions of these interfaces.
Java 8 Stream
Another major change introduced the Java 8 Streams API, which provides a mechanism for manipulating a data set in a variety of ways, including filtering, transforming, or any other means that might be useful for an application.
The Streams API in Java 8 supports a different type of iteration where you simply define the number of items to process, the operations to be performed on each item, and where to store the output from those operations.
An example of a feed API. In this example, the elements are a collection of string values. You want to remove entries that begin with the prefix text.
Java 8 Date/Time API Changes
The new Date and Time APIs/classes (JSR-310), also called as ThreeTen, have simply change the way you have been handling dates in java applications.
Date class has even become obsolete. The new classes intended to replace the Date class are LocalDate, LocalTime, and LocalDateTime.
- The LocalDate class represents a date. There is no representation of a time or time zone available.
- The LocalTime class represents a time. There is no representation of a date or time zone available.
- The LocalDateTime class represents a date-time. There is no representation of a time zone available.
If you want to use the date functionality with zone information, then Lambda provides you extra 3 classes similar to the above one i.e. OffsetDate, OffsetTime, and OffsetDateTime. Timezone offset can be represented in “+05:30” or “Europe/Paris” formats. This has been done via using another class i.e. ZoneId.
|LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.of(12, 20);
LocalDateTime localDateTime = LocalDateTime.now();
OffsetDateTime offsetDateTime = OffsetDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(“Europe/Paris”));
Timestamp and Duration
For representing the specific timestamp at any moment, the class that needs to be used is Instant. The Instant class represents an instant in time to a validity of nanoseconds. Operations on an Instant include a collation to another Instant and adding or subtracting a duration.
Duration class is a whole new concept brought first time in the java language. It represents the time difference between two-time stamps.
Duration works on a small unit of time such as milliseconds, seconds, minutes, and hours. They are much more suitable for interacting with application code. While interacting with humans, you need to get bigger durations which are presented with Period class.
Multithreaded code has long been the bane of server developers (ask Oracle Java Language Architect and competition guru Brian Goetz). Over time, complex idioms have been added to the main Java libraries to minimize the waiting time for threads to access shared resources. One of them is the classic ReadWriteLock, which allows you to divide the code into sections that must be mutually exclusive (writers) and sections that are not (readers).
That sounds good on paper. The problem is that ReadWriteLock can be very slow (up to 10x), which does the wrong thing. Java 8 introduces a new ReadWrite lock – StampedLock. The good news here is that this guy is really fast. The bad news is that it is more complicated to use and contains more states. It is also non-reentrant, which means that a topic can have the dubious pleasure of holding on to itself.
StampedLock has an “optimistic” mode that produces a buffer that is returned by each blocking operation to serve as a kind of entry ticket. Each unlocks operation must receive its correlation buffer. Any thread that receives a write lock while a unit is holding an optimistic lock will invalidate the optimistic unlock (the buffer is no longer valid). At this point, the application can be restarted, possibly with a pessimistic lock (also implemented in StampedLock). Handling is up to you, and one buffer cannot be used to unlock another. So be very careful.
Another good addition to Java 8 that is specifically aimed at large code is simultaneous “adders”. One of the most basic competitive models is to read and write the value of a digital accountant. So there are many ways to do this today, but none is as efficient or elegant as what Java 8 has to offer.
This was previously done with Atomics, which used a direct CPU Compare and Swap (CAS) command (via the sun.misc.Unsafe class) to set the value of a counter. The problem was that when a CAS fails due to a conflict, AtomicInteger spins and the CAS repeats itself in an infinite loop until it succeeds. If you are very reluctant, it can end up being very slow.
Insert the Java 8 LongAdders. These classes provide a convenient way to read and write numerical values to scale at the same time. The operation is super easy. Just instantiate a new LongAdder and use the add () and intValue () methods to increment and sample the counter.
The difference between this and the old Atomics is that the adder here stores the delta in an internal cell object assigned to that thread when a CAS fails due to a conflict, instead of spinning the CPU. This value is then added to the result of intValue () along with any other pending cells. This reduces the need to roll back and CAS or block other threads.
Just as simultaneous adders speed up counting, Java 8 offers an interesting way to speed up sorting. The recipe is very simple. Rather than –
Now you can use –
This automatically divides the target collection into several parts, which are classified independently of each other according to multiple cores and then combined into groups. The only caveat is that the cost of switching context reduces the benefits of this approach (by more than 90%) when used in highly multithreaded environments, such as the Internet. B. a busy web container. Increased CPUs.
Learning Java8 can be much more fruitful if you give it a try by visiting Java Classes in Pune as they have 100% placement assurance.