Pole * Java Crash Course - (8)

Java Advanced Features

annotation

Annotations can add more information in addition to the code, a more complete description of the program to help the compiler to work, or to achieve certain specific function other than Java code.
Annotations can simplify certain repeatable processes, automate those processes.

Use annotations

Use annotations no different from other modifiers. Java provides three standard comment:

  • @Override
    show that the method will be covered by the parent class method, when the method signature and is not covered methods at the same time, the compiler will report an error.
  • @Deprecated
    If developers use the annotated element, then the compiler will issue a warning.
  • @SuppressWarnings
    closed improper compiler warnings.

Defined annotations

Before using annotations, notes need to be defined. Notes does not support inheritance, like annotated defined an empty interface, use @interfacemodified, the definition of notes, above require some meta-annotation.
There are four meta-annotation for the annotation of other notes:

  • @Target used to define your notes used in any place, such as a method or a domain
    • CONSTRUCTOR constructor declaration
    • FIELD field declaration
    • LOCAL_VARIABLE local variable declaration
    • METHOD method declaration
    • PACKAGE package declaration
    • PARAMETER parameter declaration
    • TYPE classes, interfaces (including type of annotation), or an enum declaration
  • @Retention annotation can be used to define which level, such as source code, or runtime class file.
    • SOURCE annotation will be discarded compiler
    • CLASS Annotations can be used in the class file, but will be dropped VM
    • RUNTIME VM will be retained annotations at runtime, can be read by reflection annotation information
  • @Documented this comment included in the Javadoc
  • @Inherited allows annotation subclass inherits the parent class

Notes can contain some elements to represent some value, if there is no element, then this comment is called a marker annotation. Annotation elements can have default values.

The definition and use of annotations as follows:

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
  public int id();
  public String description() default "no description";
}

import java.util.*;

public class PasswordUtils {
  @UseCase(id = 47, description =
  "Passwords must contain at least one numeric")
  public boolean validatePassword(String password) {
    return (password.matches("\\w*\\d\\w*"));
  }
}

After setting the annotation, also you need to create annotation processor, processing of annotations. Class can be used getDeclaredMethods () Get all classes other than the present methods inherited, getAnnotation () method to get the specified type annotation method.

Annotation elements

Annotations can be used to record notes element annotation information.
Annotations can be used in the following types:

  • All basic types
  • String
  • Class
  • enum
  • Annotation
  • More than one type of array

Element must have a default value, otherwise it must provide value when using annotations. For non-base type element, which is not a null value (but empty string ""and negative specific meaning is allowed)

Java is apt tool

In Java, you can use the tool apt annotation processor is invoked, it annotated source code for processing. Class must provide a path plant or factory class.
However, in the above Java7, recommended javax.annotation.processing annotation tools for the development of processors. Related Content Reference annotation processor Detailed

Complicated by

Parallel methods

Use runnable interfaces

Threads can drive task, the task can be written by implementing Runnable interface and run () method is described.
Will be submitted Runnable object to the Thread constructor, you can create a thread to the driving task. Then start Thread class () method, you can start the task.

, Can be managed by the Thread object class Executor java.util.concurrent package.
() Method to create a thread pool by newCachedThreadPool, and then call the execute () method to register tasks ExecutorService objects can be processed in parallel. Call shutdown () method to stop accepting new tasks.
In addition to CachedThreadPool, there FixedThreadPool such as thread pool can use, FixedThreadPool can perform a one-time pre-expensive thread allocation tasks, while the number of threads can also be restricted. SingleThreadExecutor while only running one thread, the execution sequence of tasks will be submitted at the same time maintain a task queue in sequence.
All threads in the pool, under the existing thread if possible, will be automatically reused.

Use Callable Interface

By implementing Callable interface class may execute concurrently, () method call can return a return value after the task is completed. This method must be used ExecutorService object submit () method to submit the task.
submit () method produces Future object that can be used isDone () method of inquiry has been completed, when the task is completed, you can use the get () method to obtain returns the result. get () method is also a blocking method.

May be within the class, the class inherits the inside by a method or implemented runnable Thread class interface achieve multithreading.

Parallel control

Through to Thread.sleep () or TimeUnit.MILLISECONDS.sleep () method, allows thread to sleep.
In the run () method (provided constructor invalid) using the setPriority thread object () method sets the thread priority, getPriority () method gets thread priority, JDK priority and the priority of the operating system does not correspond the method is to use portable Thread.MIN_PRIORITY, Thread.MAX_PRIORITY and Thread.NORM_PRIORITY.
The use of yield () may be alluded to in the thread scheduling can make concessions (not guaranteed to achieve).
Before the thread is started, using the Thread object setDeamon () method can be set as the thread a background thread. ThreadFactory achieved by the interface, in the interface can newThread () method of the Thread-created setDeamon () is provided. By isDeamon () query thread is a background thread.
Calls the join () method on the thread object, the thread can be suspended until the end of the timeout or the target thread t was restored. interrupt () method will be interrupted join, and set the interrupt flag. isInterrupted () method returns a value based on the interrupt flag, interrupt will throw an exception, however, it will clean up this flag when an exception is caught.

Parallel exception handling

By class methods ThreadFactory by setUncaughtExceptionHandler () implements an exception handler Thread.UncaughtExceptionHandler interface attached to the thread, if the thread throws an exception, then the exception handler processing referred to. You can also use setDefaultUncaughExceptionHandler () method to set the default thread exception handler.

Parallel competition control

Shared resources can be modified by synchronized keyword, Java automatically checks whether the resource has a lock, is available. When using the synchronized keyword, domain should be private time, or keyword can not guarantee that other tasks will not create a conflict of access to the domain.
Locks may also be used in the class library java.util.concurrent explicitly locked. class lock () by the lock; tryLock () and unlock () method lock to lock. ReentrantLock allowed to try to obtain but ultimately did not acquire the lock when the lock can not get to leave rather than wait for additional processing.

Guess you like

Origin www.cnblogs.com/CoveredWithDust/p/Fast_JAVA_8.html