The difference between read/write locks vs synchronized shown on basic code












0















In my homework I need to show the difference between read/write lock and 'synchronized' key word usage in code. I really don't know how to do it and what is the clear way to understand that difference. I also need to show the time difference between execution of the same task in both ways. Here is code that I tried (without synchronized though)



public class Main {

public static void main(String args) {

Number number = new Number(5);

Thread t1 = new Thread(){
public void run(){
System.out.println(number.getData());
number.changaData(10);
System.out.println(number.getData());
}};
Thread t2 = new Thread(){
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(number.getData());
number.changaData(20);
System.out.println(number.getData());
}};

t2.start();
t1.start();
}
}


public class Number {

private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock readLock = rwl.readLock();
private final Lock writeLock = rwl.writeLock();
int value;

public Number(int value) {
this.value = value;
}

public int getData() {
readLock.lock();
try {
return value;
}
finally {
readLock.unlock();
}
}

public int changaData(int change) {
writeLock.lock();
try {
value = change;
return value;
}
finally {
writeLock.unlock();
}
}
}









share|improve this question

























  • have you tried reading about the subject in "Java concurrency in practice"

    – mehdi maick
    Jan 19 at 14:23
















0















In my homework I need to show the difference between read/write lock and 'synchronized' key word usage in code. I really don't know how to do it and what is the clear way to understand that difference. I also need to show the time difference between execution of the same task in both ways. Here is code that I tried (without synchronized though)



public class Main {

public static void main(String args) {

Number number = new Number(5);

Thread t1 = new Thread(){
public void run(){
System.out.println(number.getData());
number.changaData(10);
System.out.println(number.getData());
}};
Thread t2 = new Thread(){
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(number.getData());
number.changaData(20);
System.out.println(number.getData());
}};

t2.start();
t1.start();
}
}


public class Number {

private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock readLock = rwl.readLock();
private final Lock writeLock = rwl.writeLock();
int value;

public Number(int value) {
this.value = value;
}

public int getData() {
readLock.lock();
try {
return value;
}
finally {
readLock.unlock();
}
}

public int changaData(int change) {
writeLock.lock();
try {
value = change;
return value;
}
finally {
writeLock.unlock();
}
}
}









share|improve this question

























  • have you tried reading about the subject in "Java concurrency in practice"

    – mehdi maick
    Jan 19 at 14:23














0












0








0








In my homework I need to show the difference between read/write lock and 'synchronized' key word usage in code. I really don't know how to do it and what is the clear way to understand that difference. I also need to show the time difference between execution of the same task in both ways. Here is code that I tried (without synchronized though)



public class Main {

public static void main(String args) {

Number number = new Number(5);

Thread t1 = new Thread(){
public void run(){
System.out.println(number.getData());
number.changaData(10);
System.out.println(number.getData());
}};
Thread t2 = new Thread(){
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(number.getData());
number.changaData(20);
System.out.println(number.getData());
}};

t2.start();
t1.start();
}
}


public class Number {

private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock readLock = rwl.readLock();
private final Lock writeLock = rwl.writeLock();
int value;

public Number(int value) {
this.value = value;
}

public int getData() {
readLock.lock();
try {
return value;
}
finally {
readLock.unlock();
}
}

public int changaData(int change) {
writeLock.lock();
try {
value = change;
return value;
}
finally {
writeLock.unlock();
}
}
}









share|improve this question
















In my homework I need to show the difference between read/write lock and 'synchronized' key word usage in code. I really don't know how to do it and what is the clear way to understand that difference. I also need to show the time difference between execution of the same task in both ways. Here is code that I tried (without synchronized though)



public class Main {

public static void main(String args) {

Number number = new Number(5);

Thread t1 = new Thread(){
public void run(){
System.out.println(number.getData());
number.changaData(10);
System.out.println(number.getData());
}};
Thread t2 = new Thread(){
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(number.getData());
number.changaData(20);
System.out.println(number.getData());
}};

t2.start();
t1.start();
}
}


public class Number {

private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock readLock = rwl.readLock();
private final Lock writeLock = rwl.writeLock();
int value;

public Number(int value) {
this.value = value;
}

public int getData() {
readLock.lock();
try {
return value;
}
finally {
readLock.unlock();
}
}

public int changaData(int change) {
writeLock.lock();
try {
value = change;
return value;
}
finally {
writeLock.unlock();
}
}
}






java multithreading locks






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 19 at 14:10









c0der

