Stop saying Java is dying, Java is still alive and kicking in every way.

0. After reading this article you will

  • Learn about the controversy that Java has faced as one of the hottest languages
  • Learn about the Java ecosystem and future

1 Introduction

原文标题:Why Java Is Perfectly Alive——A response to "Why Java Is Dying"

Original address: betterprogramming.pub/why-java-is…

Original author: Ivan Khodyrev

Note: All pictures in the text are from the original text

Translator's note: The programming language industry has always been very lively, with all kinds of contempt chains and wars of words emerging one after another. As one of the popular languages, Java cannot avoid a lot of controversy. Today, let's take a look at how this popular article with 1,800 likes made "innocent defense" for Java from the perspective of foreign authors.

2. Text

I wrote this long afterthought as a response to the article "Why Java is Dying". My comment below this post is already pinned to the top, and I thought I should write a full analysis post.

The best short answer to the original author's article is actually Coder:76's answer, which has hundreds of likes.

For some bloggers looking for attention, Java has been dying or dead for 15 years.

I totally agree with that.

2.1 What's wrong with the statement "Java is dying"?

That "Why Java is Dying" article received over 70 comments, mostly criticism, with dozens or hundreds of likes each. Why are so many people commenting so negatively? the reason is simple. This article is provocatively written and contains many controversial claims that are far from the reality for people using Java. Let's take a look at some of them.

"For example, Spring configures automatic injections (bean injections), which is understandable, but where does Lombok fit in the application environment and how is the messaging between the two coordinated?"

To someone using the above technique, this statement looks false. Lombok is a compile-time library and Spring is a runtime library. They work at different levels at different times in the application life cycle and do not interact directly. The correct answer to the author's question "Where is Lombok in the application environment?" is "no place".

"The point of Java still seems to be on stupid rules about what class names should be, what packages they should be in, and whether variables should be private or protected. Seriously, who cares?"

People working on large, long-term projects care. These rules are not stupid to them.

"By contrast, 'We are all adults' is simply Python's official response to the lack of access specifiers in the language."

There's nothing wrong with someone on the team assuming other people aren't adults - it's a plain idea. The problem is, large projects that last long and are created by large teams need rules; otherwise, they fail.

A big project is like a big city. It requires building foundations, planning, separation of concerns, private and public areas. If a skilled programmer divides language structures into public and private, they are likely to create "streets" that lead others in the right direction, save them time, and hide auxiliary infrastructure "underground", That way no one gets lost there.

There are many more controversial claims in the "Why Java is Dying" article, but my goal here is not a detailed analysis. What I want to do is use this opportunity to talk a little bit about the current state of Java.

For many years, Java was one of the programming languages ​​of choice, and it was also the target of critics. Not because it's bad, but because it's a compelling target, and if you want to get more attention yourself, you have to say something against it and hope someone notices. From this perspective, Java is a good target.

But what about now? Is Java still a sweet treat? Or is it "dying" as some say? Let's discuss the most important and controversial topics in order to get this clear.

2.2 Syntax

Often, Java's syntax is criticized the most: "not concise", "outdated", "too many templates", etc. For these "arguments", the only correct answer is to show the code. I won't discuss special syntax features here, there are plenty of detailed guides that cover all the nuances of Java syntax. Instead, I've chosen five code snippets just to give you an idea of ​​how Java works today for different practical tasks.

import static spark.Spark.*;
public class HelloWorld {
    public static void main(String[] args) {
        port(80);
        get("/hello", (request, response) -> "Hello World");
    }
}
复制代码

You may have heard of the "good" days before, when a simple Java web server required hundreds of lines of code and configuration to run? Forget them now.

This code uses Spark Java to start a simple web server on port 80 with HTTP GET method and /hello context path, returning a constant string when requested. Pretty straightforward and concise, isn't it?

...
OrderRepository orders;
QOrder qorder = QOrder.order;
DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public Iterable<Order> getShopOrdersByDate(ShopId id, ZonedDateTime date){
    return orders.findAll(
      qorder.shopId.eq(id).and(qorder.date.eq(yyyyMMdd.format(date)))
    );
}
...
复制代码

Some people say, "Java wasn't made for database manipulation". They must be joking.

