What is a JUC

In Java, the threading part is a big focus, and this article is all about threads. JUC stands for java.util.Concurrent toolkit. This is a toolkit for working with threads, which started with JDK 1.5.

Processes and threads

process

Process is a running activity of a program on a data set in a computer. It is the basic unit of resource allocation and scheduling in the system and the basis of operating system structure. In modern thread-oriented computer architectures, processes are containers for threads. A program is a description of instructions, data and their organizational form, while a process is an entity of the program. Is a computer program about a data set on a running activity, is the system for resource allocation and scheduling of the basic unit, is the basis of the operating system structure. A program is a description of instructions, data and their organizational form, while a process is an entity of the program.

thread

A thread is the smallest unit in which an operating system can schedule operations. It is contained within the process and is the actual operating unit within the process. A thread is a single sequential flow of control in a process, and multiple threads can be concurrent in a process, each performing a different task in parallel.

conclusion

Process: an application that is running in the system; Once a program runs, it is a process; Process – the smallest unit of resource allocation.

Thread: A basic unit of the system that allocates processor time resources, or a stream of unit execution that executes independently within a process. Thread – The smallest unit of program execution.

For Java: Thread, Runnable, Callable

Extension: Can Java really start threads?

public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus ! = 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (! started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } Private native void start0(); private native void start0();Copy the code

Concurrency and parallelism

The essence of concurrent programming: Make full use of CPU resources

concurrent

Concurrent (multi-threaded operation of the same resource) CPU a core, simulated out of multiple threads, the world martial arts, only fast not broken, fast alternating

parallel

Multiple people walking together CPU multi-core, multiple threads can be executed at the same time; The thread pool

conclusion

Concurrency: Alternate execution of different blocks of code

Parallelism: Simultaneous execution of different code blocks

Thread state

