8 great Java 8 Features No One ' s talking about--reprint

Source: Internet
Author: User
Tags cas

Original address: Http://www.infoq.com/articles/Java-8-Quiet-Features

If you haven ' t seen some of the videos or tutorials around Java 8, you ' ve probably been super-busy or has a more interest ing social life than I do (which isn ' t saying much). With new features like lambda expressions and Project Nashorn taking so much of the spotlight, I wanted to focus on some n EW APIs that has been a bit under the radar, but make Java 8 better in so many ways.

1. Stamped Locks

Multi-threaded code has long been the bane of server developers (just ask Oracle Java Language Architect and Concurrency G Uru Brian Goetz). Over time complex idioms were added to the core Java libraries to help minimize thread waits when accessing shared RESOURC Es. One of these is the classic Readwritelock so lets you divide code into sections that need to be mutually exclusive (writ ERS), and sections that don ' t (readers).

On paper the This sounds great. The problem is and the Readwritelock can be super slow  (up to 10x) and which kind of defeats its purpose. Java 8 introduces a new ReadWrite Lock–called stampedlock. The good news here's is, this is seriously fast. The bad news was that it's more complicated-to-use and lugs-around more state. It's also not reentrant, which means a thread can has the dubious pleasure of deadlocking against itself.

Stampedlock have an "optimistic" mode, issues a stamp that's returned by each locking operation to serve as a sort of Admission ticket; Each of the unlock operation needs to is passed its correlating stamp. Any thread this happens to acquire a write lock while a reader is holding an optimistic lock, would cause the optimistic U Nlock to being invalidated (the stamp is no longer valid). At the application can start all over, perhaps with a pessimistic lock (also implemented in Stampedlock.) Managing that was up to you, and one stamp cannot was used to unlock another–so be super careful.

Let's see this lock in action-

LongStamp =Lock. Tryoptimisticread ();//Non blocking path-super fastWork ();//we ' re hoping no writing would go on the The Meanwhile if (lock . Validate (stamp)) {//success! no contention with a writer thread} Else {//another thread must has acquired a write lock in the meanwhile, changing the stamp.//bummer-let ' s downgrade to a heavier read lock Stamp = lock. Readlock (); This is a traditional blocking read lock try {//no writing happening nowWork (); } finally { lock. Unlock (stamp); //release using the correlating stamp}}
2. Concurrent adders

Another beautiful addition to Java 8, meant specifically for code running at scale, is the concurrent "adders". One of the most basic concurrency patterns is reading and writing the value of a numeric counter. As such, there is many ways in which can do this today, but none so efficient or elegant as what Java 8 have to offer.

Up until today this is done using Atomics, which used a direct CPU compare and swap (CAS) instruction (via the Sun.misc.Uns Afe Class) to try and set the value of a counter. The problem was, then a CAS failed due to contention, the Atomicinteger would spin, continually retrying the CAs in an Infinite Loop until it succeeded. At high levels of contention this could prove to be pretty slow.

Enter Java 8 ' s longadders. This set of classes provides a convenient a-concurrently read and write numeric values at scale. Usage is super simple. Just instantiate a new longadder and use it Add () and Intvalue () methods to increase and sample the counter.

The difference between this and the old Atomics are so here, when a CAS fails due to contention, instead of spinning the CPU, the Adder would store the delta in a internal cell object allocated for that thread. It would then add this value along with any other pending cells to the result of Intvalue (). This reduces, need to go, and CAS or block other threads.

If you ' re asking yourself when should I prefer to use concurrent adders over Atomics to manage counters? The simple answer is–always.

3. Parallel Sorting

Just as concurrent adders speed up counting, Java 8 delivers a concise-to-speed up sorting. The recipe is pretty simple. Instead of-

Array. Sort (MyArray);

You can now use–

Arrays. Parallelsort (MyArray);

This would automatically break up the target collection into several parts, which would be sorted independently across a num ber of cores and then grouped back together. The only caveat this is if called in highly multi-threaded environments, such as a busy web container, the benefits Of this approach would begin to diminish (by more than 90%) due to the cost of increased CPU context switches.

4. Switching to the new Date API

Java 8 introduces a complete new date-time API. You kind of know it's about time if most of the methods of the current one is marked as deprecated ... The new API brings ease-of-use and accuracy long provided by the popular Joda time API into the core Java library.

As with any new API the good news was that it's more elegant and functional. Unfortunately there is still vast amounts of code out there using the old APIs, and that won ' t change any time soon.

To help bridge the gap between the old and new API's, the venerable Date class now has a new method called Toinstant () whi CH converts the Date into the new representation. This can is especially effective in those cases where do you ' re working on a API that expects the classic form, but would li Ke to enjoy everything the new API have to offer.

5. Controlling OS Processes

Launching an OS process from within your code are right there with JNI Calls–it ' s something you do half-knowing there ' s a Good chance you ' re going-get some unexpected results and some really bad exceptions down the line.

Even so, it ' s a necessary evil. But processes has another nasty angle to them-they has a tendency to dangle. The problem with launching process from within, Java code so, has been, is a-hard-to-control a process once it was launched.

To help us with this Java 8 introduces three new methods in the Process class-

    1. Destroyforcibly-terminates a process with a much higher degree of success than before.
    2. IsAlive tells if a process launched by your code is still alive.
    3. A new overload for WaitFor () lets your specify the amount of time you want to wait for the process to finish. This returns whether the process exited successfully or timed-out in which case you might terminate it.

Double good use-cases for these new methods is-

    • If the process does not have finish in time, terminate and move forward:
Timeunit. MILLISECONDS)) {       }else {    process.destroyforcibly ();}
    • Make sure this before your code is do, you ' re not leaving any processes behind. Dangling processes can slowly but surely deplete your OS.
