Java surface for personal use 5
-
How does java start threads? How to ensure thread safety?
The difference between thread and process: process is the smallest unit of resource allocation by the operating system. Thread is the smallest unit of task allocation in the operating system. Thread belongs to process
How do I start a thread?
1. Inherit Thread and override run method
2. Implement the Runnable interface and rewrite the run method
3. Implement the Callable interface and call method. Create a thread through FutureTask to obtain the return value of the thread execution
class myth implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName()+"====="+"I'll take your mother"); return 1024; } } public class mythread { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Integer> task = new FutureTask<>(new myth()); FutureTask<Integer> task2 = new FutureTask<>(new myth()); new Thread(task, "AA").start(); new Thread(task, "BB").start(); System.out.println(task.get()); } }
-
Start thread through thread pool
public class myDiyThreadPool { public static void main(String[] args) { System.out.println(Runtime.getRuntime().availableProcessors()); ThreadPoolExecutor pool = new ThreadPoolExecutor( 2, 5, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy() ); try { for (int i = 1; i <= 10; i++) { // pool1.execute(new Thread() { // @Override // public void run() { // System.out.println(); // } // }); // The maximum thread pool is 5 + 3 = 8, but an error is reported for 10 requests pool.execute(() -> { // There are only five threads to execute System.out.println(Thread.currentThread().getName()+"Execute business"); }); } } catch (Exception e) { e.printStackTrace(); } finally { pool.shutdown(); } } }
-
How to ensure thread safety? Lock. 1. Use the locks provided by the jvm and various locks provided by synchronized2.JDK
-
What's the difference between Volatile and synchronized? Can Volatile ensure thread safety? Why does DCL (double ended retrieval mechanism) add Volatile for a single case?
1.volatile can only guarantee the visibility of variables, but can not guarantee atomicity and prohibit instruction rearrangement. It is usually applicable to the situation that one thread writes and multiple threads read
The synchronized keyword is used to lock
2.volatile can only guarantee thread visibility, not atomicity
3. Prevent instruction rearrangement (1. The cpu reads data from the memory, 2. The memory returns to the cpu, and 3. The cpu performs operations internally. Because the cpu performs operations 1 and 2 very quickly, the response time of operations 2 is too long, and the system optimizes it to perform operations 2 after performing operations 3 in this gap, which is called instruction rearrangement)
For example, the process of object creation:
1. Allocate memory 2. Initialize objects 3. Establish pointer correspondence. If the thread is unsafe, instruction rearrangement (1, 2, 3,) will be disordered
public class danli { private static volatile danli obj = null; private danli() { System.out.println("Hello, I'm" + Thread.currentThread().getName()); } public static danli getObj() { if (obj == null) { synchronized (danli.class) { if (obj == null) { obj = new danli(); } } } return obj; } }
-
What is the java thread locking mechanism? What's the difference between bias lock, lightweight lock and heavyweight lock? How to upgrade the lock mechanism?
A lock is to record a lock status in the object's Markword. Lock free, biased, lightweight and heavyweight locks all correspond to different lock states. The lock mechanism is a process of continuously upgrading locks according to the intensity of resource competition
Bias lock: the thread can access the information after registering it
Lightweight lock: spin lock, fail retry, waste cpu, wait until the lock is released, and successfully obtain the lock volatile
Heavyweight lock: it needs to interact with the operating system, which is inefficient. synchronized
The jvm optimizes the new object with two parameters
-20: Whether the bias lock is turned on by usebiasedlocking. It is not turned on by default
-20: Biasedlockingstartupdelay open bias lock in 4 seconds
-
Talk about your understanding of AQS. How does AQS implement reentrant locks?
1.AQS is a framework for JAVA thread synchronization. Almost all locks in JDK are implemented based on AQS
2. In AQS, a bidirectional linked list queue composed of semaphore state=0, locked thread = null and one thread is maintained
After thread 1 obtains the lock state=1, CAS judges whether it is successful. After success, the locking thread = thread 1, and thread 2 enters the waiting queue. After thread 1 releases the lock, the state decreases, and the locking thread becomes null. Take thread 2 out of the waiting queue (re-entry, multiple locking, multiple release, locking times = lock release times)
-
There are three ABC threads. How to ensure that the three threads execute at the same time? Execute in sequence? Orderly interleaving execution?
Concurrent tools: CountDownLatch, CylinBarrier, Semaphore
Simultaneous execution:
newCountDownLatch(1).await();
Orderly execution
class bean { private Lock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); private Condition c3 = lock.newCondition(); public void print(int number) { lock.lock(); if (number == 1) { for (int i = 1; i <= 5; i++) { System.out.println(Thread.currentThread().getName() + "==" + i); } c2.signal(); try { c3.await(); } catch (InterruptedException e) { e.printStackTrace(); } } if (number == 2) { for (int i = 1; i <= 10; i++) { System.out.println(Thread.currentThread().getName() + "==" + i); } c3.signal(); try { c1.await(); } catch (InterruptedException e) { e.printStackTrace(); } } if (number == 3) { for (int i = 1; i <= 15; i++) { System.out.println(Thread.currentThread().getName() + "==" + i); } c1.signal(); try { c2.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class condition { public static void main(String[] args) { bean b = new bean(); new Thread("A") { @Override public void run() { for (int i = 1; i <= 10; i++) { b.print(1); } } }.start(); new Thread("B") { @Override public void run() { for (int i = 1; i <= 10; i++) { b.print(2); } } }.start(); new Thread("C") { @Override public void run() { for (int i = 1; i <= 10; i++) { b.print(3); } } }.start(); } }
Orderly interleaving execution:
The Semaphore implementation is similar to the above code. S1, s2, S3. After S1. Acquire() is executed, s2.release(), s2 starts s2.acquire() in turn
- How to sort a string quickly? (Fork/Join framework)
Divide and rule, split and summarize
Divide the large task into several small tasks and put them into the task list. Then join the calculation, schedule the cpu thread resources, use the number of cpu cores as much as possible, and split the large task into many small subtasks
-
What is the difference between TCP and UDP? Why does TCP shake hands three times instead of two?
TCP: a connection oriented, reliable, transport layer communication protocol, point-to-point communication, which is inefficient and occupies more resources
UDP: a connectionless, unreliable, transport layer communication protocol. The sender sends directly whether the receiver is ready or not. Broadcast transmission is unreliable and may lose messages. It has high efficiency and occupies less resources
2. If the network is unstable, it will cause transmission failure and waste of resources
-
How many io models are there in java? What's the difference?
Synchronous asynchronous for requests, blocking non blocking for clients
BIO synchronization blocking io has poor reliability and low throughput. It is suitable for scenarios with few and relatively fixed connections
NIO synchronous non blocking io has good reliability and high throughput. It is suitable for scenarios with many connections and short connections, such as chat rooms
AIO asynchronous non blocking io has the best reliability and high throughput. It is suitable for scenarios with many connections and long connection time. For example, the album server has a simple programming model and needs the support of the operating system
-
The core component of java nio? What is the role of each?
Channel Buffer Selector
Channels are similar to streams. Each channel corresponds to a buffer buffer. The channel will be registered with the selector, and the selector will give it to an idle thread for processing according to the read-write events on the channel. The selector must correspond to one or more threads
Both buffer and selector are readable and writable
-
The difference between HTTP and HTTPS
HTTP: it is the most widely used network communication protocol on the Internet. Based on TCP, it can make the browser more efficient
HTTPS: it is an enhanced version of HTTP, which can be considered as HTTP+SSL. A series of security mechanisms are added on the basis of HTTP. On the one hand, ensure the safety of data transmission. On the other hand, an authentication mechanism is added to visitors. It is the most secure solution at present
difference:
1.HTTP connection is simple and stateless, and HTTPS data transmission is encrypted by certificate, with higher security
2.HTTP is free, and HTTPS requires certificates and charges
3.HTTP port 80, Https port 443
HTTPS disadvantages:
1.HTTPS handshake protocol is time-consuming and will affect the response speed of the service
2.HTTPS is not completely secure, and the certificate system is not completely secure. Moreover, HTTPS can hardly play a role in the face of DDoS (a large number of access to servers and many times of authentication) attacks.
3. The cost of different security level certificates is also different
-
What is the whole process of JAVA class loading? What is the parental delegation mechanism? What does an object go through from loading into the jvm to being cleaned up by gc?
JAVA class loader: APPCLASSLOADER, EXTCLASSLOADER, BOOTSTRAP CLASSLOADER
Each kind of loader has its own loading directory to load jar packages under the directory
Each class loader has a cache of loaded classes
Upward delegate search and downward delegate load function: protect the underlying classes of java from being overwritten by applications
Class loading process: load - > connect - > initialize
Load: load the java bytecode data into the jvm memory and map it to the data structure recognized by the jvm
Connection: 1. Verification: check whether the loaded byte information conforms to the jvm specification. 2. Preparation: create a static variable of a class or interface and assign the initial value to a semi initialized state. 3. Resolution: convert the symbolic reference to a direct reference
initialization:
What does an object go through from loading into the jvm to being cleaned up by gc?
1. When the user creates an object, the jvm first goes to the method area to find the type information of the object, and then creates the object
2. To instantiate an object, the JVM must first create an object in the heap. Semi initialized state
3. The object will first be allocated to the new generation EDEN area in the heap memory, and then undergo a Minor GC. If the object survives, it will enter the s area. In the follow-up, if the object survives all the time, it will copy back and forth in the s area. Each time it moves, the object will be transferred to the old generation after the age plus 1 (the maximum age is 15) exceeds a certain age
4. After the method is executed, the pointer in the stack will be removed first
5. After fullgc, the objects in the heap will be marked as garbage and then cleaned up
- What garbage collectors does the jvm have? How do they all work? What is stw? At what stage did he happen? What is tricolor marking? How to solve the problem of wrong marking and missing marking? Why design so many garbage collectors?
stw: stop the world is a state in which the jvm memory needs to be frozen during the execution of the garbage collection algorithm. In the stw state, all threads of java are stopped. Except GC threads, the native method can execute, but cannot interact with the jvm.
The optimization of various GC algorithms focuses on reducing stw, which is also the focus of jvm tuning
The core algorithm of CMS is tricolor marking
Tricolor marking: it is a logical abstraction that divides memory objects into three colors: Black indicates that they and member variables have been marked. Gray: self marking is completed, but the member variables are not completely marked. White: you haven't finished marking
cms solves the problem of missing labels by incrementally marking increment update
- How to tune the jvm? What are the jvm parameters? How do I view the jvm parameters of a process? Talk about your understanding of jvm parameters. If a java program becomes very stuck after running for a period of time, how to optimize it?
jvm tuning: improve the running data of java applications by customizing jvm running parameters
Troubleshooting with Arts