Monday, September 10, 2018

How Multithreading works in Java


1.     Handling Threads in Java


• Each thread created / executed by a Java program is represented in Java by an instance of the Thread class.
• A thread executes the code received at the time of instantiation through an instance of the Runnable class.
• A thread starts by calling its method start ().
If you do not need to use the same executable multiple times in different threads, you can reduce the code as follows:
Someone is used to not using the executable class, but to create a subclass of thread by changing the code to run (). Personally, I do not recommend it. Keep in mind that the inheritance request must replace certain behaviors and this is not the case.
Keep in mind that every Java run is always generated in a main thread, even if you do not explicitly implement it. Use the static method of the currentThread () thread class to get the reference to this main thread.
Topics What you need most:
• start () causes the thread to execute. Java Virtual Machine calls the execution method of this thread
• run () If the thread was created with a separate runnable object, the executable method of that runnable object is called. Otherwise, this method does nothing and returns nothing (unless you have changed the threadclass execution method as recommended before you did).
• interrupt (): interrupts the thread; When this method is called on a thread, an InterruptedException exception is thrown if methods such as wait (), join (), sleep ()) are expected. Remember that stopping does not mean deleting the thread, but sending an "interrupt signal" to the execution code. What happens depends on the implementation of Thread.run () and then Runnable.run (), especially if an interrupt error occurs.
• interrupted (): tests whether the thread has been interrupted. The suspended status of the thread is deleted using this method. In other words, if this method were called twice in succession, the second call would return false (unless the current thread is aborted again after the first call aborts its interrupted state and before the second call. Appeal was considered). ,
• isInterrupted (): Same behavior as interrupt (), but the suspended state of the thread is not affected
• yield (): gives the scheduler an indication that the current thread can use its current processor. Use this feature in your CPU-intensive code to avoid inconsistencies in non-preventive operating systems (more about the preemptible operating system)
• join (): Waits for the end of the thread, breaks the thread that ran the join () method, and restarts it when the target thread stops.
• setPriority (): Change the priority of the thread (more information)
• getState (): returns the status of the thread (do not use for synchronization purposes)

2. How to manage asynchrony in Java

Synchronized keyword


Multithreading leads to asynchronous code execution, which can cause inconsistencies. To avoid malicious behavior, it is sometimes necessary to run the code in sync: this means that other segments that access the same data structure or call the same method must wait for each other.
The key to synchronization is the concept of the monitor. A monitor is an object that is used as a mutually exclusive block. Once a thread blocks a monitor, other threads competing for that monitor must wait for unlocking.
Every Java object (every instance of a class) has its own monitor.
You can lock and unlock the monitor as follows:
• Invoke a synchronized method: Blocks the monitor of the called method object
• Call any method of a synchronized object: This blocks the monitor of the called method
• Inserting a code from a synchronized section: Blocks the monitor of the passed object as a parameter of the synchronized block
Only use synchronized classes / methods / sequences when absolutely necessary, as excessive synchronization can lead to very long execution times.

Threads direct communication

wait (): The subject falls asleep waiting for someone to wake him up. Remember that the wait () method can generate an InterruptedException. Therefore, you should always prepare for it.

notify (): Enables one of the aforementioned wait () segments of the same object named notify ().

notifyAll (): same asnotify (), but wakes up all outstanding threads
These methods are available for every object in Java. Therefore, entering "myObject.wait ()" is always allowed for each object type.
If these methods are called without an explicit object, as in the following example, this means that the object considered to be called is XXX.

Attention: Sometimes a thread is activated by the operating system, although no notification was sent, it is always better to check the activation condition before starting the execution of the agreed string. (and possibly reactivate it) wait).

Problems with JVM Cache — Important!

The Java Virtual Machine is used to cache object instances for each sub-process and is updated without a strict procedure. This can lead to inconsistencies: A method that reads a variable from an object can not read the latest version, but its version is cached.
Therefore, even read-only applications require some precautions .

There are two ways to force the JVM to update the cache values:

• Execute the read operation in a synchronized sequence (if a monitor is locked to update the strength of the JVM in the chaining cache).
• declare the variable as volatile (volatile forces of the JVM to use the values ​​in main memory and not the cache)

3. Advanced handling of the concurrency

For the advanced handling of simultaneity in Java, it is better to consult the official reference of Competition Utilities, which is suggested in nativ: java.util.concurrent
The above explanation is an introduction to Simultaneity in Java. If you need to develop a real application, it is best to first learn what java.util.concurrent offers and perhaps a complete professional framework.



No comments:

Post a Comment

From Java 8 to Java 11

Switching from Java 8 to Java 11 is more complicated than most updates. Here are some of my notes on the process. Modules Java 9 i...