This code uses a combination of Querydsl and Spring Data to fetch information from an SQL database. Everything seems simple: the getShopOrdersByDate method returns orders for a particular store on a particular date, with additional date formatting.

Interestingly, there is no SQL here, only Java constructs that are later translated into safe SQL in the library. This means that the query itself is type-safe and will be reliably checked at compile time rather than randomly at runtime. Plus, the IDE will help you do it automatically, just like any other Java code, making your job easier.

A large number of databases are available out of the box, such as PostgreSQL, MySQL, Oracle, and even MongoDB. Also, if you want to try them all, you don't have to change the query code.

import java.nio.file.Files;
import java.util.stream.Stream;
import static java.nio.file.Paths.get;
import static java.util.stream.Collectors.*;

public class Example {
     public static void main(String[] args) throws Exception {
        List<String> fileLines = Files.readAllLines(get("huge.txt"));
        String fileStats = fileLines.parallelStream()
                .flatMap(line -> Stream.of(line.split("\\s+")))
                .filter(word -> !"dumb".equalsIgnoreCase(word))
                .collect(groupingBy(word -> word.charAt(0), counting()))
                .entrySet().parallelStream()
                .map(letterStats -> letterStats.getKey() + ":" + letterStats.getValue())
                .collect(joining("\n"));
        System.out.println(fileStats);
    }
}
复制代码

Never thought of doing a simple data analysis in Java? I suggest you try it.

There are no extra libraries here, just pure Java.

Read all the lines from the large file, split them into separate words, filter out the dumb words to make sure the result is what you want, group the words by the first letter, count how many words there are in each group, and parse the result Grouping and counting create a string representation, and finally print the result.

This is a fairly readable and maintainable process. Of course everything is being done in parallel threads to achieve the proper speedup so that your 16-core machine is worth the cost.

On my 4-core laptop with Java 15, for a 1.2Gb text file filled with random words, the execution of this code takes an average of 6 seconds. That's not bad for such a large file and straight unoptimized code.

...
public MultiLayerNetwork createModel() {
    return new MultiLayerNetwork(new NeuralNetConfiguration.Builder()
            .regularization(true).l2(0.001)
            .learningRate(0.01)
            .weightInit(WeightInit.XAVIER)
            .activation(Activation.RELU)
            .optimizationAlgo(STOCHASTIC_GRADIENT_DESCENT)
            .updater(new Nesterovs(0.9))
            .list()
            .layer(convolution(5, 25).nIn(3).build())
            .layer(maxPooling(2).build())
            .layer(convolution(3, 50).build())
            .layer(maxPooling(2).build())
            .layer(convolution(3, 100).build())
            .layer(maxPooling(2).build())
            .layer(dense(200).dropOut(0.5).build())
            .layer(dense(200).dropOut(0.5).build())
            .layer(outputClassification(10))
            .setInputType(convolutionalFlat(28, 28, 3))
            .backprop(true).pretrain(false)
            .build());
}

ConvolutionLayer.Builder convolution(int filterSize, int filterCount) {
    return new ConvolutionLayer.Builder(filterSize, filterSize)
            .activation(IDENTITY).nOut(filterCount);
}

SubsamplingLayer.Builder maxPooling(int size) {
    return new SubsamplingLayer.Builder(PoolingType.MAX)
            .kernelSize(size, size).stride(size, size);
}

DenseLayer.Builder dense(int size) {
    return new DenseLayer.Builder().nOut(size);
}

OutputLayer outputClassification(int numOfClasses) {
    return new OutputLayer.Builder(LossFunction.MCXENT)
            .nOut(numOfClasses).activation(SOFTMAX).build();
}
...
复制代码

They say: "You can't do deep learning in Java". No, you can.

This simple example shows how to prepare the neural network structure stage before the learning stage, it uses Dl4j. Those in deep learning will recognize many familiar words.

Nothing fancy. Yes, you can also do deep learning and machine learning in Java.

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {
    String name;
    String surName;
    List<ContactInfo> contacts;
}
复制代码

Lombok is an island adjacent to Java. They are so close that you can even conflate them.

Do you hate templates? Then use Lombok. This code snippet shows a fully functional data class with all fields like getters, setters, equals, hashcode, toString, and finally AllArgsConstructor. Of course, you can override any of them if you want.

People from outside the Java ecosystem often think that "Lombok made Java stop being Java". I don't agree with this point of view. Lombok is Java. It is part of the modern Java ecosystem, uses legitimate Java mechanisms to augment its functionality, helps you work with Java code, has few drawbacks, and is used and loved by many Java developers. how many people? One of the most popular Java IDEs, the Lombok plugin has 11 million downloads.

It's a tool that makes Java better, so in a practical sense, it's Java for the millions of people who use it. Still, there are people in the Java community who are against Lombok and have every right to do so - if you don't like Lombok, no one is forcing you to do it.

Now imagine what these examples would look like in other languages. You may find that you can achieve the same goal with fewer characters. But will this code be as reliable, readable, maintainable and fast as the Java language? I do not think so.

Another important thing about syntax is IDE support. It's not an abstract theoretical question like how powerful a language construct is, or how much code a developer has to write to do what. IDEs add a pragmatic layer that translates all abstractions into the question of how much developer time a particular task will take.

Using a well-designed language combined with a modern IDE, developers can achieve their goals faster than using a more powerful or concise but IDE-unfriendly language. Due to its syntax, Java is one of the best languages ​​supported by IDEs. It's not too complicated, and it's not too free of choice, so the IDE can understand your current work environment and predict with great precision what you're going to do next.

Last but not least, Java's syntax allows for different styles of programming. Your code can be written in an object-oriented paradigm, where objects interact with each other; it can be written in a procedural paradigm, where global state is changed through a sequence of imperative program calls; or it can be written in a functional paradigm, Achieve your goals through the orchestration and application of functions. Sometimes people distinguish more paradigms - for example, Java is a good fit for aspect-oriented or actor-based paradigms. Java gives you a lot of flexibility in how you think about your tasks, so it's well-prepared for a paradigm shift in programming.

All in all, there is nothing wrong with Java's syntax. It's relatively simple, flexible, and expressive. Moreover, it allows the IDE to effectively assist developers in a variety of ways, greatly increasing their productivity. If you know Java well, write clean code, and use the right toolset for your task, your programs will be beautiful, maintainable, and concise. Don't let people fool you on this topic .

2.3 Reliability

Unlike many other technologies, Java as a language and a platform gives you reliability you can count on.

The Java language has the "Java Language Specification", which is the main basis for judging how the structure of Java code should work and how it should be used.

Why is it important? Because you can validate what you're doing and resolve issues or disputes in a rigorous, predictable way. With a language without a specification, you can't be completely sure what's going on. You may find bits of information in manuals, blogs, or tweets from language creators, but until a language is regulated, all of these pieces of information don't have a strong foundation to warrant anything.

Of course, the specs have different qualities or levels of detail, so something might be missed. However, a language with a specification gives you more confidence that your work is correct than a language without a specification. Java's specification is so deep and detailed that it leaves little to no ambiguity.

Java versions are strongly backwards compatible with things in the specification and the public Java API. This means that if you take code that uses version 1.3 of the public Java API written 20 years ago and run it on Java 15 today, it will work just fine.

At the same time, if you use private Java APIs, which include classes and methods/fields that should not be used directly by developers, you may be in trouble. I think it's a pretty fair deal: if you're using something that has a backwards compatibility guarantee, you can rely on it, but if you're using something you're not going to use, don't expect them to work forever.

Java is safe, not absolute, but realistic. Java code is safe because developers are less likely to make mistakes with it than with many other languages. It is safe because Java code cannot access the operating system or hardware directly, so the Java runtime can restrict what a Java program can and cannot do.

Java code is portable. This means that you can compile Java code on one platform and run it on any platform that implements the Java Virtual Machine without recompiling. "Write once, run anywhere" - this old Java slogan still holds true 25 years later.

Broad portability along with backward compatibility is a very powerful combination of guarantees that give developers confidence that their efforts and knowledge will not quickly become obsolete. Of course, there are some exceptions, some virtual machines are only allowed to use a subset of the Java language specification due to different reasons such as hardware limitations. For example, you can run Java code on a microcontroller with 8kB RAM, but there are some limitations you have to consider.

Java code is maintainable. Compared to languages ​​like C++, Java's syntax is a great simplification; it lacks many of the features, customizations, and powerful constructs that C++ has. At the same time, compared to scripting languages, Java has many "ceremonies" that are redundant at first glance. In this sense, Java attempts to maintain a balance between complexity, power, and readability to maximize the long-term maintainability of the code.