8,63051744




8,63051744










asked Jan 19 at 14:03









jakubradzikowski97jakubradzikowski97

166




166













  • have you tried reading about the subject in "Java concurrency in practice"

    – mehdi maick
    Jan 19 at 14:23



















  • have you tried reading about the subject in "Java concurrency in practice"

    – mehdi maick
    Jan 19 at 14:23

















have you tried reading about the subject in "Java concurrency in practice"

– mehdi maick
Jan 19 at 14:23





have you tried reading about the subject in "Java concurrency in practice"

– mehdi maick
Jan 19 at 14:23












1 Answer
1






active

oldest

votes


















2














The difference between synchronized and read/write locks is such that when you are using synchronized it allows only one thread at a time to access. With read/write lock you can have many readers at the same time (given that there are no write locks already in) so you can get better concurrent performance under some cases, especially when having many reads here.



You should add many more threads that are accessing this object to test performance.



And you can simply count time between finishing and starting of operations to measure performance (in example - Long startTime = System.nanoTime();).



Read up here to see how to check whether thread has ended so you can measure execution time :
How to know if other threads have finished?





edit to answer comment:
Hey, my answer is a bit simplified (ok, very, as multithreading is hard) as I was writing this in between doing stuff, so, for now, I can link you with some other resources which provide more in-depth look.




  • What does 'synchronized' mean?


  • How do I write a correct micro-benchmark in Java? <- when writing performance tests it's good to be aware of this

  • https://javarevisited.blogspot.com/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

  • https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html


very simple example as per your existing class:



class Number {

private int value;

public Number(int value) {
this.value = value;
}

public synchronized int getValue() {
return value;
}

public synchronized int changeData(int change) {
value = change;
return value;
}
}





share|improve this answer


























  • Thank you for your answer! :) How can I use 'synchronized' in my example above?

    – jakubradzikowski97
    Jan 19 at 21:56











  • see edit in my answer

    – ejaksla
    Jan 19 at 23:12











  • Thank You! Exactly what I needed

    – jakubradzikowski97
    Jan 20 at 0:01











Your Answer






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: "1"
};
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: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
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
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54267888%2fthe-difference-between-read-write-locks-vs-synchronized-shown-on-basic-code%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














The difference between synchronized and read/write locks is such that when you are using synchronized it allows only one thread at a time to access. With read/write lock you can have many readers at the same time (given that there are no write locks already in) so you can get better concurrent performance under some cases, especially when having many reads here.



You should add many more threads that are accessing this object to test performance.



And you can simply count time between finishing and starting of operations to measure performance (in example - Long startTime = System.nanoTime();).



Read up here to see how to check whether thread has ended so you can measure execution time :
How to know if other threads have finished?





edit to answer comment:
Hey, my answer is a bit simplified (ok, very, as multithreading is hard) as I was writing this in between doing stuff, so, for now, I can link you with some other resources which provide more in-depth look.




  • What does 'synchronized' mean?


  • How do I write a correct micro-benchmark in Java? <- when writing performance tests it's good to be aware of this

  • https://javarevisited.blogspot.com/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

  • https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html


very simple example as per your existing class:



class Number {

private int value;

public Number(int value) {
this.value = value;
}

public synchronized int getValue() {
return value;
}

public synchronized int changeData(int change) {
value = change;
return value;
}
}





share|improve this answer


























  • Thank you for your answer! :) How can I use 'synchronized' in my example above?

    – jakubradzikowski97
    Jan 19 at 21:56











  • see edit in my answer

    – ejaksla
    Jan 19 at 23:12











  • Thank You! Exactly what I needed

    – jakubradzikowski97
    Jan 20 at 0:01
















2














The difference between synchronized and read/write locks is such that when you are using synchronized it allows only one thread at a time to access. With read/write lock you can have many readers at the same time (given that there are no write locks already in) so you can get better concurrent performance under some cases, especially when having many reads here.



You should add many more threads that are accessing this object to test performance.



And you can simply count time between finishing and starting of operations to measure performance (in example - Long startTime = System.nanoTime();).



Read up here to see how to check whether thread has ended so you can measure execution time :
How to know if other threads have finished?





edit to answer comment:
Hey, my answer is a bit simplified (ok, very, as multithreading is hard) as I was writing this in between doing stuff, so, for now, I can link you with some other resources which provide more in-depth look.




  • What does 'synchronized' mean?


  • How do I write a correct micro-benchmark in Java? <- when writing performance tests it's good to be aware of this

  • https://javarevisited.blogspot.com/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

  • https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html


