As a Java programmer, why am I not turning to go in a production project?

Source: Internet
Author: User
Tags coding standards
This is a creation in Article, where the information may have evolved or changed.

Since Google released the first official version of the Go language in 2009, the language has been popular with excellent language features, especially in situations where high concurrency is required, and everyone will think about whether to use go. Then, in the domestic emergence of a group of seven cattle as a representative of the use of go as the main language of the team, and Xu Great God himself in various occasions to push the go in the domestic development, so in this environment, China's go developer community gradually surpassed the other regions.

Then the problem comes, spare time to learn is one thing, really want to use a new things in production is another matter. JavaScript developers can choose node. js as a no-no-no-no, but for Java developers, is it the choice of Go or Java for the next big project?

Language itself

First of all, it needs to be explained that as a technical decision-maker, it is not possible to make a direct conclusion according to the characteristics of the language in the technology selection. In fact, most people will use a series of frameworks, libraries and tools, in short, will consider a lot of surrounding ecological environment factors, but also combined with the company's characteristics, a variety of historical issues and actual objective factors, such as a series of considerations to complete the decision-making. So, let's start with the language and step-by-step analysis of whether it's appropriate to choose Go in your project.

Go is undoubtedly superior in high-concurrency programming, supported by Goroutine from the language level, which is unmatched by languages such as Java, which is one of the most important reasons why most people choose go for high concurrency scenarios. Although Java has a framework such as Kilim, there is no language layer support that is always lesser.

In addition, the other syntax of Go is also very interesting, such as multiple return value, to some extent for developers to bring some convenience. Imagine, in order to return two to three values, have to encapsulate an object, or erase the business name use Map , List such as collection class, advanced point with Apache Pair and Triple , although feasible, but always not as good as the implementation of go elegant. On top of that, go also unifies the unusual return way, does not have to go to tangle is by throws the exception or the error code to judge whether succeeds, the multiple return value the last one is Error on the line.

Go in the native type of language support a number of commonly used structures, such as map and slice , and other languages they are more in the library, which also reflects the language is from a practical point of view, since everyone needs, why not support it at the language level. function as a class citizen appears in the go language, but Java in the recent Java 8 also has a lambda expression, is also a progress.

Other features that are icing on the cake, such as indefinite parameters, have been supported by VarArgs in Java 1.5 in 2004; Multiple assignments are also present in Ruby, but in addition to assigning multiple return values, and letting you write less than one intermediate variable when exchanging values, make the code more aesthetically pleasing , the other effect is really not how obvious.

Said so many advantages of go, of course, it also has some problems, such as GC, speaking of it, Java has to reveal the white teeth, although in the large heap of GC G1 still somewhat unsatisfactory, but Java GC has been developed for many years, various strategies are more mature, CMS or G1 enough to cope with most scenes, There is a real need to use the Azul Zing JVM. However, from the latest Go 1.5 news, GO's GC implementation has greatly improved, by the way, GOMAXPROCS by default also from 1 to the CPU core, it seems that the official go on the use of multi-core more confidence.

Xu Shiwei in the preface to "Go Language programming" predicted the next 10 years, go will replace Java, ranked in the top of the programming list, was 2012, in order to see the 2009 year Tiobe year of programming language today's rankings, the author in writing this article deliberately to Tiobe to see the next, the most recent August 2015 ranking , Java ranked first in 19.274%, and go has fallen out of the top 50, which makes some surprises.

But overall, I think go in the language level of performance is quite good , to solve some of the pain points in programming, learning curve can be accepted, especially for those who have a/C + + background, will feel very cordial.

Engineering issues

A person to write code can be very casual, how to write on how to write, but when a person into a team, this random or casually will bring a lot of problems, so the birth of coding norms this thing, the big companies have their own coding standards, such as Google has no more than 10 programming language specifications. A set of coding specifications within a team can largely ensure the style of the code and reduce the cost of reading communication. Go built-in a set of coding specifications, violate the code will not compile through, you can say as long as you are writing go, then your code will not be too ugly, of course, go does not put everything on the force of death, and some of the recommended specifications can be gofmt formatted, but this step is not necessary.

Although go itself solves this problem, but can not say that Java is blank in this area, Java development So far around the tools, there is no shortage of mature code static analysis tools, such as Checkstyle, PMD and findbugs, they can not only scan the coding specifications of the problem, It is even possible to scan the code for potential problems and to give solutions, and to be easy to use, and to have a high degree of acceptance in the Java developer community, it should be said that most of the developers will use these tools. In addition, some manufacturers also have their own coercive means, such as Baidu Internal also has a lot of language coding norms, and in most cases, if not through the coding standard Scan, you are unable to submit code, and some companies in the continuous integration process to add code scanning, A problem with findbugs high priority must be repaired before it can enter the next phase. So the advantage of go on this issue is not obvious, or in a mature environment, this is only qualified .

Here we need to emphasize one of the views of the author:

Go incorporates a number of best practices in the language itself and in the release package, and it is the experience of these predecessors that makes it look so good. Take such a sea, land and air mixed special forces to the Java, C, Ruby, the language itself to do contrast, it seems unfair, so this article in the consideration of the problem will be combined with the language and its ecosystem members, after all, this is closer to the real situation.