What is maintainability? I describe it as the time it takes for an average skilled developer to apply a change in an existing codebase (probably an old one) that leads to the developer's goals and doesn't break other things . The less time required, the better the maintainability.

In this sense, Java is good. On the one hand, it is powerful enough to express many things that developers need, but at the same time it is not as complex as some languages, and one can use extremely powerful language constructs to create beautiful, unsolvable mazes that are only created by their only to understand. Java, on the other hand, forces developers to write more verbose code with more explicit things than developers usually do in scripting languages ​​to increase readability and understandability.

Java is fast. If you try to research this topic, you'll probably find dozens of articles like "Java is faster than X" and "X is faster than Java" with conflicting statements and conclusions. If you try to experiment yourself, you can easily build examples of how slow Java is and how fast Java is surprisingly fast - you can do the same with other languages, by the way.

There is a good comment on why Java was considered slow in the past. It's a bit outdated now. For example, the latest Java runtime handles strings much better than seven years ago, and I disagree with some other claims. But the general conclusion is that with each release, Java is optimized to improve its performance, which is true. Remember the third example in the grammar section of this article?

On my laptop, with Java 8, it takes an average of 10 seconds, and with Java 15, it only takes 6 seconds with the same configuration. This is one of the important guarantees given to us by the developers of the language. Java is fast enough for many tasks today and will be faster in the future.

The last important thing about reliability is this. They have been performing for over 25 years and there is no reason not to perform in the next few years.

2.4 Java is slow to introduce modern language features

yes. Is slow speed a bad thing in general? no. Ask yourself, here is a question. If you were riding a bike and occasionally saw a wall in front of you, what would you choose: speed up or slow down? I bet your choice is the same as mine.

So why is Java slower to adopt features than some other languages? Because of reliability, which we discussed in the previous section. These reliability are the walls that force features to be carefully discussed, filtered, or translated in some way, where slow is a better friend than haste.

There is a formal process for how changes to the Java language are applied, called the Java Community Process. The main purpose of this process is to verify that the proposed feature does not break Java reliability, which is obviously not a quick task at times.

The developers of the Java language are trying to balance innovation and reliability, which is much harder than the "let's add this cool feature to our language now" strategy. But in the long run, it can bring more benefits, because reliability means trust, which is more valuable for the future than cool features. Brian Goetz has a great talk on this strategy and overall Java philosophy, check it out.

Also, worth mentioning is the current Java release schedule. Every six months, in September and March, a new Java version is released that is fully operational, with incremental updates over the next six months. Every three years, one such release becomes a Long Term Support (LTS) release, with incremental updates over the next three years.

Now, Java 15 is the latest version and Java 11 is the current LTS . The next LTS release will be Java 17, scheduled for release in September 2021. Each release may include some "preview features". These features do not guarantee compatibility in future releases. Their goal is to let developers try out controversial innovations and leave feedback about them. Such as

If a feature is not marked as preview, it means it will be fully included in the platform and will have the reliability of Java.

2.5 Ecosystem

Some people understand language ecosystems narrowly, limiting their concepts to just the set of libraries available to programmers. I prefer to think of the ecosystem in a broader perspective, as a tool for dealing with problems. The more problems a developer can solve with a language, the wider its ecosystem will be. It doesn't matter which meaning you like. Java has a huge ecosystem.

Some of the issues listed below are personal ones I've had in the past:

  • Can I write a web app in pure Java without knowing nothing about HTML, JS and CSS? Can.
  • Can I stop the world with a millisecond-scaled terabyte heap? Yes, it's easy.
  • Can I process images and videos in pure Java for portability? Can.
  • Can I do deep learning in Java? yes.
  • Can I program that robot I bought on Black Friday in Java? Can.
  • Can I find an answer to my personal stupid question about Java? yes.

This list is definitely personal, but I'm pretty sure that in most cases when the question involves Java in a programming context, instances of "yes" will trump instances of "no".

With the help of the Java ecosystem, you can solve many problems in many areas, and, often, you also have multiple options to choose how to do it. If you want to understand how huge the Java ecosystem is, take a look at this resource.

2.6 Startup time and memory usage

Java code is compiled into an intermediate form called Java Byte Code and then executed on a runtime platform called the JVM. In addition to complaining about Java's syntax, critics often complain about the JVM's memory footprint and startup time. Let's discuss it in more detail.

JVM is short for Java Virtual Machine, which means that your application runs in a sandbox of a virtual computer. There are many benefits to this approach. Developers don't need to think about the nuances of the operating system and hardware where the application runs. A virtual sandbox provides greater security capabilities because it doesn't allow applications to interact directly with low-level stuff. The virtual environment stands outside your application and can dynamically optimize it to improve performance in different situations, etc.

The downside is that the JVM requires additional resources, including memory and processor time, to function, and it also has a startup and warm-up time.

In typical use cases, the standard Oracle HotSpot JVM introduces tens or hundreds of megabytes of additional footprint and takes on average a few seconds to start, depending on the application. (The JVM itself usually starts within a second, but some other libraries increase this time due to their internal routines). Also, in the first few seconds after startup, the JVM may consume more CPU than average as it identifies and compiles "hot" parts of the bytecode to optimize its future use.

In most cases, these disadvantages are justified for many types of applications. However, there are cases where they are not and you want to trade the benefits and drawbacks in some way. So, what should you do? Should you ditch Java for something else? Usually not needed -- just use another runtime environment that suits your particular task.

For example, consider the world of microservices. Modern microservice applications often require minimal memory footprint and startup time in order to efficiently populate container orchestrators such as Kubernetes. To meet this need, the developers of Java created GraalVM. It allows developers to create native images from Java code that will run in tens of milliseconds of startup time and with only a few megabytes of additional memory footprint. Many Java networking frameworks use GraalVM for the microservices world. Quarkus, Micronaut, Spring, Helidon.

Disadvantages of trading? You lose portability, and the built image will only run on the platform that GraalVM was compiled for. But for microservices, it doesn't really matter because your application will most likely be running in a container with a predefined environment. You may also face some other limitations. In conclusion, when you hear that Java is not suitable for modern microservice needs, keep it in mind. This statement is false.

Java doesn't mean excessive memory usage and slow startup times as many critics claim. Memory usage and startup time are mainly determined by the runtime used to eventually run an application and the additional libraries it uses. In this sense, the choices that the Java ecosystem gives you depend on your needs.

2.7 What exactly does Java do?

Java can be used for everything you can imagine: APIs and web servers, games and multimedia software, UI and web applications, IoT and robotics, AR and VR, machine learning and data streaming, databases and cloud-native microservices, huge enterprise Systems and small software projects.

Are there any exceptions? Not technically, but practically. Java is not intended to be a low-level systems language, so it is not a good idea to create the core or hardware drivers of an operating system in Java. Technically yes, but for these cases there are better tools than Java.

2.8 But we have to pay for Java, right?

No, you don't need to pay for Java if you use a free Java distribution.

Java is open source, so anyone can build ready-to-use Java distributions, there are many free pre-built distributions such as OpenJDK, AdoptOpenJDK, AWS Coretto, Azul Zulu, and others. The use of these distributions is completely free, and there is a good chance that any of them will meet your requirements. If you want to learn more about this, please refer to this article.

2.9 The future of Java

To sum it up, Java is still a behemoth.

Java's role is to be a core technology in many areas, balancing innovation, capability, and maintainability to sustainably support the projects in which it is applied. If you like trying cool new language ideas, choose another technology.

However, if you see a particular feature end up in the Java specification, you can be sure that it was added not by chance or to catch up, but the result of intensive research and significant design effort to achieve what other Java features have the same level of reliability. In this sense, you can trust Java unlike many other technologies on the market.

If you're wondering which computer language you should learn as your first or next language, give Java a try. I believe that Java will be with us for a long time.

I bet there are plenty of good arguments for why Java has longevity that I missed in this article, so feel free to share them in the comments.

Featured in the past

  1. Java 8 Stream from entry to advanced - play with collections like SQL
  2. How many new features of Java8-15 do you know?
  3. From the star of open source startups to building bombs, and finally deleting the library and running away, what has he experienced?
  4. 11 Java Code Performance Optimization Tips Worth Mastering
  5. Alibaba's Java Development Manual (Huangshan Edition) is here

Guess you like

Origin blog.csdn.net/wdjnb/article/details/124404880