2019 Java Interview Basics series 228

The answer to questions 1 to 20 in the first update is analyzed

Juejin. Cn/post / 684490…

21~50

Juejin. Cn/post / 684490…


51~95

Juejin. Cn/post / 684490…




Java Interview Questions (2)

Can volatile arrays be created in Java?

2. Can volatile make a nonatomic operation atomic?

What is the practice with volatile modifiers?

4. What guarantees do volatile variables provide?

Which is easier to write, 5, 10 or 2 thread synchronization code?

How do you call wait ()? If block or loop? Why is that?

8. What is Busy Spin? Why do we use it?

How to obtain a thread dump file in Java?

Is Swing thread-safe?

What are thread-local variables?

Use wait-notify to write code to solve a producer-consumer problem.

Write a thread-safe Singleton in Java?

What is the difference between sleep and wait in Java?

What is an immutable object? How do you create an immutable object in Java?

16. Can we create an immutable object that contains mutable objects?

17. What data types should be used to represent prices in Java?

18, How to convert byte to String?

19. How do you convert bytes to long in Java?

20. Can we cast int to byte? What happens if the value is greater than the byte range?



Questions 1 to 20 of the Java Interview questions (2) are updated

Can volatile arrays be created in Java?

Yes, you can create volatile arrays in Java, but only as a reference to the array, not the entire array. What I mean by that is that changing the array to which the reference refers is protected by volatile, but if multiple threads change the elements of the array at the same time, the volatile identifier is not protected.

2. Can volatile make a nonatomic operation atomic?

A typical example is having a member variable of type long in a class. If you know that the member variable will be accessed by multiple threads, such as counters, prices, etc., it is best to set it to volatile. Why is that? Because reading a long variable in Java is not atomic and requires two steps, if one thread is changing the value of the long variable, another thread may only see half of the value (the first 32 bits). But reading or writing to a volatile long or double is atomic.

What is the practice with volatile modifiers?

One practice is to use volatile to modify long and double variables so that they can be read and written by atomic type. Double and long are both 64 bits wide, so reads of both types are split into two parts, first reading the first 32 bits and then reading the remaining 32 bits. This process is not atomic, In Java, however, volatile long or double variables are read and written atomically. Another use of volatile fixes is to provide memory barriers, as in distributed frameworks. In simple terms, the Java memory model inserts a writebarrier before you write a volatile variable, and a read barrier before you read a volatile variable. This means that when you write a volatile field, you can ensure that any thread can see the value you write, and that any value changes are visible to all threads prior to writing, because the memory barrier updates all other written values to the cache.

4. What guarantees do volatile variables provide?

Volatile variables provide order and visibility guarantees. For example, the JVM or JIT may reorder statements for better performance, but volatile variables do not reorder statements even if they are assigned without synchronized blocks. Volatile provides a happens-before guarantee that changes made by one thread are visible to other threads. Volatile can also provide atomicity in some cases, such as reading 64-bit data types, such as long and double, which are not atomic, but double and long, which are volatile.

Which is easier to write, 5, 10 or 2 thread synchronization code?

From a coding standpoint, the complexity is the same, because synchronized code is independent of the number of threads. But the choice of synchronization strategy depends on the number of threads, because more threads means more contention, so you need to take advantage of synchronization techniques such as lock separation, which require more complex code and expertise.

How do you call wait ()? If block or loop? Why is that?

The wait() method should be called in a loop, because other conditions may not have been met by the time the thread gets to the start of CPU execution, so it is better to loop to check if the conditions have been met before processing. Here is a standard code that uses wait and notify:

// The standard idiom for using the wait method
synchronized (obj) {
	while (condition does not hold)
	obj.wait();
	// (Releases lock, and reacquires on wakeup)
	... // Perform action appropriate to condition
}Copy the code

7. What is false sharing in multi-threaded environments?

Pseudo-sharing is a well-known performance problem in multithreaded systems (where each processor has its own local cache). Pseudo-sharing occurs when threads on different processors modify variables depending on the same cache line.

8. What is Busy Spin? Why do we use it?

Busy Spin is a technique that waits for events without releasing the CPU. It is often used to avoid losing data in the CPU’s cache (lost if the program is paused first and then runs on another CPU). So, if your job requires low latency and your threads are currently out of any order, you can loop through the queue to detect new messages instead of calling sleep() or wait(). The only advantage is that you only have to wait a few microseconds or nanoseconds. The LMAX Distributed framework is a high performance library for interthread communication. The library has a BusySpinWaitStrategy class implemented based on this concept, using the BusySpin loop EventProcessors wait barrier.

How to obtain a thread dump file in Java?

On Linux, you can run the kill -3 PID command to obtain the dump file of the Java application. On Windows, you can get it by pressing Ctrl + Break. The JVM then prints the thread’s dump file to standard output or an error file, either in the console or in a log file, depending on the configuration of the application. If you use Tomcat.

