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
$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.
java multithreading concurrency producer-consumer
New contributor
$endgroup$
add a comment |
$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.
java multithreading concurrency producer-consumer
New contributor
$endgroup$
$begingroup$
Welcome to Code Review! I find a name likereadCountSempaphote
unsettling. Using a (java.util.concurrent.
?)Semaphore
around a (…atomic
?)AtomicInteger
looks belt and braces.
$endgroup$
– greybeard
57 mins ago
add a comment |
$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.
java multithreading concurrency producer-consumer
New contributor
$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
java multithreading concurrency producer-consumer
New contributor
New contributor
edited 8 mins ago
Jamal♦
30.5k11121227
30.5k11121227
New contributor
asked 3 hours ago
Oscar Besga PanelOscar Besga Panel
1
1
New contributor
New contributor
$begingroup$
Welcome to Code Review! I find a name likereadCountSempaphote
unsettling. Using a (java.util.concurrent.
?)Semaphore
around a (…atomic
?)AtomicInteger
looks belt and braces.
$endgroup$
– greybeard
57 mins ago
add a comment |
$begingroup$
Welcome to Code Review! I find a name likereadCountSempaphote
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
add a comment |
0
active
oldest
votes
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
$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