Eight features of the forgotten Java8

Source: Internet
Author: User
Tags cas

In Java 8 There are a few features that no one will ever talk about, and maybe it's been used before, and it's recommended to learn Java basics and reinforce tutorials, and here are eight features that nobody in Java 8 is talking about:

Time stamp Lock

Long-threaded code is a poison for server developers. The core library of Java is constantly adding complex usages to reduce the thread wait time when accessing shared resources. One of these is the classic read-write lock (Readwritelock), which lets you divide the code into two parts: a write operation that requires mutual exclusion and a read operation that does not require a mutex.

It looks pretty good on the surface. The problem is that a read-write lock can be extremely slow (up to 10 times times), which is contrary to its original intention. Java 8 introduces a new read-write lock called a timestamp lock. The good news is that this guy is really fast. The bad news is that it is more complex to use and has more state to deal with. And it is non-reentrant, which means that a thread has the possibility of being deadlocked with itself.

A timestamp lock has an optimistic mode in which each lock operation returns a timestamp as a permission credential, and each unlocking operation needs to provide its corresponding timestamp. If a thread requests a write lock and the lock happens to be held by a read operation, the unlock of the read operation will be invalidated (because the timestamp has been invalidated). This time the application needs to start over, perhaps using pessimistic mode locks (timestamp locks are also implemented). You need to do it yourself, and a timestamp can only unlock its corresponding lock--this must be done with great care.

Let's look at an example of this lock--

Concurrency Adder

Another great feature of Java 8 is the concurrency "adder", which is especially meaningful for code that runs on a large scale. One of the most basic concurrency patterns is the reading and writing of a counter. In itself, there are many ways to deal with this problem today, but none can be more efficient or elegant than the one provided by Java 8.

So far, this problem has been solved by Atomic class (Atomics), which directly uses the CPU's "compare and Exchange" instruction (CAS) to test and set the value of the counter. The problem is that when a CAS command fails because of a competition, the Atomicinteger class will death and try the CAS instructions continuously in an infinite loop until it succeeds. In an environment where competitive probabilities are high, this implementation proves to be very slow.

Look at the Longadder of Java 8. This series of classes provides a convenient solution for large numbers of parallel read and write values. Super easy to use. Simply initialize a Longadder object and use its add () and Intvalue () methods to accumulate and sample counters.

The difference between this and the old atomic class is that when a CAS instruction fails because of a competition, Adder does not always occupy the CPU, but instead allocates an internal cell object for the current thread to store the increment of the counter. The value is then added to the result of the Intvalue () along with other pending cell objects. This reduces the likelihood of repeatedly using CAS instructions or blocking other threads.

If you ask yourself, when should you use a concurrency adder instead of an atomic class to manage counters? The simple answer is--keep doing it.

Parallel Sorting

Just as the concurrency adder can speed up counting, Java 8 also implements a neat way to speed up sorting. The secret is simple. You don't do this anymore:

Array.Sort (MyArray);

Instead, do this:

Arrays.parallelsort (MyArray);

This automatically splits the target array into sections that are run on separate CPU cores and merge the results together. The only thing to note here is that in a heavily multithreaded environment, such as a busy web container, the benefits of this approach are reduced (by more than 90%), as more and more CPU context switching increases overhead.

switch to the new date interface

Java 8 introduces a new Date-time interface. Most of the methods of the current interface have been marked as deprecated, and you know it's time to launch the new interface. The new date interface brings ease of use and accuracy to the Java Core Library, which was previously only possible with Joda time (translator Note: Joda time is a third-party date library that is more user-friendly and manageable than the Java-brought library).

As with any new interface, the good news is that the interface becomes more elegant and powerful. Unfortunately, there is a lot of code in use of the old interface, this will not change for a short period of time.

To bridge the old and new interfaces, the historic date class added the Toinstant () method for converting date to a new representation. This approach is especially efficient when you want to enjoy the benefits of the new interface and the interfaces that only accept the old date representation.

controlling operating system processes

To start an operating system process in your code, you can do it with JNI calls--but this thing is always smattering, and you're likely to get an unexpected result, along with some pretty bad exceptions.

Even so, this is something that cannot be avoided. But the process also has a nasty feature--they can turn into a zombie process if they don't get it wrong. The problem with running a process from Java is that it can be difficult to control once the process is started.

To help us solve this problem, Java 8 introduces three new methods in the Process class

    1. destroyforcibly--end a process with a much higher success rate than before.
    2. isalive--query Whether the process you started is still alive.
    3. Overloaded with waitfor (), you can now specify the time to wait for the process to end. This interface will return when the process exits successfully, and will return if it is timed out, as you may have to terminate it manually.

Here are two good examples of how to use these new methods--

If the process does not exit within the specified time, terminate it and continue to move forward.

if (process.wait (My_timeout, timeunit.milliseconds)) {//Success}else {process.destroyforcibly ();}

Before your code ends, make sure that all processes have exited. The zombie process will gradually deplete the system resources. for (Process p:processes) {if (p.isalive ()) {p.destroyforcibly ();}}

Precise numeric operations

A digital overflow can cause some nasty bugs because it's inherently error-prone. In some systems, the integer value is constantly increasing (for example, the counter), the problem of overflow is particularly serious. In these cases, the product runs well in the evolution phase, even after a long period of business, but it will eventually be a strange failure, because the operation begins to overflow, resulting in a completely unpredictable value.

To solve this problem, Java 8 adds several new "exact" methods to the math class to protect important code from overflow, by throwing an unchecked arithmeticexception exception when the operation exceeds its range of accuracy.

int safec = Math.multiplyexact (Biga, BIGB); If the result exceeds +-2^31, the ArithmeticException exception is thrown

The only downside is that you have to identify the code that might generate the overflow. In any case, there is no automatic solution. But I think having these interfaces is always better than nothing.

secure random number generator

In the past few years, Java has been plagued by security breaches. Whether justified or not, Java has done a lot of work to strengthen the virtual machine and the framework layer to protect it from attack. If the random number comes from a seed that is not random, then those systems that use random numbers to generate keys or hash sensitive information are more vulnerable.

So far, the random number algorithm has been determined by the developer. The problem is that if you want the algorithm to depend on a specific hardware, operating system, virtual machine, then you may not be able to implement it. In this case, the application tends to use a weaker default generator, which exposes them to greater risk.

Java 8 Adds a new method called Securerandom.getinstancestrong (), whose goal is to have the virtual machine choose a safe random number generator for you. If your code does not fully control the operating system, hardware, virtual machines (which is common if your program is deployed to the cloud or PAAs), I recommend that you seriously consider using this interface.

Optional References

A null pointer is like "kick to Toe"--from the moment you learn to walk accompanied with you, no matter how smart you are now--you still make that mistake. To help solve this old problem, Java 8 introduced a new template called optional.

This template is borrowed from Scala and Hashkell, and it is possible to explicitly declare that the reference to a function or function return is empty. With it, people who rely too much on old documents or have seen code change often don't need to guess whether a reference is likely to be empty.

Optionaltryfinduser (int userID) {

Or

void Processuser (user user, Optionalshoppingcart) {

The optional template has a function that makes it easier to sample it, such as ispresent () to check if the value is non-null, or ifpresent () you can pass a lambda function past, if Ispresent () returns True, This lambda function will be executed. The downside is the same as the new date interface for Java 8, which is becoming popular, and it takes time and effort to penetrate the libraries we use and the everyday design.

Eight features for you to introduce here, you can actually understand that you want to learn the programming language tutorial knowledge Please login e mentor network.

Eight features of the forgotten Java8

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.