Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


Next >>     


Completable Future Enhancement



Java 8 introduced the CompletableFuture<T> class, which is a java.util.concurrent.Future<T> that may be explicitly completed (setting its value and status), and may be used as a java.util.concurrent.CompletionStage, supporting dependent functions and actions that are triggered upon the future's completion. Java 9 introduces several enhancements to CompletableFuture:

  • support for delays and timeouts
  • improved support for subclassing
  • new factory methods

One of the things that excited us the most is the copy() method that returns an immutable copy of an existing CompletableFuture. In the code snippet below we construct a CompletableFuture, make a copy of it and show that completing the copy doesn't influence the original future object. This is incredibly useful when you offer an asynchronous API that returns CompletableFutures. Before you had to jump through hoops to avoid situations where clients can complete the future you returned. Now it's a matter of calling the copy() method.


CF_CompleteOnTimeoutExample.java

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CF_CompleteOnTimeoutExample {

private static final int TIMEOUT = 3;

public static void main(String[] args) {
try {
CompletableFuture<String> future = doProcessing("Javalogin")
.completeOnTimeout("Java Technology", TIMEOUT,
TimeUnit.SECONDS).whenComplete((result, error) -> {
if (error == null) {
System.out.println("The result is: " + result);
} else {
// this statement will never run.
System.out.println("Sorry, timeout in "
+ TIMEOUT + " seconds.");
}
});

String result = future.get();
System.out.println("Result >> " + result);
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
}

private static CompletableFuture doProcessing(String s) {

return CompletableFuture.supplyAsync(() -> {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("inside doProcessing " + i + " s");
}
return s + ".com";
});
}
}



CF_OrTimeoutExample.java

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CF_OrTimeoutExample {

private static final int TIMEOUT = 3;

public static void main(String[] args) {
try {
CompletableFuture<String> future =
completableFuturepProcess("value2")
.orTimeout(TIMEOUT, TimeUnit.SECONDS) .whenComplete((result, error) -> {

if (error == null) {
System.out.println("The result is: " + result);
} else {
System.out.println("Sorry, timeout in "
+ TIMEOUT + " seconds");
}
});

String content;
content = future.get();
System.out.println("Result >> " + content);
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
}

private static CompletableFuture<String>
completableFuturepProcess(String s) {

return CompletableFuture.supplyAsync(() -> {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("running inside completableFuturepProcess()... " + i + " s");
}
return s + ".com";
});
}
}


delayedExecutorExample

private static void delayedExecutorExample() {
CompletableFuture<String> future = new CompletableFuture<>();
future.completeAsync(() -> {
try {
System.out.println("inside delayedExecutorExample:
processing data...");

return "javalogin.com";
} catch (Throwable e) {
return "not detected";
}
}, CompletableFuture.delayedExecutor(3, TimeUnit.SECONDS))
.thenAccept(result -> System.out.println("accept: " + result));

// other statements
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("running outside... " + i + " s");
}
}

copyMetodExample

private static void copyMetodExample() {
CompletableFuture<String> nameFuture
= CompletableFuture.supplyAsync(() -> "javalogin");
CompletableFuture<String> nameFutureCopy = nameFuture.copy();
CompletableFuture<String> withSurname =
nameFuture.thenApply(name -> "javalogin author");

// Should be avoided, only for demonstration purpose
System.out.println(withSurname.join());

// Change in original instance should affect it's copy instance.
System.out.println(nameFutureCopy.join());
}

completeAsyncExample

private static void completeAsyncExample() {
CompletableFuture<String> completableFuture =
new CompletableFuture<>();

CompletableFuture<String> nameFuture =
completableFuture.completeAsync(() -> "Javalogin");
System.out.println(nameFuture.join());
}



New Static Factory Methods

completedFuture() - Returns a new CompletableFuture that is already completed with the given value.
completedStage() - Returns a new CompletionStage that is already completed with the given value and supports only those methods in interface CompletionStage.
failedStage() - Returns a new CompletionStage that is already completed exceptionally with the given exception and supports only those methods in interface CompletionStage

completedFuture() signature - public static CompletableFuture completedFuture(U value)

completedStage() signature - public static CompletionStage completedStage(U value)

failedStage() signature - public static CompletionStage failedStage(Throwable ex)

Static Factory Methods in Action -


CompletableFuture name = CompletableFuture.completedFuture("Javalogin");

CompletableFuture completionStage = CompletableFuture.completedStage("Javalogin");

CompletableFuture failedFuture = CompletableFuture.failedFuture(new TimeoutException());

System.out.println(failedFuture.join());



Next >>