Many-readers-one-writer with semaphores and multithreading The Next CEO of Stack OverflowReader-writers problem using semaphores in JavaMultithreading concepts with Producer ConsumerIn-memory cache implementation revisitedMultithreading synchronization between reading and writing in a channelParsing log files of HearthStone: The log reading APISimultaneous works with multithreadingMessage queue with multiple producer, single consumer and no duplicatesOne producer and multiple consumers wherein the producer has to wait until all consumers finish before adding more dataQueue with multiple consumers and one producerReadWriteSerializerRequesting 400 links with multithreading and ThreadPool

Does destroying a Lich's phylactery destroy the soul within it?

What difference does it make using sed with/without whitespaces?

Is it ok to trim down a tube patch?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

In the "Harry Potter and the Order of the Phoenix" video game, what potion is used to sabotage Umbridge's speakers?

What day is it again?

Expectation in a stochastic differential equation

Film where the government was corrupt with aliens, people sent to kill aliens are given rigged visors not showing the right aliens

(How) Could a medieval fantasy world survive a magic-induced "nuclear winter"?

How to avoid supervisors with prejudiced views?

Expressing the idea of having a very busy time

Where do students learn to solve polynomial equations these days?

Is it correct to say moon starry nights?

How to get the last not-null value in an ordered column of a huge table?

Which one is the true statement?

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

What connection does MS Office have to Netscape Navigator?

How to find image of a complex function with given constraints?

Can this note be analyzed as a non-chord tone?

Is French Guiana a (hard) EU border?

Can Sneak Attack be used when hitting with an improvised weapon?

What would be the main consequences for a country leaving the WTO?

What is the difference between "hamstring tendon" and "common hamstring tendon"?



Many-readers-one-writer with semaphores and multithreading



The Next CEO of Stack OverflowReader-writers problem using semaphores in JavaMultithreading concepts with Producer ConsumerIn-memory cache implementation revisitedMultithreading synchronization between reading and writing in a channelParsing log files of HearthStone: The log reading APISimultaneous works with multithreadingMessage queue with multiple producer, single consumer and no duplicatesOne producer and multiple consumers wherein the producer has to wait until all consumers finish before adding more dataQueue with multiple consumers and one producerReadWriteSerializerRequesting 400 links with multithreading and ThreadPool










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 that's what I think. I've set up a new GitHub repo to put the code to be used in another project 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 pseudocode 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.










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$











  • $begingroup$
    Welcome to Code Review! I find a name like readCountSempaphote unsettling. Using a (java.util.concurrent.?)Semaphore around a (…atomic?)AtomicInteger looks belt and braces.
    $endgroup$
    – greybeard
    57 mins ago















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 that's what I think. I've set up a new GitHub repo to put the code to be used in another project 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 pseudocode 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.










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$











  • $begingroup$
    Welcome to Code Review! I find a name like readCountSempaphote unsettling. Using a (java.util.concurrent.?)Semaphore around a (…atomic?)AtomicInteger looks belt and braces.
    $endgroup$
    – greybeard
    57 mins ago













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 that's what I think. I've set up a new GitHub repo to put the code to be used in another project 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 pseudocode 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.










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 that's what I think. I've set up a new GitHub repo to put the code to be used in another project 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 pseudocode 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.







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








edited 8 mins ago









Jamal

30.5k11121227




30.5k11121227






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 3 hours 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.











  • $begingroup$
    Welcome to Code Review! I find a name like readCountSempaphote unsettling. Using a (java.util.concurrent.?)Semaphore around a (…atomic?)AtomicInteger looks belt and braces.
    $endgroup$
    – greybeard
    57 mins ago
















  • $begingroup$
    Welcome to Code Review! I find a name like readCountSempaphote unsettling. Using a (java.util.concurrent.?)Semaphore around a (…atomic?)AtomicInteger looks belt and braces.
    $endgroup$
    – greybeard
    57 mins ago















$begingroup$
Welcome to Code Review! I find a name like readCountSempaphote unsettling. Using a (java.util.concurrent.?)Semaphore around a (…atomic?)AtomicInteger looks belt and braces.
$endgroup$
– greybeard
57 mins ago




$begingroup$
Welcome to Code Review! I find a name like readCountSempaphote unsettling. Using a (java.util.concurrent.?)Semaphore around a (…atomic?)AtomicInteger looks belt and braces.
$endgroup$
– greybeard
57 mins ago










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%2fmany-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%2fmany-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

名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar