2017 you can't miss the Java class library __java

Source: Internet
Author: User
Tags connection pooling
2017 You can't miss the Java class library

Dear Readers,

This article was sorted out after I read an introductory article by Andres Almiray.

Because the content is very good, I will organize it into a reference list to share with you, along with the features of each library profile and examples.

Please enjoy. Guice

Guice (pronounced with ' juice ') is a lightweight dependency injection framework developed by Google that is suitable for more than 6 Java versions.

# Typical dependency Injectionpublic class Databasetransactionlogprovider implements Provider<transactionlog> c2/> @Inject Connection Connection;  Public TransactionLog get () {return    new Databasetransactionlog (connection);
  }
} # Factorymodulebuilder generates factory using your Interfacepublic interface Paymentfactory {Payment
   Create (Date St Artdate, money amount);
 }

GitHub, JavaDoc, use guide, Factorymodulebuilder okhttp

HTTP is a way for modern applications to connect to the Internet, and also a tool for data and media exchange. Using HTTP efficiently enables you to load things faster and save bandwidth.

Okhttp is a very efficient HTTP client, by default:

Supports HTTP/2, allowing a single socket to be shared with a request to the same host.

If HTTP/2 is unavailable, connection pooling reduces request latency.

Transparent gzip can reduce download traffic.

The cache of responses avoids duplicate network requests.

Okhttpclient client = new Okhttpclient (); String run (string url) throws IOException {
  Request request = new Request.builder ()
      . URL (URL)
      . Build ();

  Response Response = client.newcall (Request). Execute ();  Return Response.body (). String ();

GitHub, Website

Retrofit

Retrofit is a type-safe HTTP client under Square that supports Android and Java, which translates your HTTP APIs into Java interfaces.

Retrofit converts HTTP APIs to Java interfaces:

Public interface Githubservice {    @GET ("Users/{user}/repos")
    Call<list<repo>listrepos (@Path ("User ") String user);
Retrofit class implements Githubservice interface:

RETROFIT RETROFIT = new Retrofit.builder ()
    . BaseURL ("https://api.github.com/")
    . Build ();

Githubservice service = retrofit.create (Githubservice.class);

Each call from Githubservice can generate an asynchronous or synchronous HTTP request for a remote Web service:

call<list<repo>> repos = Service.listrepos ("Octocat");

GitHub, Website

jdeferred

Java Deferred/promise Class library similar to jquery

Deferred Objects and Promise

Promise callback:. Then (...),. Done (...),. Fail (...),. Progress (...),. Always (...)

Supports multiple promises-. When (P1, p2, p3, ...). Then (...)

Callable and Runnable-wrappers.when (new Runnable () {...})

Using the Executor service

Support Java generics: Deferred<integer, Exception, doubledeferred;, Deferred.resolve (a);, Deferred.reject (New Exception ());, Deferred.notify (0.80);,

Support Android

Java 8 Lambda Friendly support

Githu links, official website links Rxjava

RXJAVA–JVM's responsive programming extension – is a class library for Java virtual machines that uses observable sequences to build asynchronous event-based programs.

It implements the sequence of data/events based on the observer pattern, and adds some operators that allow you to build the sequence declaratively, leaving developers with no concern for low-level threads, synchronization, thread safety, and concurrent data structures.

One of the most common uses of Rxjava is to run some computation and network requests in a background thread, and to display results (or errors) on the UI thread:

Flowable.fromcallable (()-{
     thread.sleep (1000);//imitate expensive-computation return
     ' done ';
 })
   . Subscribeon (Schedulers.io ())
   . Observeon (Schedulers.single ())
   . Subscribe (system.out::p rintln, Throwable: :p rintstacktrace);

 Thread.Sleep (2000); <---Wait for the "flow" to finish

GitHub, Wiki Mbassador

Mbassador is a lightweight, High-performance event bus that implements the publish-subscribe model. It is easy to use and strives to be rich and extensible, while ensuring efficient utilization and high performance of resources.

The core of Mbassador's high performance is a professional data structure that provides non-blocking readers and minimizes the lock contention of the writer, so the performance attenuation of concurrent read and write access is minimal.

Note-driven

Provide anything to be cautious about type hierarchies

Synchronous and asynchronous Message delivery

Types of references that can be configured

Message filtering

Encapsulated messages

Priority of the processor

Custom error Handling

Scalability

Define your listenerclass simplefilelistener{    @Handler public
    void handle (File msg) {      //does something with The file
    }
}//somewhere else in your Codembassador = new Mbassador ();
Object listener = new Simplefilelistener ();
Bus.subscribe (listener);
Bus.post (New File ("/tmp/smallfile.csv")). Now ();
Bus.post (New File ("/tmp/bigfile.csv")). asynchronously ();

GitHub, Javadoc Lombok Project

Use annotations to reduce repetitive code in Java, such as Getter,setters, Non-empty checks, generated builder, and so on.

Val--finally got it. The final local variable of worry-free.

@NonNull-or: How do I learn to stop worrying and fall in love with a Non-empty exception (NullPointerException).

@Cleanup-Automatic resource management: Secure call to your close () method without any trouble.

@Getter/@Setter-no more need to write public int getfoo () {return foo;} Out.

@ToString-No need to start the debugger to check your field: Let Lombok to generate a ToString method for you.

@EqualsAndHashCode-it's easy to make equal judgments: it generates hashcode and equals methods for you from the field of your object.

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor-Custom constructors: Generate a variety of constructors for you, including those without parameters, Each final or Non-null field is a parameter, or each field is an argument.

@Data-All are generated at the same time: This is a shortcut that can generate @tostring for all fields, @EqualsAndHashCode, @Getter annotations, and generate @setter annotations for all non final fields, and generate @requiredargsconstructor.

@Value-Declaring an immutable class becomes very easy.

@Builder-... And Bob is your uncle: Create an uncontested and luxurious interface to the object.

@SneakyThrows-boldly throw in places where no one has thrown a check-type anomaly before.

@Synchronized-Correct implementation sync: Don't expose your locks.

@Getter (Lazy=true) laziness is a virtue.

@Log-captain's log, Ephemeris 24435.7: "What is that line?" ”

GitHub, Website java simple log façade (SLF4J)

The Java simple log façade (SLF4J) provides a simple façade or abstract implementation for different log frames (such as java.util.logging, Logback, log4j), allowing end users to access the log framework they want to use when they deploy.

In short, class libraries and other embedded components should consider using SLF4J as their log requirements because class libraries cannot impose their choice of log frames on end users. On the other hand, for independent applications, it is not necessary to use SLF4J. Standalone applications can directly invoke the log frame of their choice. For Logback, the problem is meaningless because Logback exposes its log interface through SLF4J.

Website, GitHub, FAQ junitparams

It's good to parameterize the test.

       @Test
       @Parameters ({"False", 
                    "true"}) public       void Personisadult (int age, Boolean valid) throws Exception {
         assertthat (new person (age). Isadult (), is (valid));
       

The difference from the standard junit parameterized runtime is as follows:

More explicit – The argument is actually in the parameter of the test method, not in the field of the class

Less code-you don't need to use constructors to set parameters

You can mix parameterized and nonparametric methods in the same class.

Parameters can be passed in by a CSV string or a parameter.

The parameter provider class can have as many parameters as possible to provide methods so that you can categorize different use cases.

You can have a test method that can provide parameters (no external classes or static classes are required)

You can see the actual parameter values in your integrated development tool (and in JUnit's parametrised, only the number of consecutive arguments)

Official website, GitHub, QuickStart Mockito

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.