Is Swing thread-safe?

No, Swing is not thread-safe. Swing components such as JTable, JList, or JPanel cannot be updated by any thread; in fact, they can only be updated by GUI or AWT threads. This is why Swing provides the invokeAndWait() and invokeLater() methods to get GUI update requests from other threads. These methods put the update request into a thread queue in the AWT and can either wait or return the result directly through asynchronous updates. You can also see and learn more details in the reference answers.

What are thread-local variables?

Thread-local variables are variables that are limited within a thread and are owned by the thread itself and are not shared between multiple threads. Java provides a ThreadLocal class to support thread-local variables as a way to achieve thread-safety. However, be careful when using thread-local variables in a managed environment, such as a Web server, where the life of a worker thread is longer than the life of any application variable. Java applications run the risk of memory leaks if any thread-local variables are not released after work is done.

Use wait-notify to write code to solve a producer-consumer problem.

Just remember to call wait() and notify() in the synchronized block and, if blocked, test the wait condition through a loop.

Write a thread-safe Singleton in Java?

Step by step, create a thread-safe Java singleton class. When we say thread-safe, we mean that even if the initialization is in a multi-threaded environment, a single instance can still be guaranteed. In Java, using enumerations as singleton classes is the easiest way to create thread-safe singleton patterns.

What is the difference between sleep and wait in Java?

While both are used to pause the currently running thread, sleep() is actually a short pause because it does not release the lock, and wait() means conditional waiting, which is why this method releases the lock so that other waiting threads can acquire the lock when the condition is met.

What is an immutable object? How do you create an immutable object in Java?

Immutable objects mean that once an object is created, its state cannot be changed. Any changes create a new object, such as String, Integer, and other wrapper classes. See the answer for a step-by-step guide to creating an immutable class in Java.

16. Can we create an immutable object that contains mutable objects?

Yes, it is possible to create an immutable object that contains a mutable object. You just need to be careful not to share references to mutable objects, and return a copy of the original object if changes are needed. The most common example is when an object contains a reference to a date object. Data types and Java basics interview questions

17. What data types should be used to represent prices in Java?

Use BigDecimal if you are not particularly concerned with memory and performance, otherwise use a double of predefined precision.

18, How to convert byte to String?

The conversion can be done using the String constructor that accepts the byte[] argument. The important thing is to use the correct encoding, otherwise the platform default encoding will be used, which may or may not be the same as the original encoding.

19. How do you convert bytes to long in Java?

The bytes[] conversion to a numeric type is a frequently used code with more than one solution.

Java code implementation

If you don’t want to use any existing classes, you can implement this code yourself, as follows:

/** * Convert the byte array to long<br> * If input is null, or the remaining array specified by offset is less than 8 bytes, an exception is thrown * @param input * @param offset The initial offset * @param LittleEndian input array whether the littleEndian mode * @return*/ public static long longFrom8Bytes(byte[] input, int offset, Boolean littleEndian){ long value=0; // Loop through each byte to complete the 8-byte assembly of longfor(int count=0; count<8; ++count){ intshift=(littleEndian? count:(7-count))<<3; value |=((long)0xff<<shift) & ((long)input[offset+count] << shift);
	}
	return value;
}Copy the code

Implemented with java.nio.byteBuffer

Java.nio.bytebuffer itself has getLong,getInt,getFloat… Byte [] can be converted to ByteBuffer for reading data of all primitive types. See Javadoc.

/** * Use {@link java.nio.byteBuffer} to implement byte[] to long * @param input * @param offset * @param littleEndian input array * @return*/ public static long bytesTolong(byte[] input, int offset, Boolean littleEndian) {// Wrap byte[] as ByteBuffer.if(littleEndian){// bytebuffer. order(ByteOrder) specifies the ByteOrder, i.e. BIG_ENDIAN/LITTLE_ENDIAN // ByteBuffer The default mode is BIG_ENDIAN buffer.order(byteorder.little_endian); }return buffer.getlong();
}Copy the code

Implement with java.io.DataInputStream

Java. IO. A DataInputStream also provides readLong readLong readLong… Byte [] can be converted to DataInputStream to read data of all primitive types. See Javadoc.

20. Can we cast int to byte? What happens if the value is greater than the byte range?

Yes, we can cast, but Ints in Java are 32 bits and byte is 8 bits, so if cast is, the higher 24 bits of ints are discarded, and byte ranges from -128 to 127.



The last

Welcome everyone to pay attention to my public kind hao [programmer tracking wind], organized 1000 2019 Java interview questions of many companies more than 400 pages of PDF documents, articles will be updated in it, organized information will also be placed in it. If you like the article, remember to pay attention to me. Thank you for your support!