The go itself has a set of conventions on the structure of the project, where the code is put, how the test file is named, what directory the results of compiling the packaged output to, and even the go cover command line of the statistical test coverage, the developer does not have to be too tangled in these issues, once again embodies the go focus on engineering practice characteristics. Back to the Java side, Maven Gradle It is a tool that focuses on engineering lifecycle management, and has a Maven long history and is widely used in various projects. As an Maven example, not only to achieve all of the above features, there is a strong plug-in extension capabilities, here is just one-time maintenance of the good pom.xml files on the line, because Maven of the large number of users online, there are a lot of examples, and even many of the tools and templates for generating projects, so the cost of use is not high.

Here also to derive a topic, is to rely on management, in the development of code, it is bound to rely on a lot of external things, go can directly import remote content, this feature is very creative, but does not solve the problem of the version, in Maven or Gradle , We can directly specify the individual dependencies or even the plug-in version, and the tool will automatically download them from the repository. If it is necessary to rely on different versions of the same library in different modules of the same system at the same time, we can also be implemented through the slightly complex means of OSGi, which, in terms of modularity, Jagsaw is expected to be included in Java 9, but it will also solve many problems. And according to the Golang practice group in the discussion, it seems that godep, GB and GVT are not satisfactory, in this regard go still have a way to go.

To sum up, go in the engineering has a lot of bright spots, absorbing a lot of best practices, and even can say with go after more easy to write code, there is a good project structure, but with the complete ecosystem of Java, go does not occupy an advantage , because the quality of the final code is decided by people, Both sides are not short of good tools, so the characteristics of this aspect can not affect the decision-making of technology selection.

Development practices

Talk is cheap. Show me the code.

Enter the coding link below, first from the go proud of the concurrency began, "Go language Programming" in the preface has such a code:

func Run (Arg string) {    //  ... }func Main () {    go run ("test")    ...}

The Java code in the book is 12 lines, and the thread, not the association, is obvious, but it was in 2012, and today, Java has grown to Java 8, 3 years, to see what the Java code looks like today:

 public  class   Threaddemo { static  void   main (string[] args) {String str  = "Test"; //  new  Thread ((), {/*   do sth. with str 
    */ }). Start (); }}

Not a co-process is still a mishap, but with a lambda expression, the code is a lot shorter. But then again, this comparison does not have much meaning, so you do not have to stand out go to say go also support closures, go version can also be streamlined. We do not write short, in Java practice, most of the time we will choose the thread pool, rather than new one of their own Thread object, Doug Lea great God's Java and the contract is very useful, and very reliable. In addition, the content processed in the concurrency is the key, city a thread or the process is the first step of the Great Wall, if there are 10 branches of business logic, but also multiple access to the database and call remote services, that no matter what language is useless. So in the case of complex business logic, the difference in language is not too obvious , at least in the Java and go contrast is not obvious, as for other higher-level, more expressive language (such as common Lisp), we will have to spell IQ.

In some cases, due to objective factors constraints, completely can not use go, such as now in full swing in the Internet financial system, and the bank docking system almost no choice, are Java implementation, because some banks will only give jar package ah ... To the jar bag ah ... Jar Bag Ah ... If it is a so file, perhaps can also use CGO to cope with, face a jar you let go what to do?

Put aside these annoying questions, let's take a look at the more common ways to implement rest services now. When it comes to this, we must sacrifice the Beego framework of the people who go abroad. One of the simplest rest services can be this:

 Package Main Import (    "Github.com/astaxie/beego") type Maincontroller struct {    beego. Controller}func ( this *Maincontroller) Get () {    this. Ctx.writestring ("Hello world!" )}func Main () {    beego. Router ("/", &maincontroller{})    Beego. Run ()}

Since the go aspect, we use a set of framework, then Java aspect, we also choose a mature framework, spring in Java EE Basic can be regarded as the fact standard, and spring boot is greatly improved the development efficiency of spring project, See how the same rest service is implemented in Springboot.

First of all, to start.spring.io build the skeleton of the project as needed (in fact it can be easily manually configured by MAVEN or created with CLI tools), for subsequent demonstrations, here I will choose "Web", "Actuator" and "Remote Shell, in fact, is more than two Maven dependency, the following operations Section will mention, and then casually find a handy IDE to open the project, type the following code on the line (import, package and class definition of the basic is the IDE generated).

 Packagedemo;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController, @SpringBootApplication @restcontroller Public classdemoapplication {@RequestMapping ("/")     PublicString SayHello () {return"Hello world!"; }     Public Static voidMain (string[] args) {Springapplication.run (demoapplication.class, args); }}

Running this code will automatically start the built-in tomcat container and access the http://localhost:8080/to see the output. Because it is spring, there is no pressure to mix with other framework facilities, and there is not much to learn.

There is no significant difference between the two in implementing rest services, and with the business logic mentioned above, there is no qualitative difference between two languages as long as the right tools are used.

The ORM in Beego supports MySQL, PostgreSQL, and Sqlite3, while ORM tools such as Hibernate and MyBatis in Java can almost take the most common relational databases and are quite mature, The community is equipped with a variety of auto-generating tools to simplify use, and the industry also has a recognized standard like JPA. Throughout the Go ORM tool, we are still in the discussion, which is to use it? To NoSQL, both sides have a large number of drivers to use, such as MongoDB and Redis have a detailed list of drivers, MongoDB is not officially driven, but there is community maintenance of MgO, is a tie bar. A little bit larger, like Hadoop, Spark, and storm scenarios, it seems that Java has a higher rate of out-of-the-way, or it is solved directly by means of streaming, and this is no longer unfolding.

While there are so many questions, go is a good choice if you really encounter large traffic, high concurrency scenarios, and need to develop the infrastructure from scratch to deal with these issues. For example, a cloud service provider such as seven cattle, or BFE (Baidu Front End, claiming to be probably the world's largest go language cluster, left its figure in the Velocity conference in 2015--figures 1 and 2).

Operation and Maintenance

Write the code is just a small step long march, there are a lot of things waiting for you to solve, such as how to write the code compiled, packaged, released on-line. Compile and pack without saying, the command-line tool of Go go build can directly make your code together with all its dependencies into an executable file. As for deployment, everyone praised that go deployment is not dependent (in addition to the GLIBC version of the requirements, regardless of the need for CGO), directly to the executable file there to throw it, very convenient. Go has built-in powerful HTTP support that does not require additional Web servers to support you for good performance.

Then look at Java, according to common sense, generally use Maven or Gradle to deal with the compilation, packaging, or even publish, still as an Maven example, mvn package can be done to compile and package. You can choose a jar package, which can be a war package if a Web project is deployed to a container, or it can be packaged together into a compressed package (zip, tar, and so on), which is not a complex step.

The next deployment, we have something to say, "Write Once, Run Anywhere" This was a Java propaganda, but it is this sentence has been criticized, in fact, if the code does not use platform-specific content (such as to avoid binding on WebLogic), The internal classes that do not use a particular version of the JDK (for example com.sun , things in this way are not recommended), Java code can be compiled and run anywhere, in fact, most of the time, we are doing this, Look at the vast majority of Java libraries are released from the jar to the Maven repository, and no one lets you directly pull the source code to compile. In a different environment, you just need to deploy the corresponding JDK (usually put in the installed template, or directly with the installation package to deploy it), as to what the operating system is not really important.

Continuation of the rest service example above, Java Web Projects are generally deployed in containers, such as Tomcat or jetty, of course, also useful for commercial containers (many banks are used WebLogic), so we all think that the deployment of Java programs need to first have a container, This is actually a few years ago, and then blew up a wave of embedded containers, Tomcat and jetty can be embedded in your program, no longer have to worry about having a container. Spring Boot simply makes this a little easier, and mvn package after that, a word will take care of the startup of the built-in Tomcat, the various deployments, and then everything becomes the following (assuming that the last generated jar package is named Demo.jar):

Java-jar Demo.jar

In spring Boot 1.3, you can also adjust the configuration of Maven plugin so that the jar can be executed directly (don't underestimate the change, it can greatly improve the operational dimension):

./demo.jar

So Java program difficult to deploy is also history, now Java program deployment is already a different condition. The compilation, packaging, and deployment of the two can be completely tied. I think some aspects of Java is better, such as Java basically do not have to worry about cross-compilation problem; Go library in the release of the recommended direct release of the source code rather than the binary package, encountered in the celestial network can not access the situation, compile something to bring a ladder ... As for the conjunction with Nginx and so on, it is very convenient for everyone, will not repeat it.

The completion of the deployment, the next log and monitoring, are very common problems, the log has a corresponding library, and monitoring are dependent on professional monitoring platform, their own information output is good, please allow me to show the spring boot Remoteshell terminal monitoring, In addition to the regular HTTP output JSON information (with the health check, meter data, Dump, request tracking and a series of rest output), but also brought a similar top tall on the device, ssh -p 2000 user@localhost after the execution dashboard can see this real-time update of the interface.

Summarize

So much to summarize the full text of the view-although go in the language is very good, but also into a lot of best practices, but combined with many considerations, in many cases it will not be more valuable than Java, and may not necessarily be able to do better than Java, so as a Java programmer, I will not turn to go in my own production project.

In addition, in addition to the issues discussed in this article, there are more realistic issues, such as team transition costs and recruitment costs, do not underestimate the recruitment, for managers, recruitment is also an important part of the work, imagine, is to recruit an experienced go programmer easy, Or is it easy to recruit an experienced Java programmer, and even if you can recruit a full-time employee of Go, can you recruit a go outsourcing, especially if the team is in need of fresh blood, the result is obvious.

But all this does not prevent everyone to learn go, the beginning of this article has expressed this point of view, spare time to learn go and in the production project without go is not conflict, go still have a lot of learning and learn from the place, and who is not sure which day you will really meet the right to use the Go project.

Finally, special thanks to Xie Mengjun and Li Daobing in the writing process and the author's various thinking collision and communication.

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.