preface

We have updated several chapters in the series on multithreading, and we strongly recommend that you learn in order:

Squat can also enter the factory “multithreading series article directory

Semaphore is a common tool class in JUC. It is relatively simple to use. The only difficulty is that many people have difficulty understanding what Semaphore is.

What is a semaphore

  • Examples of Life scenes

Our country has a lot of pollution more serious factory, but for economic development, cannot close to its completely again, because this country has a compromise method, each factory needs to environmental protection administrative department to apply for discharge permit. Only licensed factories are allowed to operate legally. However, the annual emission permits are limited in number, and too many factories cannot be allowed to apply for them, otherwise they will not be able to control environmental pollution.

  • Semaphores in Java

In Java, Semaphore is the sewage permit, or Semaphore, above. So when do we use semaphores, for example, if we call a method and it’s a file download or a big data processing operation inside, so it’s very time consuming, and if we don’t limit this method, when we call it through multiple threads at once, it might drag down the whole service, Semaphore is here to limit the number of access threads.

Semaphore core method

Semaphore, like CountDownLatch, internally maintains a core attribute, Sync, which is implemented through AQS ‘shared lock mechanism, as AQS will explain in more detail

private final Sync sync;
Copy the code

Take a look at some of Semaphore’s core approaches:

  • Semaphore (int premits, Boolean fair) :Constructor method.permitsIs the number of semaphore initializations, the second argumentfairYou can set whether a fair policy is required, and if true is passed, thenSemaphoreThe waiting thread is placed in the FIFO queue so that when the license is released, it can be allocated to the thread that has waited the longest.
  • Acquire () : Attempts to acquire a license and enters a blocked wait state if none is currently available;
  • TryAcquire () : Attempts to acquire a license, if it can be obtained or not, it will not be blocked.
  • TryAcquire (long Timeout, TimeUnit Unit) : The same as tryAcquire, but with an extra timeout, wait for a specified time until the license is not obtained, the wait will stop;
  • AvailablePermits: number of availablePermits obtained;
  • Release () : releases a license;
  • Release (int permits) : a specified number of permits is released.

Third, code demonstration

Now create 100 threads, each acquire(1) one semaphore at a time, and initialize the semaphore to 3. Let’s take a look at the code and imagine what the result will be.

public class SemaphoreDemo { static Semaphore semaphore = new Semaphore(3,true); public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(5); for (int i = 0; i < 100; i++) { service.submit(new Runnable() { @Override public void run() { try { semaphore.acquire(1); } catch (InterruptedException e) { e.printStackTrace(); } system.out.println (thread.currentThread ().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } system.out.println (thread.currentThread ().getName()); semaphore.release(); }}); } service.shutdown(); semaphore.tryAcquire(); }}Copy the code

The print result is as follows:

You can clearly see that three threads at a time acquire the semaphore, and only after the semaphore is released can other threads continue to acquire it.

The code process is illustrated as follows:

  • Initialize semaphore license number to 3;
  • Thread 1, thread 2, thread 3 can obtain the license normally, and the location service;
  • Thread 4 is blocked due to insufficient licenses.
  • When thread 1 releases the license, thread 4 uses acqire to access the service normally.

Acquire () : acquire() : acquire() : acquire() : acquire() : acquire() : acquire() : acquire() : acquire() : acquire() : acquire();

Semaphore.acquire (2); semaphore.release(1);Copy the code

The results are as follows:

This is easy to understand because one thread acquires two licenses at a time, but only releases one, so after two rounds the license is not enough to be acquired again by another thread, and the other thread blocks.

Four, notes

  • The number of licenses obtained and released must be the same; otherwise, over time, there will eventually be insufficient licenses and the thread will freeze.
  • SemaphoreWhen setting fairness, it is generally reasonable to set true, because Semaphore is used for long operations, and threads will continue to wait if they are repeatedly queued.
  • To obtainandThe release ofThe license is not required for the same thread, as long as it meets our business needs, can be byA threadGet a license and letThread BTo release.

conclusion

Above is all there is about a Semaphore, overall, usage is simple, combining the actual license of chestnuts in the scene, we will easier to grasp the Semaphore, today is a harvest full day, what should we say in the next chapter, flower elder brother will share with you another interesting knowledge Condition, next time we meet.

Pay attention to avoid getting lost

The above is the whole content of this issue, if there is any mistake, please leave a message for advice, thank you very much. I’m Gie, feel free to leave a comment if you have any questions, and we’ll see you next time at 🦮.

The article continues to update, you can wechat search a search [flower elder brother programming] the first time to read, and you can get interview materials learning video, interested partners welcome to pay attention to, learn together, ha 🐮🥃.

Original is not easy, how can you bear to whoring for nothing, if you think this article is a little useful to you, thank old tie for this article to like, comment or forward, because this will be my output more quality articles of power, thank you!