This is the 29th day of my participation in the August Wenwen Challenge.More challenges in August

Let’s start with singletons

  • The singleton pattern is a well-known design pattern that has been used by spring and other frameworks
    • There are many advantages, such as:
    1. Do not frequently create objects, save the consumption of new, reduce the system overhead
    2. Reduces the GC stress and reduces the GC pause time
Public class Sinleton {private Singleton() {system.out.println ("Singleton is Creating"); } private static Singleton instance = new instance; public static Singleton getInstance() { return instance; }}Copy the code
  • There are a few things to note
    1. Instance objects must be private and declared static, which, if parallel, results in instance being null
    2. Does the getInstance() method not have to be called after the initial creation

Of course, everyone is the partner of the double check lock 🔐

Parallel situation

  • In parallel cases, reading is rarely a problem, and writing is often a problem
  • However, in order to ensure the consistency and correctness of data, synchronization must be carried out, but synchronization will consume the performance of the system
    • So we want to improve the performance of parallel programs, can make dependent object invariance

Let’s look at a classic multithreaded producer-consumer case

  • Producer: Used to submit a user’s request
  • Consumer: Retrieves and processes tasks in the memory buffer
  • Memory buffer: Caches data submitted by producers for consumption by consumers

  • The above code is an implementation of the producer thread, creating the AData and placing it into a queue (buffer)

  • The above code fetches the AData object from the BlockingQueue queue for the consumer

  • Entity classes as data or tasks

  • Create three producers and three consumers and make them write to run the main functionLinkedBlockingDequeforBlockingDequeThe implementation of the class

conclusion

  • Because of the buffer, the system performance can be alleviated to a certain extent

In the next section, let’s look at producer consumers in lockless mode