Pasang Iklan Atas 1

Down Menu

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, October 23, 2018

9 Buku Pemrograman Java yang Harus Dibaca

These top Java programming books are some of the best books to learn Java — I would even say that some of them are the best Java books ever published. Whenever a programmer starts learning the Java programming language, the first question he asks is, "Which book should I refer to learn Java?," or "What is the best book to learn Java for beginners?," or "Can you tell me some good books to learn Java?" That, itself, says how important Java books are for programmers especially beginners.  Despite having so many free resources available in Java, like tutorials, tips, blogs, and code examples, Java books have their own place because of these two reasons:
  • They are written by programmers who are an authority in the subject
  • They cover the subject with more details and explanation.
These Java books are my personal favorites, and whenever I get some time, I prefer to read them to refresh my knowledge. Though I have read many of them already (I have read Effective Java at least four times), I always want to learn something new. These books are the best available today and equally useful for beginners, intermediate, and advanced Java programmers.
It doesn't matter whether you are completely new to Java or have been programming in Java for over five years, you will learn a lot of new things through these books.
Having said that, not all books are equally suitable for all programmers. For beginners, Head First Java is the best book to get started, and for the advanced Java developer, Effective Java is a good book to start with.

9 Good Books to Learn Java Programming

Here is my collection of Java books that I suggest to every programmer who wants to learn Java. It contains books for both beginners and experienced programmers.
These books cover a variety of areas, including core Java fundamentals, the Java collection framework, multithreading and concurrency, JVM internals and performance tuning, design patterns, etc.

Head First Java

Head First Java is the best book for any programmer who is new in both programming and Java. The head-first way of explanation is quite a phenomenal and I really enjoyed their book.
Head First Java covers the essential Java programming knowledge about class, object, thread, collection, and language features, like generics, enums, variable arguments, or auto-boxing.
They also have some advanced section on Swing, networking, and Java IO, which makes them a complete package for Java beginners. This should be your first Java book you look at if you're starting from scratch. 
Best book to start learning Java programming

If you prefer online courses over books, then you can also check out Udemy's Complete Java MasterClass course.
This is a free course, and you can also have a 10-day free trial to get the benefit of other Java programming courses.

Head First Design Patterns

Head First Design Pattern is another top class Java book from the Head-First lab.
When I started reading this book back in 2006, I didn't think much about design patterns, how they solve common problems, how to apply a design pattern, what benefits they provide, and all sort of basic things, but after reading this Java book, I benefited immensely.
The first chapter on inheritance and composition, which is simply fantastic and promotes improved practices by introducing a problem and then the solution.
Good book to learn Java Design pattern
This book also contains helpful bullet points, exercises,and memory maps, which help you to understand design patterns quickly.
If you want to learn core Java design patterns and object-oriented design principles, this is the first Java book you should check out. 
If you are looking for a course on GOF or object-oriented design patterns, I suggest you check out Design Pattern Library, one of the best course I have attended on design patterns so far.
One point of good news about this book is that the new edition is updated for Java SE 8, which will teach you how to develop classic GOF design pattern using Java 8 features, e.g. lambda expressions and streams.

Effective Java

Effective Java is one of the best or top Java books in my record and most enjoyable. I have high regards for Joshua Bloch, the writer of this book, for his contribution in the Java collection framework and Java concurrency package.
Effective Java is best for a seasoned or experienced programmer who is well versed in Java programming and wants to share their skill by following programming best practices and eager to listen to someone who contributed to the Java development kit (JDK).
The Best Must Read book for Java Programmer
Effective Java consists of a collection of Java programming best practices, ranging from static factories, serialization, equals, and hashcode to generics, enums, varargs, and reflection.
This Java programming book covers almost every aspect of Java in a slightly different way than you are used to.
A new edition was released last year that introduced features in the JDK 7, 8, and 9, which was released this year in September.  It will also have a full chapter on lambdas.

Java Concurrency in Practice

Java Concurrency in Practice is another classic from Joshua Bloch, Doug Lea, and team. The is the best Java book on concurrency and multi-threading — one of the must-reads for core Java developers.
The strength of Concurrency Practice in Java includes:
1) This book is very detailed and captures minor details of multi-threading and concurrency
2) Instead of focusing on core Java classes, this book focuses on concurrency issues and problems, like deadlock, starvation, thread-safety, race conditions, and present ways to solve them using Java concurrency classes.
This book is an excellent resource to learn and master Java concurrency packages and classes, like CountDownLatchCyclicBarrierBlockingQueue, or Semaphore. This is the biggest reason I like to read this Java book and read again and again.
Best book on multithreading and concurrency in Java
3) One more strong point of concurrency practice in Java is through no-nonsense examples; the examples in this book are clear, concise, and intelligent.
4) This book is also good at explaining what is wrong and why its wrong and how to make it right, which is essential for any Java book to succeed.
In short, this is one of the best books to learn concurrency and multi-threading in Java. The content is definitely advanced from a beginner's perspective, but surely, this is a must-read book for experienced Java programmers.

Java Generics and Collections

Java Generics and Collection by Naftalin and Philip Wadler from O'Reilly is another good book on Java, which I initially forgot to include in my list but am including it now as requested by many readers.
I like this book because of its content on generics and collections, which are core areas of the Java language.
Having a strong knowledge of Java collections and generics are expected from any experienced programmer, and these books help in that area.
Book to Learn Java Generics and Collection
It explains each of collection interface, e.g. Set, List, Map, Queue, and their implementation, comparing how well they perform in a different situation.
I really loved their comparison chart at the end of each chapter, which gives you a good idea about when to use a particular Java collection class, e.g. ArrayListHashMap, or  LinkedHashMap.

Java Performance From Binu John

This is another good book that teaches about JVM internals, garbage collection, JVM tuning, profiling. etc, and I highly recommend every senior Java developer read this book. This is also one of my personal favorites.
As we are moving gradually, we started from a beginners level to intermediate and now the senior level.
Java Performance is all about performance monitoring, profiling, and tools used for Java performance monitoring.
This is not a usual programming book, Instead, It provides details about JVMGarbage CollectionJava heap monitoring and profiling application.
I loved their chapter on the JVM overview, and it's a must read to learn more about JVM in simple language.
Books Every experienced Java developer Should read
Both beginners and an intermediate programmer can benefit from this book, but it's good to have some Java experience under your belt before reading this book. So far, this is the best Java book on performance monitoring.
This is another must-read Java book if you are serious about performance.
Update: There are a couple of new books available in Java, which covers JDK 1.7, to find out latest book on Java performance e.g.  Java Performance, The Definitive Guide by Scott Oaks, which is certainly worth checking out before buying this book.

Java Puzzlers

Java Puzzlers is another book worth reading from Joshua Bloch, this time with Neal Gafter. This book is about corner cases and pitfalls in the Java programming language.
Java is safer and more secure than C++, and the JVM does a good job to free the programmer from error-prone memory allocation and deallocation, but still, Java has corner-cases that can surprise even the experienced Java programmer.
Best book in Java
This Java books presents such Java pitfalls and explains them in greater detail. This is a good Java book if you love puzzles, You can even include many of these in core Java interviews to check their Java knowledge.
I don't rate it as high as Effective Java and Java Concurrency in Practice, but still, you can give it a go, particularly to check your knowledge about Java and its corner cases, which will help you to answer some of the tricky Java questions from interviews.
In order to get most of this Java book, it tries to solve puzzles by yourself and then look into explanations to make your knowledge more concrete.

Head First Object-Oriented Analysis and Design

Another good book on Java programming and design principles from the Head-First series. Head First Object-Oriented Analysis and Design can be read in conjunction with Head First Design Patterns.
This book focuses on object-oriented design principles, like favor Composition over inheritance, programming for interface rather than implementation, DRY, etc.
Good book to learn object oriented analysis and design
One part of learning Java is writing good code and following the best practices, and this book is great in educating programmers about them.
Knowledge gained from this book is applicable to many object-oriented programming languages and will, overall, improve your understanding of code and OOP design principles.

Thinking in Java

Thinking in Java is written by Bruce Eckel, who is also the author of Thinking in C++ and uses his unique style to teach the Java concept.
Many would agree that this is one of the best Java books, with a strength being that is points to intelligent examples. This is one of the complete books in Java and can be used as a reference as well.
There is a chapter on Java memory mapped IO from Thinking in Java, which is my favorite.
Good book for Java programmer Thinking in Java
I would say this is another book that demands a space on the Java programmer's shelf.
If you don't like the Head-First teaching style, but you need a beginners Java book with a plain example style, Thinking in Java is a good choice.
It is detailed, matured, and frequently updated, but, if you need more choices, you can check out these core Java books for beginners, as well.
This was my list of top Java programming books. I have read all the books, some of them I am still reading and a couple of them, like Effective Java and the Head-First series, I have read a couple of times. Many programmers ask me which books they should start with and which Java book they should read now. I hope you found some good books in this collection. Happy reading!

Introduction to Reactive APIs With Postgres, R2DBC, Spring Data JDBC and Spring WebFlux

Saya tahu - ada BANYAK teknologi yang tercantum dalam judul artikel ini. Spring WebFlux telah diperkenalkan dengan Spring 5 dan Spring Boot 2 sebagai proyek untuk membangun aplikasi web reaktif-stack. Saya telah menjelaskan cara menggunakannya bersama Spring Boot dan Spring Cloud untuk membangun microservices reaktif dalam artikel itu: Reactive Microservices dengan Spring WebFlux dan Spring Cloud. Spring 5 juga telah memperkenalkan proyek-proyek yang mendukung akses reaktif ke database NoSQL, seperti Cassandra, MongoDB, atau Couchbase. Namun, masih ada kurangnya dukungan untuk reaktif untuk menyediakan akses ke database relasional. Perubahan ini datang bersamaan dengan proyek R2DBC (Reactive Relational Database Connectivity). Proyek itu juga sedang dikembangkan oleh anggota Pivotal. Tampaknya ini adalah inisiatif yang sangat menarik, namun pada awal perjalanan. Bagaimanapun, ada modul untuk integrasi dengan Postgres, dan kami akan menggunakannya untuk aplikasi demo kami.
R2DBC tidak akan menjadi satu-satunya solusi baru yang menarik yang dijelaskan dalam artikel ini. Saya juga akan menunjukkan kepada Anda bagaimana menggunakan Spring Data JDBC - proyek lain yang sangat menarik yang dirilis baru-baru ini. Perlu disebutkan fitur Spring Data JDBC. Proyek ini telah dirilis dan tersedia di bawah versi 1.0. Ini adalah bagian dari kerangka Data Musim Semi yang lebih besar. Ini menawarkan abstraksi repositori berdasarkan JDBC. Alasan utama pembuatan pustaka tersebut adalah untuk mengizinkan akses ke basis data relasional menggunakan Data Musim Semi (melalui antarmuka CrudRepository) tanpa menyertakan pustaka JPA ke dependensi aplikasi. Tentu saja, JPA masih tetap merupakan API persistensi utama yang digunakan untuk aplikasi Java. Spring Data JDBC bertujuan untuk menjadi lebih sederhana secara konseptual daripada JPA dengan tidak menerapkan pola populer seperti pemuatan malas, cache, konteks kotor, dan sesi. Ini juga memberikan dukungan yang sangat terbatas untuk pemetaan berbasiskan anotasi. Akhirnya, ia menyediakan implementasi repositori reaktif yang menggunakan R2DBC untuk mengakses database relasional. Meskipun modul itu masih dalam pengembangan (hanya versi SNAPSHOT tersedia), kami akan mencoba menggunakannya dalam aplikasi demo kami. Mari lanjutkan ke penerapan.

Including Dependencies

Kami menggunakan Kotlin untuk implementasi. Jadi pertama, kami menyertakan beberapa dependensi Kotlin yang diperlukan.
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
    <version>${kotlin.version}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-test-junit</artifactId>
    <version>${kotlin.version}</version>
    <scope>test</scope>
</dependency>

We should also add kotlin-maven-plugin with support for Spring.
<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>
    <version>${kotlin.version}</version>
    <executions>
        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <args>
            <arg>-Xjsr305=strict</arg>
        </args>
        <compilerPlugins>
            <plugin>spring</plugin>
        </compilerPlugins>
    </configuration>
</plugin>

Then, we may proceed to include frameworks required for the demo implementation. We need to include the special SNAPSHOT version of Spring Data JDBC dedicated for accessing the database using R2DBC. We also have to add R2DBC libraries and Spring WebFlux. As you may see below, only Spring WebFlux is available in a stable version (as a part of Spring Boot RELEASE).
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jdbc</artifactId>
    <version>1.0.0.r2dbc-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-spi</artifactId>
    <version>1.0.0.M5</version>
</dependency>
<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-postgresql</artifactId>
    <version>1.0.0.M5</version>
</dependency>

Kami juga harus menambahkan kotlin-maven-plugin dengan dukungan untuk Spring.
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Lovelace-RELEASE</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

Repositories

Kami menggunakan gaya Spring Data yang terkenal dari implementasi repositori CRUD. Dalam hal ini, kita perlu membuat antarmuka yang memperluas antarmuka ReactiveCrudRepository.
Berikut penerapan repositori untuk mengelola objek Karyawan.
interface EmployeeRepository : ReactiveCrudRepository<Employee, Int< {
    @Query("select id, name, salary, organization_id from employee e where e.organization_id = $1")
    fun findByOrganizationId(organizationId: Int) : Flux<Employee>
}

Berikut ini implementasi lain dari repositori - kali ini, kami menggunakannya untuk mengelola Organisasi objek.
interface OrganizationRepository : ReactiveCrudRepository<Organization, Int< {
}

Implementing Entities and DTOs

Kotlin menyediakan cara mudah untuk menciptakan kelas entitas dengan mendeklarasikannya sebagai kelas data. Ketika menggunakan Spring Data JDBC, kita harus menetapkan kunci utama untuk entitas dengan annotating field dengan @Id. Ini mengasumsikan kunci secara otomatis bertambah oleh database. Jika Anda tidak menggunakan kolom peningkatan otomatis, Anda harus menggunakan pendengar BeforeSaveEvent, yang menetapkan ID entitas. Namun, saya mencoba mengatur pendengar semacam itu untuk entitas saya, tetapi itu tidak bekerja dengan versi Spring Data JDBC yang reaktif.
Berikut ini penerapan kelas entitas Karyawan. Perlu disebutkan bahwa Spring Data JDBC akan secara otomatis memetakan organisasi bidang kelasId ke dalam kolom basis data organization_id.
data class Employee(val name: String, val salary: Int, val organizationId: Int) {
    @Id 
    var id: Int? = null
}

Berikut ini penerapan kelas entitas Organisasi.
data class Organization(var name: String) {
    @Id 
    var id: Int? = null
}

R2DBC tidak mendukung daftar atau kumpulan apa pun. Karena saya ingin kembali daftar dengan karyawan di dalam Organisasi objek di salah satu titik akhir API, saya telah membuat DTO yang berisi daftar seperti itu, seperti yang ditunjukkan di bawah ini.
data class OrganizationDTO(var id: Int?, var name: String) {
    var employees : MutableList = ArrayList()
    constructor(employees: MutableList) : this(null, "") {
        this.employees = employees
    }
}

Skrip SQL yang terkait dengan entitas yang dibuat terlihat di bawah ini. Seri tipe bidang akan secara otomatis membuat urutan dan melampirkannya ke ID bidang.
CREATE TABLE employee (
    name character varying NOT NULL,
    salary integer NOT NULL,
    id serial PRIMARY KEY,
    organization_id integer
);
CREATE TABLE organization (
    name character varying NOT NULL,
    id serial PRIMARY KEY
);

Building Sample Web Applications

Untuk tujuan demo, kami akan membangun dua aplikasi independen: layanan karyawan dan layanan organisasi. Aplikasi organisasi-layanan berkomunikasi dengan karyawan-layanan menggunakan WebFlux WebClient. Ia mendapat daftar karyawan yang ditugaskan ke organisasi dan termasuk mereka untuk merespon bersama dengan OrganisasiOryek. Contoh kode sumber aplikasi tersedia di GitHub di bawah repositori sample-spring-data-webflux.
Oke, mari kita mulai dari mendeklarasikan kelas utama Spring Boot. Kita perlu mengaktifkan repositori Spring Data JDBC dengan memberi annotating kelas utama dengan @EnableJdbcRepositories.
@SpringBootApplication
@EnableJdbcRepositories
class EmployeeApplication
fun main(args: Array<String>) {
    runApplication<EmployeeApplication>(*args)
}

Bekerja dengan R2DBC dan Postgres memerlukan beberapa konfigurasi. Karena tahap awal kemajuan dalam pengembangan Spring Data JDBC dan R2DBC, tidak ada konfigurasi otomatis Spring Boot untuk Postgres. Kita perlu mendeklarasikan pabrik koneksi, klien, dan repositori di dalam kacang @Configuration.
@Configuration
class EmployeeConfiguration {
    @Bean
    fun repository(factory: R2dbcRepositoryFactory): EmployeeRepository {
        return factory.getRepository(EmployeeRepository::class.java)
    }
    @Bean
    fun factory(client: DatabaseClient): R2dbcRepositoryFactory {
        val context = RelationalMappingContext()
        context.afterPropertiesSet()
        return R2dbcRepositoryFactory(client, context)
    }
    @Bean
    fun databaseClient(factory: ConnectionFactory): DatabaseClient {
        return DatabaseClient.builder().connectionFactory(factory).build()
    }
    @Bean
    fun connectionFactory(): PostgresqlConnectionFactory {
        val config = PostgresqlConnectionConfiguration.builder() //
                .host("192.168.99.100") //
                .port(5432) //
                .database("reactive") //
                .username("reactive") //
                .password("reactive123") //
                .build()
        return PostgresqlConnectionFactory(config)
    }
}

Akhirnya, kita dapat membuat pengendali REST yang berisi definisi metode API reaktif kami. Dengan Kotlin, tidak butuh banyak ruang. Definisi kontroler berikut berisi tiga metode GET yang memungkinkan kita untuk menemukan semua karyawan, semua karyawan yang ditugaskan ke organisasi tertentu, atau satu karyawan berdasarkan id.

@RestController
@RequestMapping("/employees")
class EmployeeController {
    @Autowired
    lateinit var repository : EmployeeRepository
    @GetMapping
    fun findAll() : Flux<Employee> = repository.findAll()
    @GetMapping("/{id}")
    fun findById(@PathVariable id : Int) : Mono<Employee> = repository.findById(id)
    @GetMapping("/organization/{organizationId}")
    fun findByorganizationId(@PathVariable organizationId : Int) : Flux<Employee> = repository.findByOrganizationId(organizationId)
    @PostMapping
    fun add(@RequestBody employee: Employee) : Mono<Employee> = repository.save(employee)
}

Inter-Service Communication

Untuk OrganizationController, penerapannya sedikit lebih rumit. Karena organisasi-layanan berkomunikasi dengan karyawan-layanan, pertama-tama kita perlu menyatakan WebFlibuilder WebFlux reaktif.
@Bean
fun clientBuilder() : WebClient.Builder {
    return WebClient.builder()
}

Kemudian, mirip dengan repository bean, pembangun sedang disuntikkan ke pengontrol. Ini digunakan di dalam metode the findByIdWithEmployees untuk memanggil metode GET /employees/organization/{organizationId} terpapar oleh employee-service. Seperti yang Anda lihat pada fragmen kode di bawah ini, ia menyediakan API reaktif dan mengembalikan objek Flux yang berisi daftar karyawan yang ditemukan. Daftar ini disuntikkan ke dalam OrganizationDTOobject menggunakan metode zipWith Reactor.
@RestController
@RequestMapping("/organizations")
class OrganizationController {
    @Autowired
    lateinit var repository : OrganizationRepository
    @Autowired
    lateinit var clientBuilder : WebClient.Builder
    @GetMapping
    fun findAll() : Flux<Organization> = repository.findAll()
    @GetMapping("/{id}")
    fun findById(@PathVariable id : Int) : Mono<Organization> = repository.findById(id)
    @GetMapping("/{id}/withEmployees")
    fun findByIdWithEmployees(@PathVariable id : Int) : Mono<OrganizationDTO> {
        val employees : Flux<Employee> = clientBuilder.build().get().uri("http://localhost:8090/employees/organization/$id")
                .retrieve().bodyToFlux(Employee::class.java)
        val org : Mono = repository.findById(id)
        return org.zipWith(employees.collectList())
                .map { tuple -> OrganizationDTO(tuple.t1.id as Int, tuple.t1.name, tuple.t2) }
    }
    @PostMapping
    fun add(@RequestBody employee: Organization) : Mono<Organization> = repository.save(employee)
}

How Does it Work?

Sebelum menjalankan tes, kita perlu memulai basis data Postgres. Berikut adalah perintah Docker yang digunakan untuk menjalankan kontainer Postgres. Ini membuat pengguna dengan kata sandi, dan mengatur database default.
$ docker run -d --name postgres -p 5432:5432 -e POSTGRES_USER=reactive -e POSTGRES_PASSWORD=reactive123 -e POSTGRES_DB=reactive postgres

Kemudian, kita perlu membuat beberapa tabel pengujian, jadi Anda harus menjalankan skrip SQL yang ditempatkan di bagian Entitas Implementasi dan DTO. Setelah itu, Anda dapat memulai aplikasi uji kami. Jika Anda tidak mengesampingkan pengaturan default yang disediakan di dalam file application.yml, layanan karyawan mendengarkan pada port 8090 dan layanan organisasi pada port 8095. Gambar berikut mengilustrasikan arsitektur sistem sampel kami.
spring-data-1
Sekarang, mari tambahkan beberapa data pengujian menggunakan API reaktif yang diekspos oleh aplikasi.
$ curl -d '{"name":"Test1"}' -H "Content-Type: application/json" -X POST http://localhost:8095/organizations
$ curl -d '{"name":"Name1", "balance":5000, "organizationId":1}' -H "Content-Type: application/json" -X POST http://localhost:8090/employees
$ curl -d '{"name":"Name2", "balance":10000, "organizationId":1}' -H "Content-Type: application/json" -X POST http://localhost:8090/employees

Terakhir, Anda dapat memanggil metode GET organizations / {id} / withEmployees, misalnya, menggunakan browser web Anda. Hasilnya harus serupa dengan hasil yang terlihat pada gambar berikut.
spring-data-2