List of Semaphores in Java and concurrency

huangapple go评论73阅读模式
英文:

List of Semaphores in Java and concurrency

问题

我有一个应用程序,在我的实现中需要一些信号量。我的问题是,这如何与ArrayList一起使用?

假设我有一个包含多个信号量的ArrayList<Semaphore> semList;,如果我执行semList.get(0).aquire();,信号量是否会在列表中相应地更新 - 换句话说,其他线程是否会知道它已被获取?我不确定,因为ArrayList.get()只获取对象的引用。

英文:

I have an application and in my implementation I need a number of Semaphores. My question is how this works with an ArrayList?

Let's say I have an ArrayList&lt;Semaphore&gt; semList; containing a number of Semaphores, if I do semList.get(0).aquire(); will the Semaphore be updated accordingly in the list - in other words, will other threads know that's it has been aquired? I'm uncertain since ArrayList.get() only gets a reference to the object.

答案1

得分: 1

"will the Semaphore be updated accordingly in the list"?

Think of it this way: the semaphore is not in the list, the list only stores a reference to the semaphore. If another thread calls get(0) it will get a reference to the same semaphore (unless the list has been modified, or there is a data race). So yes, other threads will know that it has been acquired.

If you are modifying the list concurrently then you should use a thread-safe list, but if it is initialized and filled once and then not changed and published safely to the other threads then you would be fine using an ArrayList.

I recommend reading the JLS section on the memory model to help understand it better: JLS 17.4.5

英文:

"will the Semaphore be updated accordingly in the list"?

Think of it this way: the semaphore is not in the list, the list only stores a reference to the semaphore. If another thread calls get(0) it will get a reference to the same semaphore (unless the list has been modified, or there is a data race). So yes, other threads will know that it has been aquired.

If you are modifying the list concurrently then you should use a thread safe list, but if it is initialized and filled once and then not changed and published safely to the other threads then you would be fine using an ArrayList.

I recommend reading the JLS section on the memory model to help understand it better: https://docs.oracle.com/javase/specs/jls/se14/html/jls-17.html#jls-17.4.5

答案2

得分: 1

是的,无论您是直接引用信号量还是通过list.get(0)引用它,信号量都会相应地更新。所有线程都访问同一个实例。假设信号量只剩下一个许可证,那么调用acquire方法的下一个线程将获得最后一个许可证。接下来的线程将等待直到有许可证被释放。

英文:

> will the Semaphore be updated accordingly in the list

Yes, it does not matter whether you reference the semaphore directly or via list.get(0). All threads access the same instance. Assuming the semaphore has one permit left, the next thread that calls the acquire method will get the last permit. The next thread will wait until a permit is released.

huangapple
  • 本文由 发表于 2020年7月28日 01:01:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63120025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定