Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want the <code>ArrayList</code>s to store per-client info and access it by client ID, I suggest just using a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow"><code>java.util.concurrent.ConcurrentHashMap</code></a> with the client ID as key, as that is very straightforward to implement.</p> <p>If you really need an <code>ArrayList</code>, I would hide it as an implementation detail in the server code. Then you would call some server methods from your <code>Runnable</code>s to update the <code>ArrayList</code>. In this way you can start with something very simple like:</p> <pre><code>public class Server { ... private ArrayList&lt;Info&gt; infos = new ArrayList&lt;Info&gt;(); ... // Create one method for each *abstract* operation // that you need to perform on the ArrayList // (Do *NOT* implement read / write primitives // unless that is exactly what you need. The idea is // that all synchronization that you might need on // the ArrayList happens inside those methods, so // the Runnables are unaware of the implementation // you haven chosen.) // Here I have used example operations that are // a bit more complex than read / write primitives // so the intention is more clear. public void clearInfo(int pos) { synchronized (infos) { infos.set(pos, null); } } public Info updateInfo(int pos, Info info) { Info oldInfo = null; synchronized (infos) { oldInfo = infos.get(pos); infos.set(pos, info); } return oldInfo; } ... public Info readInfo(int pos) { Info info = null; synchronized (infos) { infos.get(pos); info.incrementReadCount(); } return null; } ... } ... public class ClientRunnable implements Runnable { ... private Server server; ... @Override public void run() { ... Info info = // getInfo(); int writePos = // getWritePos(); Info old = server.updateInfo(writePos, info); ... int readPos = // getReadPos(); Info newInfo = server.readInfo(readPos); ... } ... } </code></pre> <p>Then, when you profile your application, if you find contention in accesses to your list you can fine tune locking or even change your implementation to a lock-free one while minimizing impact in your code. Locking is quite fast in Java nowadays so in many cases this simple solution might be good enough.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload