Intermediate knowledge of Java induction (IV)

Sixteen, Java Memory Model

  Features: atom, visibility, orderly.

  Atomic: read, load, use, store, write, synchronized keyword to ensure atomicity

  Visibility: the synchronized, volatile , Final ensure visibility

  Ordering: synchronized to ensure the orderly

XVII design patterns

  ① Category :

    Create Type Modes (5): factory method model , abstract factory mode, single-mode embodiment , the builder pattern, the prototype model .

    Structural mode (7 types): adapter mode, decorative mode, proxy mode , the appearance mode, bridge mode, combination mode, Flyweight.

    Behavioral patterns (11 kinds): Strategy Mode, the template method pattern, observer mode , iterator pattern, the responsibility chain mode, command mode, the memo mode state mode, the visitor pattern, intermediary model to explain the mode.

    other: concurrency pattern and thread pool mode.

  ② Design Patterns six principles :

    Open Closed Principle (Open Close Principle): opening and closing the principle that is open for extension, but closed for modification. When the program needs to expand, not to modify the existing code to achieve the effect of a hot-swappable. All summarized in one sentence: To make good, easy to maintain and upgrade the extension of the program. Want to achieve this effect, we need to use interfaces and abstract classes.

    Richter substitution principle (Liskov Substitution Principle, abbreviated as: LSP): One of the basic principles of object-oriented design. Richter substitution principle in that place any base class can appear, sub-class will be able to appear. LSP is inherited cornerstone multiplexed only when the derived class can replace the base class, the software unit of functionality is not affected, the base class can really be reused, derived class can add new behavior on the basis of the base class on . Richter substitution principle is - to add "on-off" principle. To achieve "open - closed" principle is a key step in abstraction. The inheritance relationship with a base class is a subclass of the abstract concrete realization, so Richter substitution principle is the specification for concrete steps to achieve the abstract.

    Dependency Inversion principle (Dependence Inversion Principle): this is the basis of the principle of opening and closing, the specific content: for interface programming, relies on the abstract rather than relying concrete.

    Interface segregation principle (Interface Segregation Principle): the meaning of this principle is that: a plurality of interface isolation, is better than using a single interface. Or a lower degree of coupling between classes mean, from here we see that, in fact, a design pattern is a design software from triggering large-scale software architecture, in order to upgrade and easy maintenance. Therefore, the above multiple times: reduce dependence, reduce coupling.

    Demeter (minimum principle known) (Demeter Principle): Why call least known principles, that is to say: an entity should minimize the interaction between the entity and the other, such that the independent function modules.

    Synthesis of multiplexing principles (Composite Reuse Principle): principle is to use the synthetic polymeric info / instead of inheritance.

Eighteen, Java reflection (focus)

  Reflection refers to the program itself can obtain information at runtime.

  Why use reflection? Not directly create objects on it yet, which involves the dynamic and static concept:

    Statically compiled: determined at compile-time type, binding objects, namely through.

    Dynamic compilation: determine the type of running, binding objects. To maximize the flexibility of dynamic compilation of java, polymorphism reflects the application, to reduce the coupling between classes.

  The advantages of a word, reflection is that you can create objects and dynamic compilation, reflecting great deal of flexibility, particularly in the development of J2EE in its flexibility to have been very obvious.

  Role: ① first have to create a Class object according to the full name of the incoming class. ② method class methods available. ③ a method of obtaining a class attribute.

  Disadvantages: ① performance of the first: reflector includes a number of dynamic type, the JVM can not optimize the code. Thus, the efficiency of the operation reflected much lower than those of non-reflex actions. We should avoid the use of reflective frequently executed code or high performance requirements of the program. ② security restrictions: the use of reflective technology requirements of the program must be run in a restricted environment is not safe. If a program must be run in environments with security restrictions, as Applet. Internal exposure ③: Since the reflective allow code is not permitted to perform some operation under normal conditions (such as access to the private attributes and methods), the use of reflection may cause unexpected side effects - on the code error function, reduced portability. It destroyed the abstract reflection code, so when the platform is changed, the behavior of the code, there may also vary.

Nineteen, Java references

 

① Suppose we wrote the following statement in this simple function:

 

StringBuffer str= new StringBuffer("Hello world"); 

 

Although this statement is simple, in fact, it contains the following three steps:

 

First, new StringBuffer ( "Hello world") in the application heap memory cook, to create a good StringBuffer objects into them. Secondly, StringBuffer str declares a pointer. The pointer itself is stored on the stack (as written statements in a function), can be used to point to objects of a StringBuffer type. Or put it another way, this pointer can be used to store the address of a StringBuffer object. Save that last lump of memory address, which is equal to the number (of assignments) to associate the two together, that is to just apply to the value of str, complete reference.

 

②final constant problem

 

针对引用类型变量的final修饰符也是很多人搞混淆的地方。实际上final只是修饰指针的值(也就是限定指针保存的地址不能变)。至于该指针指向的对象,内容是否能变,那就管不着了。所以,对于如下语句:

 

final StringBuffer strConst = new StringBuffer();

 

你可以修改它指向的对象的内容,比如:

 

strConst.append(" ");

 

但是不能修改它的值,比如:

 

strConst = null;

 

③传参的问题:

 

例如:System.out.println(str);这个语句又是什么意思捏?这时候就两说了。

 

第一种理解:可以认为传进函数的是str这个指针,指针说白了就是一个地址的值,说得再白一点,就是个整数。按照这种理解,就是传值的方式。也就是说,参数传递的是指针本身,所以是传值的。

 

第二种理解:可以认为传进去的是StringBuffer对象,按照这种理解,就是传引用方式了。因为我们确实是把对象的地址(也就是引用)给传了进去。

二十、线程、线程池

 

①创建线程有两种方式:继承Thread或实现Runnable。Thread实现了Runnable接口,提供了一个空的run()方法,所以不论是继承Thread还是实现Runnable,都要有自己的run()方法。一个线程创建后就存在,调用start()方法就开始运行(执行run()方法),调用wait进入等待或调用sleep进入休眠期,顺利运行完毕或休眠被中断或运行过程中出现异常而退出。

 

②wait和sleep比较:sleep方法有:sleep(long millis),sleep(long millis, long nanos),调用sleep方法后,当前线程进入休眠期,暂停执行,但该线程继续拥有监视资源的所有权。到达休眠时间后线程将继续执行,直到完成。若在休眠期另一线程中断该线程,则该线程退出。等待有其它的线程调用notify()或notifyAll()进入调度状态,与其它线程共同争夺监视。

 

③线程池:多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。一个线程池包括以下四个基本组成部分:

 

A、线程池管理器(ThreadPool):用于创建并管理线程池,包括创建线程池,销毁线程池,添加新任务;

 

B、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;

 

C、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;

 

D、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。

 

④线程池分类:

 

A、newFixedThreadPool  创建一个指定工作线程数量的线程池。

 

每当提交一个任务就创建一个工作线程,如果工作线程数量达到线程池初始的最大数,则将提交的任务存入到池队列中。

 

B、newCachedThreadPool创建一个可缓存的线程池。

 

这种类型的线程池特点是:

 

1).工作线程的创建数量几乎没有限制(其实也有限制的,数目为Interger.MAX_VALUE), 这样可灵活的往线程池中添加线程。

 

2).如果长时间没有往线程池中提交任务,即如果工作线程空闲了指定的时间(默认为1分钟),则该工作线程将自动终止。终止后,如果你又提交了新的任务,则线程池重新创建一个工作线程。

 

C、newSingleThreadExecutor创建一个单线程化的Executor,即只创建唯一的工作者线程来执行任务,如果这个线程异常结束,会有另一个取代它,保证顺序执行(我觉得这点是它的特色)。

 

单工作线程最大的特点是可保证顺序地执行各个任务,并且在任意给定的时间不会有多个线程是活动的。

 

D、newScheduleThreadPool  创建一个定长的线程池,而且支持定时的以及周期性的任务执行,类似于Timer。

 

⑤Executors类,提供了一系列静态工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。

 

⑥线程池参数:

 

A、corePoolSize(线程池的基本大小)

 

B、runnableTaskQueue(任务队列):用于保存等待执行的任务的阻塞队列。

 

1)LinkedBlockingQueue:一个基于链表结构的阻塞队列,此队列按FIFO (先进先出) 排序元素,吞吐量通常要高于ArrayBlockingQueue。静态工厂方法Executors.newFixedThreadPool()使用了这个队列。

 

2)SynchronousQueue:一个不存储元素的阻塞队列。每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于LinkedBlockingQueue,静态工厂方法Executors.newCachedThreadPool使用了这个队列。

 

3)PriorityBlockingQueue:一个具有优先级的无限阻塞队列。

 

C、maximumPoolSize(线程池最大大小):线程池允许创建的最大线程数。

 

D、ThreadFactory:用于设置创建线程的工厂,可以通过线程工厂给每个创建出来的线程设置更有意义的名字。

 

E、RejectedExecutionHandler(饱和策略):当队列和线程池都满了,说明线程池处于饱和状态,那么必须采取一种策略处理提交的新任务。这个策略默认情况下是AbortPolicy,表示无法处理新任务时抛出异常。以下是JDK1.5提供的四种策略:

 

1)AbortPolicy:直接抛出异常。

 

2)CallerRunsPolicy:只用调用者所在线程来运行任务。

 

3)DiscardOldestPolicy:丢弃队列里最近的一个任务,并执行当前任务。

 

4)DiscardPolicy:不处理,丢弃掉。

 

5)当然也可以根据应用场景需要来实现RejectedExecutionHandler接口自定义策略。如记录日志或持久化不能处理的任务。

 

F、keepAliveTime(线程活动保持时间):线程池的工作线程空闲后,保持存活的时间。所以如果任务很多,并且每个任务执行的时间比较短,可以调大这个时间,提高线程的利用率。

 

G、TimeUnit(线程活动保持时间的单位):可选的单位有天(DAYS),小时(HOURS),分钟(MINUTES),毫秒(MILLISECONDS),微秒(MICROSECONDS, 千分之一毫秒)和毫微秒(NANOSECONDS, 千分之一微秒)。

 

 

    

 

Guess you like

Origin www.cnblogs.com/tizer/p/11361333.html