Programmers most likely to commit a mistake, you in a few?

Java language is the beginning for interactive television developed, over time, he has been widely used in various software development. Based on object-oriented design, shielding some complexity, such as C, C ++ and other languages, providing garbage collection mechanism, platform-independent virtual machine technology, Java developers to create an unprecedented way. On the other hand, due to "encode once, run anywhere" put forward the slogan of Java, so Java is more famous. But Java is everywhere in the abnormal occurrence, here I will list the five mistakes I think Java development most likely to occur.

1, the wheel made repeated

An obvious error is to ignore a lot of library Java programmers habitual already exists. In between you decide to build a wheel, I suggest you try to search to see if there already exists library. E.g. log regard, the logback, new log4j, networks, or there Netty Akka. There are libraries, it has gradually become a standard, such as Java8 added in Joda-Time. The following is about my last project personal experience. Part of the code for HTML escaping is a developer of yourself. This code works for years, but once again encountered a user input code into an infinite loop. The users find the application does not respond, then re-enter it again, this cycle of death because the server hung up. If this has been developed using the HTML escape tools, such as Google Guava provided by the project HtmlEscaper, this serious problem may not occur. And now the market's most popular open source database, are behind the team and community support, an error like this, can be repaired in time.

2, the error of Switch-Case use break

This is a very embarrassing problem, but still often appear in the actual development. Falls characteristics may be useful in a switch statement, but lack the necessary break keyword, sometimes disastrous consequences. For example, in the following code, in case 0 if you forget to put in a break key, code continues down, then it will output a One after Zero: public static void switchCasePrimer () {int caseIndex = 0; switch ( caseIndex) {case 0: System.out.println ( "Zero"); case 1: System.out.println ( "One"); break; case 2: System.out.println ( "Two"); break; default : System.out.println ( "Default");}}

The best solution is to use multi-state, and the different processing code into subclasses. Of course, like this error may be checked out by tools like FindBugs or PMD.

3, forget the release of resources

Once you open a file, or to establish a network connection, a very important habit is to remember to turn off resources. And must remember, if there is an error in the use of resources like this process, exception handling, but also need to do a corresponding shutdown. Some may say, FileInputStream objects in the GC time, Java terminator (finalizer) will automatically call its close () method, but we know that we can not predict GC start at what time, so we can not predict before performing the GC, will how many resources can not be closed in a timely manner. To avoid this, Java7 launch of the try-with-resources syntax is worth every developer use. private static void printFileJava7 () throws IOException {try (FileInputStream input = new FileInputStream ( "file.txt")) {int data = input.read (); while (data = -1!) {System.out.print (( char) data); data = input.read ();}}}

try-with-resources syntax applies to all classes that implement the interface AutoClosable. It can ensure the timely closure of each resource.

4, memory leaks

Java uses automatic memory management, so most of the time, we are not going to care allocate and free memory, but that does not mean Java developers need to ignore memory. In Java applications, memory problems often arise. We know that if the object is not referenced, the object will be released, but it does not mean that the problem of memory leaks will not appear. In Java, there are many causes of memory leaks, but the situation is the most prone to object references can not be released because the GC heap memory when the recovery, if an object is still referenced by other objects, the object space will not be recovered of, for example, if the class has a static field reference to a collection, if we do not have to manually after use to complete this collection, he set to null, then this collection and this collection of objects, is forever It will not be recovered because the class static fields will not be the GC. For example, there Reasons that cause memory leaks, is a set of object reference each other, that is, we often say that a circular reference, because the circular reference, so the GC can not determine whether these objects reference each other as well as the need to survive. In another case, that is, non-heap memory leak when using JNI. A typical example of a memory leak: final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool (1); final Deque numbers = new LinkedBlockingDeque <> (); final BigDecimal divisor = new BigDecimal (51);

scheduledExecutorService.scheduleAtFixedRate(() -> { BigDecimal number = numbers.peekLast(); if (number != null && number.remainder(divisor).byteValue() == 0) { System.out.println("Number: " + number); System.out.println("Deque size: " + numbers.size()); } }, 10, 10, TimeUnit.MILLISECONDS);

scheduledExecutorService.scheduleAtFixedRate(() -> {
    numbers.add(new BigDecimal(System.currentTimeMillis()));
}, 10, 10, TimeUnit.MILLISECONDS);
复制代码

try { scheduledExecutorService.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); }

In the example above, we create two scheduled tasks. The first task timing acquired from the deque the final digit "numbers" and determines if this number could be divisible by 51, the number and the print size of the deque. The second regular tasks, continued to add data to the deque. 10ms interval to perform both tasks. If this code is executed, you will find that the size of the deque will continue to increase until the data in the deque fill the entire heap space. To prevent this from happening, we can use pollLast method instead peekLast method, because the method would pollLast, to remove this element from the deque to get in after the last element.

5, excessive waste generation data

Excessive waste generation data mean, it is the object of the program is running in a short statement to generate a large number of cycles. This time results in frequent execution of GC, reclaim space from memory, perform the GC heap is required to complete the scan, the impact on system performance is very large. The following is a small example: String oneMillionHello = ""; for (int i = 0; i <1000000; i ++) {oneMillionHello = oneMillionHello + "Hello";!} System.out.println (oneMillionHello.substring (0, 6) );

In Java, strings are immutable, so each cycle will create a new string object. In order to improve such code, we can use instead of StringBuilder: StringBuilder oneMillionHelloSB = new StringBuilder (); for (int i = 0; i <1000000; i ++) {oneMillionHelloSB.append ( "Hello!");} System.out. println (oneMillionHelloSB.toString () substring (0, 6).);

The second version of the code, in the course of implementation will raise a lot of performance.

Above summarizes the error five most commonly committed Java developer, I based a lot of open source projects on github, problems Stack overflow, there are some popular google search analysis, want to share to give you help.

Guess you like

Origin www.cnblogs.com/waiwei/p/12035527.html