very simple example as per your existing class:



class Number {

private int value;

public Number(int value) {
this.value = value;
}

public synchronized int getValue() {
return value;
}

public synchronized int changeData(int change) {
value = change;
return value;
}
}





share|improve this answer


























  • Thank you for your answer! :) How can I use 'synchronized' in my example above?

    – jakubradzikowski97
    Jan 19 at 21:56











  • see edit in my answer

    – ejaksla
    Jan 19 at 23:12











  • Thank You! Exactly what I needed

    – jakubradzikowski97
    Jan 20 at 0:01














2












2








2







The difference between synchronized and read/write locks is such that when you are using synchronized it allows only one thread at a time to access. With read/write lock you can have many readers at the same time (given that there are no write locks already in) so you can get better concurrent performance under some cases, especially when having many reads here.



You should add many more threads that are accessing this object to test performance.



And you can simply count time between finishing and starting of operations to measure performance (in example - Long startTime = System.nanoTime();).



Read up here to see how to check whether thread has ended so you can measure execution time :
How to know if other threads have finished?





edit to answer comment:
Hey, my answer is a bit simplified (ok, very, as multithreading is hard) as I was writing this in between doing stuff, so, for now, I can link you with some other resources which provide more in-depth look.




  • What does 'synchronized' mean?


  • How do I write a correct micro-benchmark in Java? <- when writing performance tests it's good to be aware of this

  • https://javarevisited.blogspot.com/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

  • https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html


very simple example as per your existing class:



class Number {

private int value;

public Number(int value) {
this.value = value;
}

public synchronized int getValue() {
return value;
}

public synchronized int changeData(int change) {
value = change;
return value;
}
}





share|improve this answer















The difference between synchronized and read/write locks is such that when you are using synchronized it allows only one thread at a time to access. With read/write lock you can have many readers at the same time (given that there are no write locks already in) so you can get better concurrent performance under some cases, especially when having many reads here.



You should add many more threads that are accessing this object to test performance.



And you can simply count time between finishing and starting of operations to measure performance (in example - Long startTime = System.nanoTime();).



Read up here to see how to check whether thread has ended so you can measure execution time :
How to know if other threads have finished?





edit to answer comment:
Hey, my answer is a bit simplified (ok, very, as multithreading is hard) as I was writing this in between doing stuff, so, for now, I can link you with some other resources which provide more in-depth look.




  • What does 'synchronized' mean?


  • How do I write a correct micro-benchmark in Java? <- when writing performance tests it's good to be aware of this

  • https://javarevisited.blogspot.com/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

  • https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html


very simple example as per your existing class:



class Number {

private int value;

public Number(int value) {
this.value = value;
}

public synchronized int getValue() {
return value;
}

public synchronized int changeData(int change) {
value = change;
return value;
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 19 at 23:12

























answered Jan 19 at 15:06









ejakslaejaksla

6317




6317













  • Thank you for your answer! :) How can I use 'synchronized' in my example above?

    – jakubradzikowski97
    Jan 19 at 21:56











  • see edit in my answer

    – ejaksla
    Jan 19 at 23:12











  • Thank You! Exactly what I needed

    – jakubradzikowski97
    Jan 20 at 0:01



















  • Thank you for your answer! :) How can I use 'synchronized' in my example above?

    – jakubradzikowski97
    Jan 19 at 21:56











  • see edit in my answer

    – ejaksla
    Jan 19 at 23:12











  • Thank You! Exactly what I needed

    – jakubradzikowski97
    Jan 20 at 0:01

















Thank you for your answer! :) How can I use 'synchronized' in my example above?

– jakubradzikowski97
Jan 19 at 21:56





Thank you for your answer! :) How can I use 'synchronized' in my example above?

– jakubradzikowski97
Jan 19 at 21:56













see edit in my answer

– ejaksla
Jan 19 at 23:12





see edit in my answer

– ejaksla
Jan 19 at 23:12













Thank You! Exactly what I needed

– jakubradzikowski97
Jan 20 at 0:01





Thank You! Exactly what I needed

– jakubradzikowski97
Jan 20 at 0:01


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • 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.


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%2fstackoverflow.com%2fquestions%2f54267888%2fthe-difference-between-read-write-locks-vs-synchronized-shown-on-basic-code%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

Homophylophilia

Updating UILabel text programmatically using a function

Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage