Java Threads (iii)

Source: Internet
Author: User
Tags connection pooling finally block semaphore thread class volatile

Connected to the Java Thread (ii), finally finished ...

) which parameter in the JVM is the small stack stack used to control the thread

The problem is simple, and the-XSS parameter is used to control the stack size of the thread. You can view a list of JVM configurations to learn more about this parameter.

What is the difference between synchronized and Reentrantlock in Java?

Java has had some drawbacks in the past for a long time only through the Synchronized keyword to achieve mutual exclusion. For example, you cannot extend a method or block boundary outside of a lock, and you cannot cancel it while trying to acquire a lock. Java 5 provides more complex control through the lock interface to address these issues. The Reentrantlock class implements Lock, which has the same concurrency and memory semantics as synchronized, and it also has extensibility. You can view this article to learn more

33) There are three threads t1,t2,t3, how to ensure that they are executed sequentially?

There are several ways to get threads to execute in a particular order in multiple threads, and you can use the join () method of the thread class to start another thread in one thread, and another thread to finish the thread. In order to ensure the order of three threads you should start the last one (T3 call t2,t2 call T1) so T1 will be completed first and T3 finalized. You can view this article to learn more.

How does the yield method in the thread class work?

The yield method can pause the currently executing thread object, allowing other threads with the same priority to execute. It is a static method and only guarantees that the current thread abandons the CPU and does not guarantee that other threads will be able to occupy the CPU, and that the thread executing yield () is likely to be executed immediately after entering the paused state. Click here to find out more about the yield method.

What is the concurrency level of concurrenthashmap in Java?

Concurrenthashmap the actual map into several parts to achieve its extensibility and thread safety. This partitioning is obtained using concurrency, which is an optional parameter to the Concurrenthashmap class constructor, with a default value of 16, which avoids contention in multithreaded situations. For more concurrency and internal resizing please read my article how Concurrenthashmap works in Java.

What is semaphore in Java?

Semaphore in Java is a new synchronization class, which is a counting signal. Conceptually, the semaphore maintains a set of permissions in a conceptual sense. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, semaphore only counts the number of available licenses and takes action accordingly. Semaphores are often used in multithreaded code, such as database connection pooling. For more details, please click here.

37) If you submit a task, the thread pool queue is full. What will happen when the meeting is made?

This question is tricky to ask, and many programmers think the task will block until the thread pool queue is empty. In fact, if a task cannot be scheduled to execute, then the Threadpoolexecutor's submit () method throws a Rejectedexecutionexception exception.

) What is the difference between the submit () and execute () methods in the Java thread pool?

Two methods can submit a task to the thread pool, the return type of the Execute () method is void, it is defined in the executor interface, and the Submit () method can return a future object holding the result of the calculation, which is defined in the Executorservice interface. It extends the executor interface, and other thread pool classes like Threadpoolexecutor and Scheduledthreadpoolexecutor have these methods. For more details, please click here.

39) What is a blocking method?

The blocking method means that the program waits for the method to complete without doing anything else, and the ServerSocket accept () method is to wait for the client to connect. The blocking here means that the current thread is suspended until the result of the call returns, until the results are returned. In addition, there are asynchronous and non-blocking methods that are returned before the task is completed. For more details, please click here.

) is swing thread-safe? Why?

You can be sure to answer that swing is not thread-safe, but you should explain the reason for the answer even if the interviewer doesn't ask you why. When we say that swing is not thread-safe and often mentions its components, which cannot be modified in multiple threads, all updates to GUI components are done in the AWT thread, and swing provides both synchronous and asynchronous callback methods to update. Click here to see more about swing and thread safety.

What is the difference between invokeandwait and Invokelater in Java?

These two methods are provided by the swing API to Java developers to update GUI components from the current thread instead of the event dispatch thread. Invokeandwait () updates the GUI component synchronously, such as a progress bar, and once the progress is updated, the progress bar is changed accordingly. If the progress is tracked by multiple threads, call the Invokeandwait () method to request the event dispatch thread to update the component accordingly. The Invokelater () method is called to update the component asynchronously. For more details, please click here.

How are those methods in the Swing API thread-safe?

This issue also mentions swing and thread safety, although the components are not thread-safe but there are methods that can be safely called by multithreading, such as repaint (), revalidate (). JTextComponent's SetText () method and JTextArea's insert () and append () methods are also thread-safe.

43) How do I create a immutable object in Java?

This problem does not seem to have anything to do with multithreading, but immutability helps to simplify already complex concurrent programs. The immutable object can be shared without synchronization, reducing the synchronization overhead when concurrent access is made to the object. However, Java does not @immutable this annotation, to create an immutable class, to implement the following steps: By constructing a method to initialize all members, do not provide setter methods to variables, declare all members as private, so that directly access to these members, in the Getter method , do not directly return the object itself, but instead clone the object and return a copy of the object. My article how to makes an object immutable in Java has a detailed tutorial that you can confidently read through.

What is Readwritelock in Java?

Generally speaking, read-write locks are the result of lock separation techniques used to improve concurrent program performance. Readwritelock in Java is a new interface in Java 5, a readwritelock maintains a pair of associated locks, one for read-only operations and one for writing. In the absence of a write thread, a read lock may be held by multiple read threads at the same time. Write locks are exclusive, and you can use the Reentrantreadwritelock in the JDK to implement this rule, which supports up to 65,535 write locks and 65,535 read locks.

45) What is a busy loop in multi-threading?

A busy loop is when a programmer uses a loop to wait for a thread, unlike the traditional method wait (), sleep () or yield (), which discards CPU control, and the busy loop does not abandon the CPU, it is running an empty loop. The purpose of this is to preserve the CPU cache, in which a waiting thread wakes up in a multi-core system and may run in another kernel, which rebuilds the cache. It can be used to avoid rebuilding the cache and reducing the time it takes to wait for a rebuild. You can check this article for more information.

What is the difference between a volatile variable and a atomic variable?

This is an interesting question. First, the volatile variable and the atomic variable look alike, but the function is different. Volatile variables ensure that the antecedent relationship, that is, the write operation occurs before subsequent reads, but it does not guarantee atomicity. For example, if you modify the count variable with volatile, then the count++ operation is not atomic. The atomic method provided by the Atomicinteger class allows this operation to be atomic, such as the Getandincrement () method, which atomically increments the current value by one, and other data types and reference variables can be similarly manipulated.

47) What happens if a thread inside a synchronization block throws an exception?

This problem is a lot of Java programmers, if you can think of whether the lock release this clue to answer still a little hope to correct. Regardless of whether your synchronization block is normal or abnormal exit, the thread inside will release the lock, so the contrast lock interface I prefer the synchronization block, because it does not need me to expend the effort to release the lock, this function can release the lock implementation in the finally block.

48) What is the double check lock of the single case mode?

This question is often asked in a Java interview, but the interviewer's satisfaction with answering the question is only 50%. Half of the people can't write double check lock and half of the people can't tell the hidden trouble and how the Java1.5 fix it. It's actually an old way to create a thread-safe singleton, and when the singleton instance is first created it tries to optimize performance with a single lock, but because it's too complicated in JDK1.4 it's a failure, and I don't like it personally. Anyway, even if you don't like it, you need to know it, because it's often asked. You can see how double checked locking on Singleton works this article for more information.

49) How do I create a thread-safe singleton in Java?

This is the follow-up to the question above, and if you don't like double lock and the interviewer asks for an alternative to creating the Singleton class, you can use the JVM's class-Loading and static-variable initialization features to create singleton instances, or use enumeration types to create Singleton, I like to use this method very much. You can check this article for more information.

50) write out 3 multithreading best practices that you follow

I like the problem best, and I'm sure you'll follow some best practices when writing concurrency code to improve performance. The following three best practices I think most Java programmers should follow:

Give your thread a meaningful name.

This makes it easy to find bugs or tracks. Orderprocessor, quoteprocessor or tradeprocessor this name than Thread-1. Thread-2 and Thread-3 are much better, give the thread a name related to the task it is going to accomplish, and all the main frameworks and even the JDK follow this best practice.

Avoid locking and narrowing the range of synchronizations

Lock costs are expensive and context switches are more time-consuming, try to minimize the use of synchronization and locks, and narrow the critical section. So I prefer the sync block to the synchronization method, which gives me absolute control over the lock.

Multi-use sync class less wait and notify

First, Countdownlatch, Semaphore, Cyclicbarrier, and Exchanger, these synchronization classes simplify coding operations, and it is difficult to control complex control flows with wait and notify. Second, these classes are written and maintained by the best companies in the subsequent JDK and they will continue to be optimized and perfected, using these higher-level synchronization tools your program can effortlessly get optimized.

Multiple concurrent collections with less synchronous collections

This is another best practice that is easy to follow and benefit enormously, and concurrent collections are more extensible than synchronous collections, so it is better to use concurrent collections in concurrent programming. If you need to use map next time, you should first think of using Concurrenthashmap. My article Java Concurrency collection is described in more detail.

51) How do I force a thread to start?

This problem is like how to enforce Java garbage collection, and there is no way to think about it, although you can use System.GC () to do garbage collection, but it is not guaranteed to succeed. There is no way to force a thread to start in Java, which is controlled by the thread scheduler and Java does not advertise the associated API.

What is the fork join framework in Java?

The fork join framework is an efficient tool in JDK7 that allows Java developers to take full advantage of multiprocessor on modern servers. It is designed specifically for those that can be recursively partitioned into many sub-modules, with the aim of using all available processing power to enhance the performance of the program. A huge advantage of the fork join framework is that it uses a work-stealing algorithm that can be executed by a worker thread that is able to perform more tasks from other threads. You can check this article for more information.

What is the difference between calling the wait () and sleep () methods in Java Multi-threading?

Wait and sleep in Java programs cause some form of pause, which can meet different needs. The wait () method is used for inter-thread communication, and if the wait condition is true and other threads are awakened, it releases the lock, and the sleep () method simply frees the CPU resources or causes the current thread to stop executing for a period of time, but does not release the lock. You can check this article for more information.

A little hot Java multithreading and concurrent interview questions, not sharing the answers to all the questions but giving prospective readers enough hints and clues to find answers. This article can be used not only to prepare interviews, but also to check your understanding of threading issues such as multithreading, concurrency, design patterns and race conditions, deadlocks, and thread Cheng. If you really can not find the answer to a question, do not know the friend may add me Q, or add group number to study together, we learn to share video programming, hope to help like Java friends. If you need any help, you can contact me.

Java Threads (iii)

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.