(Process  if (P.isalive ()) {             p.destroyforcibly ();       }}
6. Exact Numeric Operations

Numeric overflows can cause some of the nastiest bugs due to their implicit nature. This is especially true in the systems where int values (such as counters) grow over time. In those cases things this work well in staging, and even during long periods in production, can start breaking in the Wei Rdest of ways, when operations begin to overflow and produce completely unexpected values.

To help with this Java 8 have added several new "exact" methods to the Math class geared towards protecting sensitive code From implicit overflows, by throwing a unchecked arithmeticexception when the value of a operation overflows its precisi Mnl

int Math //would throw arithmeticexception if result exceeds +-2^31

The only downside are that it's up to your find those places in your code where overflows can happen. Not a automagical solution by any stretch, but I guess it's better than nothing.

7. Secure Random Generation

Java have been under fire for several years for have security holes. Justified or not, a lot of work have been done to fortify the JVM and frameworks from possible attacks. Random numbers with a low-level of entropy make systems this use random number generators to create encryption keys or have H sensitive information more susceptible to hacking.

So far selection of the Random number Generation algorithms have been left to the developer. The problem is a where implementations depend on specific HARDWARE/OS/JVM, the desired algorithm Le. In such cases applications has a tendency to the default to weaker generators, and which can put them at greater risk of attack.

Java 8 has added a new method called Securerandom.getinstancestrong () whose aim was to have the JVM choose a secure provide R for you. If you ' re writing code without complete control of the OS/HARDWARE/JVM on which it would run (which is very common whe n Deploying to the Cloud or PaaS), my suggestion are to give this approach some serious consideration.

8. Optional References

Nulpointers is like stubbing your toes-you ' ve been doing it since your could stand up, and no matter how smart is T Oday-chances is still do. To the age-old problem Java 8 is introducing a new template called Optional<t>.

Borrowing from Scala and Haskell, this template was meant to explicitly state when a reference passed to or returned by a F Unction can be null. This was meant to reduce the guessing game of whether a reference can being null, through over-reliance on documentation which May is out-of-date, or reading code which.

Optional<User> Tryfinduser (int UserID) {

Or-

void processuser (UserOptional<Cart> ShoppingCart) {

The Optional template has a set of functions that make sampling it more convenient, such asispresent () to check if an non- Null value is available, or ifpresent () to which you can pass a LAMBDA function that'll be executed if IsPresent is Tru E. The downside is a much like with Java 8 ' s new Date-time APIs, it'll take time and work till this pattern takes hol D and is absorbed to the libraries we use and design everyday.

New LAMBDA syntax for printing an optional value-

Value.ifpresent (System.  out::print);
About the Author

Tal Weiss is the CEO of Takipi. Tal has been designing scalable, real-time Java and C + + applications for the past years. He still enjoys analyzing a good bug though, and instrumenting Java code. In He free time Tal plays Jazz drums.

8 great Java 8 Features No One ' s talking about--reprint

Related Article

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.