Java Many Readers One Writer with semaphores and multithreading












0












$begingroup$


I've been looking for a solution to the may readers one writer in Java.
I was intrigued by this question posted here and I read the wikipedia entry about it.



So far, I've reached a fine solution, or at least thats what I think.
I've setup a new github repo to put the code to be used in another proyects if people want



But I'm open to improvements and critics if you see fit



The pseudocode of the main class is here



abstract class AbsrtactReadersWriter<T> {

Semaphore readCountSempaphote = new Semaphore(1);
Semaphore resourceSemaphore = new Semaphore(1, true);
Semaphore serviceQueueSemaphore = new Semaphore(1,true);
AtomicInteger readCount = new AtomicInteger(0);


public final T read() {
T data = null;
try {
// Entry to read
serviceQueueSemaphore.acquire();
readCountSempaphote.acquire();
if (readCount.incrementAndGet() == 1){
resourceSemaphore.acquire();
}
serviceQueueSemaphore.release();
readCountSempaphote.release();
// CRITICAL SECTION Do read
data = executeReading();
// Exit to read
readCountSempaphote.acquire();
if (readCount.decrementAndGet() == 0){
resourceSemaphore.release();
}
readCountSempaphote.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
return data;
}

// Protected critical section that read the resource
abstract protected T executeReading();


public final void write(T data) {
try {
// Entry write
serviceQueueSemaphore.acquire();
resourceSemaphore.acquire();
serviceQueueSemaphore.release();
// CRITICAL SECTION Do Write
executeWriting(data);
// Exit write
resourceSemaphore.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}

// Protected critical section that writes to the resource
abstract protected void executeWriting(T data);

}


This pseucode lacks some elements (privates, comments) form the class on the github repo, but hits the point.



In the repo, you can also see examples and tests.



The starvation problem on readers/writer is solved by Java itself, as the semaphores are created with the fair parameter, that forces the fairness of the blocking and a fifo queue on the waiting threads.
I use an AtomicInteger to store the readcount, even it's protected; the equality operation maybe not and doesn't impose a great penalty



So, guys, what do you think ?










share|improve this question







New contributor




Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    I've been looking for a solution to the may readers one writer in Java.
    I was intrigued by this question posted here and I read the wikipedia entry about it.



    So far, I've reached a fine solution, or at least thats what I think.
    I've setup a new github repo to put the code to be used in another proyects if people want



    But I'm open to improvements and critics if you see fit



    The pseudocode of the main class is here



    abstract class AbsrtactReadersWriter<T> {

    Semaphore readCountSempaphote = new Semaphore(1);
    Semaphore resourceSemaphore = new Semaphore(1, true);
    Semaphore serviceQueueSemaphore = new Semaphore(1,true);
    AtomicInteger readCount = new AtomicInteger(0);


    public final T read() {
    T data = null;
    try {
    // Entry to read
    serviceQueueSemaphore.acquire();
    readCountSempaphote.acquire();
    if (readCount.incrementAndGet() == 1){
    resourceSemaphore.acquire();
    }
    serviceQueueSemaphore.release();
    readCountSempaphote.release();
    // CRITICAL SECTION Do read
    data = executeReading();
    // Exit to read
    readCountSempaphote.acquire();
    if (readCount.decrementAndGet() == 0){
    resourceSemaphore.release();
    }
    readCountSempaphote.release();
    } catch (InterruptedException e) {
    System.out.println(e.getMessage());
    }
    return data;
    }

    // Protected critical section that read the resource
    abstract protected T executeReading();


    public final void write(T data) {
    try {
    // Entry write
    serviceQueueSemaphore.acquire();
    resourceSemaphore.acquire();
    serviceQueueSemaphore.release();
    // CRITICAL SECTION Do Write
    executeWriting(data);
    // Exit write
    resourceSemaphore.release();
    } catch (InterruptedException e) {
    System.out.println(e.getMessage());
    }
    }

    // Protected critical section that writes to the resource
    abstract protected void executeWriting(T data);

    }


    This pseucode lacks some elements (privates, comments) form the class on the github repo, but hits the point.



    In the repo, you can also see examples and tests.



    The starvation problem on readers/writer is solved by Java itself, as the semaphores are created with the fair parameter, that forces the fairness of the blocking and a fifo queue on the waiting threads.
    I use an AtomicInteger to store the readcount, even it's protected; the equality operation maybe not and doesn't impose a great penalty



    So, guys, what do you think ?










    share|improve this question







    New contributor




    Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      I've been looking for a solution to the may readers one writer in Java.
      I was intrigued by this question posted here and I read the wikipedia entry about it.



      So far, I've reached a fine solution, or at least thats what I think.
      I've setup a new github repo to put the code to be used in another proyects if people want



      But I'm open to improvements and critics if you see fit



      The pseudocode of the main class is here



      abstract class AbsrtactReadersWriter<T> {

      Semaphore readCountSempaphote = new Semaphore(1);
      Semaphore resourceSemaphore = new Semaphore(1, true);
      Semaphore serviceQueueSemaphore = new Semaphore(1,true);
      AtomicInteger readCount = new AtomicInteger(0);


      public final T read() {
      T data = null;
      try {
      // Entry to read
      serviceQueueSemaphore.acquire();
      readCountSempaphote.acquire();
      if (readCount.incrementAndGet() == 1){
      resourceSemaphore.acquire();
      }
      serviceQueueSemaphore.release();
      readCountSempaphote.release();
      // CRITICAL SECTION Do read
      data = executeReading();
      // Exit to read
      readCountSempaphote.acquire();
      if (readCount.decrementAndGet() == 0){
      resourceSemaphore.release();
      }
      readCountSempaphote.release();
      } catch (InterruptedException e) {
      System.out.println(e.getMessage());
      }
      return data;
      }

      // Protected critical section that read the resource
      abstract protected T executeReading();


      public final void write(T data) {
      try {
      // Entry write
      serviceQueueSemaphore.acquire();
      resourceSemaphore.acquire();
      serviceQueueSemaphore.release();
      // CRITICAL SECTION Do Write
      executeWriting(data);
      // Exit write
      resourceSemaphore.release();
      } catch (InterruptedException e) {
      System.out.println(e.getMessage());
      }
      }

      // Protected critical section that writes to the resource
      abstract protected void executeWriting(T data);

      }


      This pseucode lacks some elements (privates, comments) form the class on the github repo, but hits the point.



      In the repo, you can also see examples and tests.



      The starvation problem on readers/writer is solved by Java itself, as the semaphores are created with the fair parameter, that forces the fairness of the blocking and a fifo queue on the waiting threads.
      I use an AtomicInteger to store the readcount, even it's protected; the equality operation maybe not and doesn't impose a great penalty



      So, guys, what do you think ?










      share|improve this question







      New contributor




      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I've been looking for a solution to the may readers one writer in Java.
      I was intrigued by this question posted here and I read the wikipedia entry about it.



      So far, I've reached a fine solution, or at least thats what I think.
      I've setup a new github repo to put the code to be used in another proyects if people want



      But I'm open to improvements and critics if you see fit



      The pseudocode of the main class is here



      abstract class AbsrtactReadersWriter<T> {

      Semaphore readCountSempaphote = new Semaphore(1);
      Semaphore resourceSemaphore = new Semaphore(1, true);
      Semaphore serviceQueueSemaphore = new Semaphore(1,true);
      AtomicInteger readCount = new AtomicInteger(0);


      public final T read() {
      T data = null;
      try {
      // Entry to read
      serviceQueueSemaphore.acquire();
      readCountSempaphote.acquire();
      if (readCount.incrementAndGet() == 1){
      resourceSemaphore.acquire();
      }
      serviceQueueSemaphore.release();
      readCountSempaphote.release();
      // CRITICAL SECTION Do read
      data = executeReading();
      // Exit to read
      readCountSempaphote.acquire();
      if (readCount.decrementAndGet() == 0){
      resourceSemaphore.release();
      }
      readCountSempaphote.release();
      } catch (InterruptedException e) {
      System.out.println(e.getMessage());
      }
      return data;
      }

      // Protected critical section that read the resource
      abstract protected T executeReading();


      public final void write(T data) {
      try {
      // Entry write
      serviceQueueSemaphore.acquire();
      resourceSemaphore.acquire();
      serviceQueueSemaphore.release();
      // CRITICAL SECTION Do Write
      executeWriting(data);
      // Exit write
      resourceSemaphore.release();
      } catch (InterruptedException e) {
      System.out.println(e.getMessage());
      }
      }

      // Protected critical section that writes to the resource
      abstract protected void executeWriting(T data);

      }


      This pseucode lacks some elements (privates, comments) form the class on the github repo, but hits the point.



      In the repo, you can also see examples and tests.



      The starvation problem on readers/writer is solved by Java itself, as the semaphores are created with the fair parameter, that forces the fairness of the blocking and a fifo queue on the waiting threads.
      I use an AtomicInteger to store the readcount, even it's protected; the equality operation maybe not and doesn't impose a great penalty



      So, guys, what do you think ?







      java multithreading concurrency producer-consumer






      share|improve this question







      New contributor




      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 26 mins ago









      Oscar Besga PanelOscar Besga Panel

      1




      1




      New contributor




      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Oscar Besga Panel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes












          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Oscar Besga Panel is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216603%2fjava-many-readers-one-writer-with-semaphores-and-multithreading%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Oscar Besga Panel is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Oscar Besga Panel is a new contributor. Be nice, and check out our Code of Conduct.













          Oscar Besga Panel is a new contributor. Be nice, and check out our Code of Conduct.












          Oscar Besga Panel is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216603%2fjava-many-readers-one-writer-with-semaphores-and-multithreading%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Costa Masnaga

          Fotorealismo

          Sidney Franklin