Java Core Technology Volume One

Source: Internet
Author: User
Tags mutex

Java Core Technology Volume One

Java base type

Integral type
Data Type Number of bytes range of Values
Int 4 +_2^4*8-1
Short 2 +_2^2*8-1
Long 8 +_2^8*8-1
Byte 1 -128-127
Floating-point types Number of decimal
Data Type Number of bytes range of Valuesdigits
Float 4 10^-38~10^38 and -10^-38~-10^38 Number of decimal digits 6-7
Double 4 10^-308~10^308 and -10^-308~-10^308 15 decimal Places
Boolean type and char type

Java string

Immutable string
    JVM为了减少字符串对象的重复创建,其维护了一个特殊的内存,这段内存被成为字符串常量池或者字符串字面量池,字符串常量池存在于堆内存中的永久代。1、StringBuilder与 StringBuffer:StringBuilder:线程非安全的,StringBuffer:线程安全的。2、String.intern 方法

Deep analysis of string#intern:http://tech.meituan.com/in_depth_understanding_string_intern.html

Java automatic Boxing and object wrapper

    java中基础类型都有对应的包装器,装箱类型Integer,Long,Double,Short,Float,Byte,Character,Void,Boolean。

Java Collection

    • ArrayList dynamic array, dynamically increasing and shrinking the index sequence
    • LinkedList linked list, efficient insertion and deletion of ordered sequences at any location
    • Arraydeque a double-ended queue implemented with a loop array
    • Hashset unordered list with no repeating elements
    • TreeSet
      Ordered set (binary Tree)
    • Enumset Enumeration Type Set
    • Linkedhashset ordered HashSet
    • HashMap Dictionary
    • TreeMap Ordered mapping table

Java generics

    java与c#一样,都存在泛型的概念,及类型的参数化。java中的泛型是在jdk5.0后出现的,但是java中的泛型与C#中的泛型是有本质区别的,首先从集合类型上来说,java 中的ArrayList<Integer>和ArrayList<String>是同一个类型,在编译时会执行类型擦除,及java中的类型是伪泛型,伪泛型将会在后面介绍,其次,对于像集合中添加基本类型的数据时,例如int,会首先将int转化成Integer对象,即我们通常所说的装箱操作,在取出元素的时候需要将Interger对象转换成int值类型,即拆箱操作。而在c#中,List<int>和List<string>是不同的类型,泛型参数在编译后会是一个占位符,并没有被擦除,在运行时被赋予正真的类型,它们在系统运行期生成,有自己的虚方法表和类型数据,这种实现称为类型膨胀(针对类型膨胀,即时编译器已经做了很多的优化工作来解决这一问题),这就是所谓的真泛型。与此同时,在对集合中添加基本元素如int时,不需要装箱操作,取出元素时不需要拆箱操作,因此,性能上较java的集合泛型要好。java中泛型的引入主要是为了解决两个方面的问题:1.集合类型元素在运行期出现类型装换异常,增加编译时类型的检查,2. 解决的时重复代码的编写,能够复用算法。下面通过例子来说明编译器的类型检查。

Java multithreading

Several states of Java threads
    • New (newly Created)

    • Runnable (can be Run)

    • Blocked (blocked)

    • Waiting (wait) does not consume CPU time

    • Timed Waiting (timed Wait)

    • Terminated (terminated)

        BLOCKED是指线程正在等待获取锁;WAITING是指线程正在等待其他线程发来的通知(notify),收到通知后,可能会顺序向后执行(RUNNABLE),也可能会再次获取锁,进而被阻塞住(BLOCKED)。

      A thread new comes out in the state of new, and when the thread calls the start method, the thread is in the runnable state and the thread enters the blocked blocking state when the thread tries to acquire the resources exclusive to other THREADS. The wait (waiting) state occurs when a thread shleep a method call or attempts to get a conditional lock waiting for another thread to Wake.

        线程终止有两种情况,一种是正常终止,比如调用Thread.join 方法,一种是异常终止,程序发生未处理的异常。

      Note that the Thread.stop () method has been deprecated, forcing it to terminate a thread and a child thread, potentially causing the data to fail to synchronize or the resource not being Released.

Java Thread Priority
    java线程的优先级根据不同的虚拟机映射到不同不同的操作系统优先级,子线程继承主线程的优先级。
Java thread Synchronization
    当竞态条件产生时,java有两种机制防止对象被并发访问的干扰。
    • The lock () reentrantlock Fair lock, unlock () method is used to lock and unlock code Fragments.
    • Condition conditional locks such as the implementation of a bounded buffer:
--------------------------------------------------------------------------------
    Class Boundedbuffer {final Lock lock = new Reentrantlock ();//lock Object final Condition notfull = Lock.newconditi On ();//write thread condition final Condition notempty = lock.newcondition ();//read thread condition final object[] items = new object[100]          ;//cache Queue int putptr/* Write index */, takeptr/* Read index */, number of data present in count/* queue */;          public void put (Object X) throws Interruptedexception {lock.lock ();            Try {while (count = = items.length)//if the queue is full notfull.await ();//block write thread items[putptr] = x;//assignment if (++putptr = = Items.length) Putptr = 0;//if The Write index is written to the last position in the queue, then set to 0 ++count;//number + + notempty.si          Gnal ();//wake-up Read thread} finally {lock.unlock ();          }} public Object take () throws Interruptedexception {lock.lock ();           Try {while (count = = 0)//if the queue is empty notempty.await ();//block read thread Object x = Items[takeptr];//value if (++takeptr = = Items.length) Takeptr = 0;//if ReadThe index is read to the last position of the queue, then set to 0--count;//number--notfull.signal ();//wake-up write thread return x;          } finally {lock.unlock ();  }      }       }
--------------------------------------------------------------------------------
    • Synchronized keywords

      The fair lock and conditional lock provides a fairly granular level of thread synchronization control capability, starting with java1.0, where each object has an internal lock, and we can declare a synchronous method or synchronize a block of code with the synchronized Keyword. Of course, He also cannot provide some fine-grained operational capabilities, such as interrupting a thread that is trying to acquire a lock, setting the block length of the lock, the condition of a single lock, and so On.

    • Volatile and volatile structures

      1. multicore processors can store memory values in registers or local memory buffers, and different processors may read different values from memory

      2. The compiler may change the order in which the instructions are executed according to the optimization scenario, and the compiler assumes that the value of the memory changes only when the instruction that modifies the memory is executed, but another thread may be modifying the memory Value.

Understanding Scenarios + Java Singleton mode:

/** * Fourth attempt to implement a singleton access Kerrigan */public class Singletonkerrigand {/** * Singleton object instance */priv             Ate static Singletonkerrigand instance = null; public static Singletonkerrigand getinstance () {if (instance = = Null) {synchronized (singlet Onkerrigand.class) {if (instance = = Null) {instance = new Singletonkerrigand                     ();         }}} return instance; }} Let's take a look at this scenario: assuming that the thread executes to instance = new Singletonkerrigand (), It looks like a sentence, but in fact it's not an atomic operation (atomic manipulation means that the statement is either executed or not executed). , it is not possible to perform half of this scenario). In fact, there are many non-atomic operations in high-level languages, and we just have to look at the corresponding assembler code that was compiled and executed in the jvm, which is compiled into 8 assembly instructions, roughly doing 3 things: 1. Allocates memory to the instance of Kerrigan. 2. Initialize the Kerrigan Constructor. 3. Point the instance object to the allocated memory space (note that this step instance is not null). however, because the Java compiler allows the processor to execute in a random order (out-of-order), and JDK1.5 jmm (Java Memory Medel) before the cache, register to the main memory write-back order of the provisions, the above 2nd and 3rd order is not guaranteed, That is, the execution order may be either 1-3-2, if the latter, and before the completion of 3, 2 is not executed, is switched to thread two, this time instance becauseOne within the 3rd, instance has been non-empty, so thread two directly take instance, and then use, and then logically error, and this difficult to track difficult to reproduce the error estimate debugging last week may not be able to find out, is really a coffee table cup with ah. It is not entirely true that the DCL is written in a form that is recommended in a number of technical books, textbooks (including books based on JDK1.4 versions). It is true that the DCL is feasible in some languages, such as the C language, depending on whether the order of 2, 3 steps is Guaranteed. After JDK1.5, the authorities have noticed this issue, so the JMM is adjusted and the volatile keyword is materialized, so if the JDK is a 1.5 or later version, you only need to change the definition of instance to "private volatile static Singletonkerrigand instance = null; " It is guaranteed that every time the instance is read from the main memory, it is possible to use the DCL notation to complete the singleton Mode.  of course, volatile is more or less likely to affect performance, and most importantly we have to consider JDK1.42 as well as previous versions, so the improvement of the single-instance pattern in this article Continues.
    • The most common synchronization means in a non-locking programming concurrency environment are mutexes and read-write locks, such as Pthread_mutex and pthread_readwrite_lock, which are commonly used in the following paradigms:

        void ConcurrencyOperation() {      mutex.lock();      // do something      mutex.unlock();  }

      The advantages of this approach are:

      1, the programming model is simple, if the lock sequence is carefully controlled, there is generally no deadlock problem;

      2, can adjust the size of the lock to adjust the Performance.

The disadvantages are:

    • All lock-based algorithms have the possibility of deadlock;
    • Lock and unlock process to switch from the user state to the kernel state, and may accompany the thread scheduling, context switching, etc., the cost is heavier;
    • There is a mutex between the read and write of the shared Data.

No-lock Programming (strictly non-blocking Programming) can be divided into lock free and wait-free two, The following is a brief description of them: "lock free: locks independent, A lock-independent program ensures that at least one of its threads can continue to execute down." This means that some threads may be arbitrarily delayed, but at least one thread in each step can Execute. So the system is always moving forward as a whole, although some threads may progress without the other threads going faster. Wait free: waiting is irrelevant, a program that waits for nothing can end in a finite number of steps, regardless of the relative execution speed of other THREADS. Lock based: lock-based, lock-based programs cannot provide any of the above guarantees, either thread holds a mutex and is waiting, so other threads that want to get consent to the mutex only wait, and all lock-based algorithms cannot escape the shadow of the Deadlock.

Lock free is generally based on CAS (Compare and SWAP) operations

CAS(void *ptr, Any oldValue, Any newValue);即查看内存地址ptr处的值,如果为oldValue则将其改为newValue,并返回true,否则返回false。X86平台上的CAS操作一般是通过CPU的CMPXCHG指令来完成的。CPU在执行此指令时会首先锁住CPU总线,禁止其它核心对内存的访问,然后再查看或修改*ptr的值。简单的说CAS利用了CPU的硬件锁来实现对共享资源的串行使用。

The advantages of this are:

开销较小:不需要进入内核,不需要切换线程;没有死锁:总线锁最长持续为一次read+write的时间;只有写操作需要使用CAS,读操作与串行代码完全相同,可实现读写不互斥。

At the performance level, CAs and Mutex/readwrite lock have their own merits and are summarized as Follows:

The cost of a single-threaded CAs is approximately 10 additions, and the lock + unlock of the mutex is approximately 20 additions, while the ReadWrite lock is much more Expensive. The performance of CAS is fixed, and the mutex can adjust the performance by changing the size of the critical section, and if the real modification operation in the critical section is only a small fraction, then the CAs can be used to achieve greater concurrency. multi-core CPU Thread scheduling cost is higher, at this time more suitable to use Cas.

Lock-free programming also allows for lock-free or more lightweight locking mechanisms by reducing the lock range, see Java Currenhhashmap implementations:

http://blog.csdn.net/kjfcpua/article/details/11937817

    • Thread interrupts in Java provide a thread break in the interrupt method, which is actually a CPU interrupt obtained without stripping the CPU to run a time slice, but instead provides a notification mechanism to tell the thread that the interrupt logic should be handled.

    • Thread pool

Java Thread pool creation syntax:

ExecutorService threadPool = Executors.newFixedThreadPool(3)

Java JVM,GC

Java Nio,netty

Java Core Technology Volume One

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.