Public enum State {// Run RUNNABLE, // BLOCKED, // wait, // TERMINATED TERMINATED WAITING for TIMED_WAITING. }Copy the code

Wait/sleep

  • Wait => Object sleep => Thread from different classes
  • [bug Mc-10874] – Wait releases lock, sleep does not release lock.
  • The scope used is different from the code blocks that wait must synchronize, and sleep can be anywhere else
  • Whether to catch exceptions Wait Does not need to catch exceptions Sleep must catch exceptions

Three Lock Lock

Traditional Synchronized

package com.shu; Public class SaleTicketDemo01 {public static void main(String[] args) { Ticket = new Ticket(); Ticket = new Ticket(); // @functionalInterface, jdk1.8 lambda expressions ->{code} new Thread(()->{for (int I = 1; i < 40 ; i++) { ticket.sale(); } },"A").start(); new Thread(()->{ for (int i = 1; i < 40 ; i++) { ticket.sale(); } },"B").start(); new Thread(()->{ for (int i = 1; i < 40 ; i++) { ticket.sale(); } },"C").start(); }} // Resource OOP Class Ticket {// Attributes, methods private int Number = 30; // synchronized The queue, Public synchronized void sale(){if (number>0){ Thread.out.println (thread.currentThread ().getName())+"; }}}Copy the code

features

  • Atomicity: The so-called atomicity refers to an operation or multiple operations, either all performed and the execution process is not interrupted by any factor, or none performed, attention! Interviews often ask about the comparison between synchronized and volatile. The biggest difference between the two qualities is atomicity. Volatile is not atomic.
  • Visibility: Visibility means that when multiple threads access a resource, its state, value information, and so on are visible to other threads.
  • Orderliness: Orderliness values the order in which programs are executed according to code sequence.
  • Reentrancy: In layman’s terms, a thread that owns a lock can still apply for it again.

Underlying principle of Synchronized

  • Before understanding how locks are implemented, take a look at Java’s object headers and Monitor. In the JVM, objects exist in three parts: object headers, instance data, and populating them.

  • Instance data and its population have nothing to do with synchronized, but here’s a brief explanation (I also learned this from understanding the Java Virtual Machine, which you can read carefully). Instance data stores the attribute data information of the class, including the attribute information of the parent class. If it is the instance part of the array, it also includes the length of the array. This part of the memory is aligned by 4 bytes. Padding is not required, because the virtual machine requires that the object’s starting address be an integer multiple of 8 bytes, and padding is just to align the bytes.

  • The object header is the focus that we need to pay attention to. It is the basis for synchronized to realize lock, because synchronized applies for lock, locks, locks release are related to the object header. The main structure of the object header is composed of Mark Word and Class Metadata Address. Mark Word stores the hashCode, lock information, generational age or GC flag of the object. A Class Metadata Address is Class Metadata whose type pointer points to an object that the JVM uses to determine which Class the object is an instance of.

  • There are also different states of lock. In JDK6, there are only two states: lock free and lock (heavyweight lock). In JDK6, there are two states of synchronized: lock free, partial lock, lightweight lock, and heavyweight lock. The type and status of the lock are recorded in the object header Mark Word. The JVM needs to read the Mark Word data of the object during lock application and lock upgrade.

  • Each lock corresponds to a monitor object, which in the HotSpot virtual machine is implemented by ObjectMonitor (C++ implementation). Each object has a Monitor associated with it, and the relationship between the object and its Monitor can be implemented in various ways. For example, the monitor can be created and destroyed together with the object or automatically generated when a thread tries to acquire an object lock. However, when a monitor is held by a thread, it is locked.

ObjectMonitor() { _header = NULL; _count = 0; _waiters = 0, _recursions = 0; _object = NULL; _owner = NULL; _WaitSet = NULL; // Threads in wait state are added to _WaitSet _WaitSetLock = 0; _Responsible = NULL ; _succ = NULL ; _cxq = NULL ; FreeNext = NULL ; _EntryList = NULL ; // Threads in the lock block state are added to the list. _SpinClock = 0 ; OwnerIsThread = 0 ; }Copy the code

The Lock interface

package com.shu; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; Public class SaleTicketDemo02{public static void main(String[] args) { Ticket = new Ticket(); Ticket = new Ticket(); // @functionalInterface, jdk1.8 lambda expressions ->{code} new Thread(()->{for (int I = 1; i < 40 ; i++) ticket.sale(); },"A").start(); new Thread(()->{for (int i = 1; i < 40 ; i++) ticket.sale(); },"B").start(); new Thread(()->{for (int i = 1; i < 40 ; i++) ticket.sale(); },"C").start(); Private int number = 30; private int number = 30; // create Lock Lock Lock =new ReentrantLock(); Public void sale(){// lock lock.lock(); Try {if (number>0){system.out.println (thread.currentThread ().getName()+" +(number--)+", "+ "); } }catch (Exception e) { e.printStackTrace(); } finally {// unlock lock.unlock(); }}}Copy the code

contrast

  • Synchronized is a built-in Java keyword, and Lock is a Java class
  • Synchronized cannot determine the status of obtaining a Lock. Lock can determine whether a Lock is obtained
  • Synchronized automatically releases locks. You must manually release locks! If the lock is not released, a deadlock occurs
  • Synchronized thread 1 (acquire lock, block), thread 2 (wait, fool, etc.); Lock the Lock does not necessarily wait
  • Synchronized can reentrant, can not interrupt, unfair; Lock, reentrant Lock, judge Lock, not fair (can set yourself)
  • Synchronized is good for locking a small number of code synchronization problems, Lock is good for locking a large number of synchronization code!

The last

Welcome to pay attention to the public number: the future has light, receive a line of large factory Java interview questions summary + the knowledge points learning thinking guide + a 300 page PDF document Java core knowledge points summary! These are some of the things that the interviewer should ask during the interview. These include basics, Java collections, JVMS, multi-threaded concurrency, Spring principles, microservices, Netty and RPC, Kafka, diaries, design patterns, Java algorithms, databases, Zookeeper, distributed caching, data structures, and more.