[Java] - Exception & Loging

December 16, 2017 |

Before Java SE 7 or 8, we don't have any way manage a resource object (BufferReader, FileReader,... ). We must manage them by manually. Sometime, we forget close a resource and make memory leak, low performance. In Java SE 7, 8, 9, we have a way manage them by automatically.

Overview
Within JVM has two types: Check and Uncheck.
- Check exception at compile time.
- Unchecked exception at runtime.
 Error exception cannot catch like: OutOfMemoryError,...


Statement:
    try {
                //body
            } catch (Exception ex) {
                // exception code
            } finally {
                // final code
      }



Handle UncatchException

======
private void start() {
        Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
            System.out.println("Woa! there was an exception thrown somewhere! " + t.getName() + ": " + e);
        });
        final Random random = new Random();
        for (int j = 0; j < 10; j++) {
            int divisor = random.nextInt(4);
            System.out.println("200 / " + divisor + " Is " + (200 / divisor));
        }
    }
======
    private void startForCurrentThread() {
        Thread.currentThread().setUncaughtExceptionHandler((Thread t, Throwable e) -> {
            System.out.println("In this thread " + t.getName() + " an exception was thrown " + e);
        });
        Thread someThread = new Thread(() -> {
            System.out.println(200 / 0);
        });
        someThread.setName("Some Unlucky Thread");
        someThread.start();
        System.out.println("In the main thread " + (200 / 0));
    }

I. try-with-resource statement
 try-with-resource statement

try (Resource resource 1;
      Resource resourcce 2) {
}

In Java SE 6 with Resource Management.
        // Java SE 6 or later
        BufferedReader bufferReader1 = null;
        try {
            bufferReader1 = new BufferedReader(new FileReader("Test.txt"));
            System.out.println(bufferReader1.readLine());
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            try {
                bufferReader1.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


 In Java SE 7 or later with Resource Management.
         // Java SE 7 & 8
        try (BufferedReader bufferReader2 = new BufferedReader(new FileReader("Test.txt"))) {
            System.out.println(bufferReader2.readLine());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


II. Create a new Resource
 When you create a resource class that use to try-with-resource, those class must be implement close method  from java.lang.AutoCloseable .

Example:
ReadFile.java
package javaone.core.learning;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile implements AutoCloseable {
    private BufferedReader buff;
    private FileReader fileReader;

    public void printContentOfFile(String path) {
        try {
            fileReader = new FileReader(path);
            buff = new BufferedReader(fileReader);
            String line = buff.readLine();
            System.out.println(line);
            while (line != null) {
                System.out.println(line);
                line = buff.readLine(); 
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** {@inheritDoc} */
    @Override
    public void close() throws Exception {
        buff.close();
        System.out.println("Close Read File");
    }
}

MainTest.java
public static void main(String[] args) {
         // test new Resource
        System.out.println("test new Resource");
        try (ReadFile readFile = new ReadFile();) {
            readFile.printContentOfFile("Test.txt");
        } catch (Exception e) {
            System.out.println();
        }
    }

Result:
test new Resource
Try With Resource line 1
Try With Resource line 1
Try With Resource line 2
Try With Resource line 3
Try With Resource line 4
Try With Resource line 5
Close Read File 


When the point jump out try-with-resource statement, the resource auto close ReadFile resource. We don't need to manually close resource.
Read more…

[Tips] - How to use jconsole tool.

December 03, 2017 |

jconsole help you monitor and manage Java applications.

Step 1: Type following the command line with administator.
jconsole

Step 2:  At New Connection -> choose Local Process or Remote Process

Overview Tab


Memory Tab
Thread Tab

Read more…

[English] - How use to V or V-ing

December 03, 2017 |
I. Gerund ( V-ing)

1. The subject of the sentence.
Example:
- Walking must carefully.

2. Complement of the verb
Example:

3. is Complement
Example:

4. after preposition.
 Example:

5. after some special verbs:
- admit (/əd'mit/ thừa nhận),
- avoid( /ə'vɔid/ tránh),
- delay ( /di'lei/),
- enjoy,
- excuse( /iks'kju:z/),
- consider ( /kən'sidə/),
- deny,
- finish,
- imagine,
- forgive,
- keep,
- mind,
- miss,
- postpone,
- practise,
- resist,
- risk,
- propose,
- resent,
- try,
(sau các động từ phía trên thì động từ sau nó phải Ving, để dễ nhớ cần phải hiểu ý nghĩa của từng từ vì các động từ phía trên cần một động từ khác bổ nghĩa cho nó.)

Example: I enjoy working here.

II. To V Infinitive

III. The verbs both To V-infintive, V-ing
1. Stop
- Stop +  V-ing: dừng hẳn một việc làm gì đó
Example:
I stop developing .Net programming language.

- Stop + to Vinfinitive : dừng làm một việc gì đó
Example:
I stop to work on Apache Server because it happened some errors.

2. Remember / forget / regret
- remember/ foget / regret + to + V:  nhớ/quên/tiếc sẽ phải làm (dùng ở hiện tại hoặc tương lai)
- remember / foget / regret + V-ing : nhớ/quên/tiếc đã làm (dùng ở quá khứ)

3. Try
- Try + to + V: cố gắn làm gì đó ~ attempt to
- Try + V-ing: thử làm gì đó

4. Prefer
- prefer v-ing to v-ing: nói chung chung
- prefer to + V + rather than V:

5. Mean
- mean to + V: có ý định làm gì
- mean + V-ing: có nghĩa là gì
 Example:
 I mean to deploy a website for client on sunday this week.
 That mean restarting  the server before Sunday this week.

6. Need
- Need to V: cần làm gì
- Need + V-ing: cần được làm gì (= need to be done): tương tự thể bị động

7. Used to
- Used to V-ing: đã từng lam gì trong quá khứ (bây giờ không làm nữa)
- Be/Get used to + V-ing: đã quen với làm gì (ở hiện tại)

Read more…