Java Network Programming thread

Source: Internet
Author: User

Threading Action

When a server requires a large number of concurrent connections, it is common to use lightweight threads to handle a large number of connections, rather than heavyweight processes. threads are more lenient on resource use because they share memory. By using threads instead of processes, you can increase your server performance by up to three times times. In combination with a reusable thread pool , the server can run as much as 9 times times faster with the same hardware and network connections! Designing with multithreading is easier, and you can break up your programs into multiple threads and perform separate operations separately.

Because modern virtual machines and operating system threads can provide high performance, and building a thread-based server is relatively straightforward, you always start with a thread-based design in mind. If you do get into trouble, consider factoring your application into multiple redundant servers instead of relying on a 3 times-fold performance boost on a single server.

Running Threads

Here are two ways to run a thread:

    1. Derives subclasses of the thread class, overriding its run() methods.
    2. Implement the Runnable interface, write the run method, and pass the Runnable object to the thread constructor.

Whichever method is used, the key is the run() method:

    publicvoidrun()

You should put the work that the thread has to do in this method, and the thread will start here and end here.

  1. multithreaded programs main() exit when the method and all non-daemon threads (Nondaemon thread) are returned (non-daemon threads are background threads that complete background tasks).
  2. The runnable interface is not necessarily superior to inheriting the thread class. Some of the methods of calling the thread class in the subclass constructor of the thread class can be useful. When inheriting other classes, you need to use the Runnable interface.
  3. Some advocates of object-oriented think that a thread-accomplished task is not actually a thread, so it should be placed in a separate class or interface (such as runnable) rather than a subclass of thread. The author partly agrees with this view, but does not think that the argument is as good as it claims.
  4. Try not to start the thread in the constructor, otherwise a race condition may occur. A new thread may be allowed to make a callback before the constructor ends and the object is fully initialized.
Callback

A simple and effective method is to have the thread tell the main program when it ends, which is done by invoking a method in the main class (that is, the class that started the thread), which is called a callback . In this way, the main program can rest during the waiting thread's end without taking up the time of the running thread.
Here are two common practices:

    1. Invokes the static method of the main class.
    2. Use an instance method of the main class.

Using instance methods is a bit more complicated, but there are many advantages. It allows each thread to track a main class object without the need for additional data structures.

Synchronous

Because different threads share the same memory, one thread is completely likely to break the data structure of the variables used by another thread, and synchronization is required to solve the problem.

Synchronization block

Encloses an object lock in the synchronized block, which synchronizes the object. Synchronization requires that all code that is synchronized on the same object be run continuously, and not run in parallel.
Example:

synchronized(System.out){    //同步连续过程}
Synchronization method

Because it is common to synchronize the entire method body with the object itself, Java provides a shortcut for this. Synchronizes the entire method with the current object (this reference).

publicsynchronizedvoidfun() {    //同步连续过程}

But the synchronization method is not omnipotent:

    1. The synchronization method can cause a significant decrease in VM performance (although the latest VMS have been greatly improved).
    2. Greatly increases the possibility of deadlocks.
    3. Not always the object itself needs to be prevented from being modified or accessed at the same time, and it is important to be aware of which objects are locked.
Alternate ways to synchronize

The behavior caused by thread scheduling is inconsistent, but in fact synchronization is not always the best solution for this problem.

    • Use local variables instead of fields. There is no synchronization problem with local variables.
    • A basic type of method can also be safely modified in a separate thread because Java passes the base type object by value rather than by reference.
    • Immutable objects never change state.
    • Constructors generally do not need to worry about thread-safety issues. No thread has a reference to this object until the constructor returns, so it is not possible for two threads to have a reference to the object. (but not equal to the constructor start thread, no race condition occurs.) )
    • Use immutability in your class to declare all of its fields as private and final, and do not write any methods that might change them.
    • Use a non-thread-safe class as a private field for thread-safe classes. This class is safe as long as the containing class accesses the non-secure class only in a thread-safe manner and never lets the private field's reference leak into another object.
    • For basic data types, classes that are deliberately designed to ensure thread-safe but mutable are used in the Java.util.concurrent.atomic package. However, it is necessary to note that this does not make the object itself thread-safe, except that the reference variable gets and sets are thread-safe.
    • For collections such as mappings and lists, use the Java.util.Collections method to wrap them in a thread-safe version.

But these are just a single atomic method call, and if you need to do two more operations as an atom, the middle cannot have interrupts, you need to synchronize.

Dead lock

It is also possible that two threads are too careful, and each thread waits for exclusive access to the other's resources, but will never get it, which can lead to deadlocks.

    • Synchronization should ensure that the last line of defense is thread-safe. If you do need synchronization, keep the synchronization block as small as possible and try not to synchronize multiple objects at once.
    • If multiple objects need to manipulate the same set of shared resources, be sure to request them in the same order.
Thread Scheduling Priority

In Java, 10 is the highest priority, and 0 is the lowest priority.

Unix In contrast, 0 is the highest level and 10 is the lowest. While Windows has only 7 priorities, 1, 2, 3, and 8, 9 are assigned to two equal priorities.

The priority of the thread can be used setPriority() to change.

Seize

Each virtual machine has a thread scheduler that determines which thread to run at a given moment. There are two main types of thread scheduling: preemptive (preemptive) and Cooperative (cooperative).

The following are different ways to let a thread pause or prepare to pause:

Blocking

Any time a thread must stop waiting for a resource that it does not have, the block will occur. Even if you block for a few milliseconds, this is enough time for other threads to perform important tasks.

Give

An explicit discard can be done by invoking a Thread.yield() static method.

Discarding does not release locks owned by this thread. Therefore, in an ideal situation, no synchronization should be done when the thread discards.

Dormancy

Sleep is a more powerful way to give up. The dormant thread pauses regardless of whether any other thread is ready to run. In this way, not only the other threads with the same priority are given the opportunity, but also the lower-priority threads are given a chance to run.

By calling one of the two overloaded Thread.sleep() static methods, a thread can go into hibernation.

To wake a dormant thread, it can be implemented by means of a dormant thread, which interrupt() causes the thread in hibernation to get a interruptedexception exception.

Connecting Threads

Java provides three join() methods that allow one thread to wait for another thread to end before it continues execution. Similarly, the thread of another thread that is connected can be interrupted and can be invoked by means of the thread interrupt() to implement it, which will get a interruptedexception exception.

Today, the connection thread may not be as important as it was before Java5. In particular, many join() of the designs that were originally needed are now easier to implement with executor and future.

Wait for an object

A thread can wait for an object that it locks. The thread that you want to pause must first use syschronized to obtain the object for this lock, and then call one of the three overloaded methods of this object wait() .

The thread stays dormant until one of the following three cases occurs

    • Timeout. However, if a thread cannot immediately regain the lock on the object it is waiting for, it may still be blocked for some time.
    • Interrupt. Invokes a interrupt() method. However, the thread that throws the exception is going to regain the lock of the waiting object, so after the call, the threads may still have to block for a while.
    • Notice. Notification occurs when the thread waits for the object mountain to notify() be called or notifyAll() to occur. notify()basically randomly selects a thread from the list of threads waiting for this object and wakes it up. notifyAll()method wakes each thread that waits for a specified object. If successful, continue execution. If it fails, it blocks the object until it can get the lock, and then continues execution.

      Do not assume that the object is now in the correct state because the thread has been notified. To ensure that an object enters the correct state, it will never enter an incorrect state, and if this is not guaranteed, it is explicitly checked, and the wait () call is generally placed in a loop that checks the current state object.

End

When the run() method returns, the thread is revoked and other threads can take over the CPU.

Thread pool

If the concurrent threads reach 4000 to 20000, most Java virtual machines may not be able to withstand memory exhaustion. However, by using a thread pool instead of generating a new process for each connection, the server can handle thousands of short connections per minute with less than 100 threads.

With the Excutor class, you simply submit each task as a Runnable object to the thread pool, and you get a future object that you can use to check the progress of the task.

    • Executors.ewFixedThreadPool()The call can create a fixed number of thread pools.
    • Called submit() to submit a thread task.
    • Called shutdown() , does not terminate the waiting work, just notifies the thread pool that no more tasks need to be added to its internal queue. And once all the waiting work is done, it should be closed.
    • Called shutdownNow() , terminates the task in the current process, and ignores all waiting tasks.
Excutor and callbacks

Java5 references a new method of multithreaded programming that makes it easier to handle callbacks.
Instead of creating a thread directly, you create a excutorservice that creates a thread for you based on the number of fixed threads you need (in fact, creates a thread pool), and you can submit callable tasks to Executorservice. Each callable task is given a future. The result of the task can then be requested from the future. If the task is ready, the result is immediately available. If it is not ready, the rotation thread blocks until the result is ready and returns the result.

Example:

    ExecutorService service = Executors.newFixedThreadPool(2)。    Future<Integer> future1 = service.submit(task1);    Future<Integer> future2 = service.submit(task2);    return Math.max(future1.get(), future2.get());

Java Network Programming thread

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.