In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "what are the eight functions of Java8 that are easy to forget". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The core library of Java constantly adds a variety of complex uses to reduce thread wait time when accessing shared resources. One of these is the classic read-write lock (ReadWriteLock), which allows you to divide the code into two parts: write operations that require mutual exclusion and read operations that do not require mutual exclusion.
It looks good on the surface. The problem is that read-write locks can be extremely slow (up to 10 times), which is contrary to its original intention. Java 8 introduces a new type of read-write lock called timestamp lock. The good news is this guy is really fast. The bad news is that it is more complex to use and has more states to deal with. And it is non-reentrant, which means that a thread may deadlock with itself.
Timestamp locks have an "optimistic" mode, in which each lock operation returns a timestamp as some kind of permission credential; each unlock 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 expired). At this point, the application needs to start all over again, perhaps using pessimistic locks (timestamp locks are also implemented). You need to take care of all this yourself, and a timestamp can only unlock its corresponding lock-you have to be very careful.
Let's take a look at an example of this lock--
Long stamp = lock.tryOptimisticRead (); / / non-blocking path-Super Fast work (); / / We hope that no writes occur at this time if (lock.validate (stamp)) {/ / success! No write interference} else {/ / another thread must have acquired the write lock at the same time, changing the timestamp / / slob said-- Let's switch to the more expensive lock stamp = lock.readLock (); / / this is a traditional read lock that blocks try {/ / No write operation can happen now work ();} finally {lock.unlock (stamp) / / unlock using the corresponding timestamp}}
Concurrent adder
Another excellent feature of Java 8 is the concurrent "adder", which is especially meaningful for code that runs on a large scale. One of the most basic concurrency modes is the reading and writing of a counter. As far as it is concerned, there are many ways to deal with this problem today, but none is more efficient or elegant than the one provided by Java 8.
So far, this problem has been solved by using the atomic class (Atomics), which directly uses CPU's compare and swap instruction (CAS) to test and set the value of the counter. The problem is that when a CAS instruction fails because of competition, the AtomicInteger class dies and so on, trying the CAS instruction in an infinite loop until it succeeds. In an environment with a high probability of competition, this implementation has proved to be very slow.
Take a look at the LongAdder of Java 8. This series of classes provides a convenient solution for a large number of code that reads and writes numeric values in parallel. It's super easy to use. Just initialize a LongAdder object and use its add () and intValue () methods to accumulate and sample counters.
This differs from the old Atomic class in that when the CAS instruction fails because of competition, Adder does not always occupy the CPU, but allocates an internal cell object to the current thread to store the increments of the counter. This value is then added to the result of intValue () along with other cell objects to be processed. This reduces the possibility of repeatedly using CAS instructions or blocking other threads.
If you ask yourself, when should you use concurrent adders instead of atomic classes to manage counters? The simple answer is-do it all the time.
Parallel sorting
Just as concurrent adders speed up counting, Java 8 also implements a concise 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 parts that are run on a separate CPU core and then merge the results. It is important to note that in an environment that uses a lot of multithreading, such as a busy Web container, the benefits of this approach are diminished (by more than 90%), as more and more CPU context switches add 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, so you know it's time to introduce a new interface. The new date interface brings ease of use and accuracy to the Java core library, which previously could only be achieved with Joda time. Joda time is a third-party date library, which is friendlier and easier to manage than the library that comes with Java.
Like any new interface, the good news is that the interface becomes more elegant and powerful. Unfortunately, there is still a lot of code using the old interface, which will not change any time soon.
To connect the old and new interfaces, the long-established Date class adds a toInstant () method to convert Date into a new representation. This approach is especially efficient when you want to enjoy both the benefits of the new interface and those that only accept the old date representation.
Control the process of operating system
If you want to start an operating system process in your code, you can do it with a JNI call-but it's always half-understood, and you're likely to get an unexpected result, accompanied by some bad exceptions along the way.
Even so, it is inevitable. But another annoying feature of processes is that they may turn into zombie processes. The current problem with running a process from Java is that once the process is started, it is difficult to control it.
To help us solve this problem, Java 8 introduces three new methods in the Process class
DestroyForcibly-- ends a process with a much higher success rate than before.
IsAlive-- inquires whether the process you started is still alive.
With waitFor () overloaded, you can now specify the time to wait for the process to finish. This interface will return when the process exits successfully, and if it times out, it will also return, because 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 move on.
If (process.wait (MY_TIMEOUT, TimeUnit.MILLISECONDS)) {/ / success} else {process.destroyForcibly ();}
Before your code ends, make sure that all processes have exited. Zombie processes gradually deplete system resources.
For (Process p: processes) {if (p.isAlive ()) {p.destroyForcibly ();}}
Accurate numerical operation
Number overflows can lead to some annoying bug because it is inherently error-free. In some systems, when integer values keep growing (such as counters), the problem of overflow is particularly serious. In these cases, the product worked well during the evolution phase, even for a long time after commercial use, but eventually a strange failure occurred because the operation began to overflow, resulting in completely unpredictable values.
To solve this problem, Java 8 adds several new "precise" methods to the Math class to protect important code from overflows by throwing an unchecked ArithmeticException exception when the operation exceeds its precision range.
Int safeC = Math.multiplyExact (bigA, bigB); / / if the result exceeds +-2 ^ 31, an ArithmeticException exception is thrown
The downside is that you have to find the code that may overflow. In any case, there is no automatic solution. But I think it's better to have these interfaces than none.
Safe random number generator
In the past few years, Java has been criticized for security vulnerabilities. Reasonable or not, Java has done a lot of work to strengthen the virtual machine and framework layer from attacks. If random numbers come from seeds that are not random, then systems that use random numbers to generate keys or hash sensitive information are more vulnerable.
So far, the random number generation algorithm has been decided by the developer. But the problem is, if the algorithm you want depends on specific hardware, operating systems, and virtual machines, you may not be able to implement it. In this case, applications tend to use weaker default generators, which exposes them to greater risk.
Java 8 adds a new method called SecureRandom.getInstanceStrong (), which aims to get the virtual machine to choose a secure random number generator for you. If your code doesn't have full control over the operating system, hardware, and virtual machines (which is common if your program is deployed to the cloud or PaaS), I suggest you seriously consider using this interface.
Optional reference
A null pointer is like "kicking to the toe"-- it's been with you since you learned to walk, no matter how smart you are now-- you'll still make this mistake. To help solve this old problem, Java 8 introduces a new template called Optional.
This template is borrowed from Scala and Hashkell to explicitly declare that a reference passed to a function or returned by a function is likely to be empty. With it, people who rely too much on old documents or see code that changes frequently don't need to guess whether a reference might be empty.
Optional tryFindUser (int userID) {
Or
Void processUser (User user, Optional shoppingCart) {
The Optional template has a set of functions that make it easier to sample, such as isPresent () to check whether the value is non-empty, or ifPresent () you can pass a Lambda function over, and if isPresent () returns true, the Lambda function will be executed. The downside is just like the new date interface in Java 8, as this pattern becomes popular and infiltrates the libraries and everyday designs we use, which will take time and effort.
Value.ifPresent (System.out::print); "what are the eight functions of Java8 that are easy to forget"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.