Showing posts with label volatile. Show all posts
Showing posts with label volatile. Show all posts

Sunday, December 8, 2019

What will be the output of the below java code using volatile keyword?

Problem statement: Given code is
  1. public class Test extends Thread {
  2. private volatile int i = 0;
  3. public int getData() {
  4. return i + 1;
  5. }
  6. public void run() {}
  7. public static void main(String[] args) {
  8. Test t1 = new Test();
  9. t1.start();
  10. System.out.println("First thread: " + t1.getData());
  11. Test t2 = new Test();
  12. t2.start();
  13. System.out.println("Second thread: " + t2.getData());
  14. Test t3 = new Test();
  15. t3.start();
  16. System.out.println("Third thread: " + t3.getData());
  17. }
  18. }
Output:
First thread: 1
Second thread: 1
Third thread: 1

Friday, April 27, 2018

Volatile in java

public class SharedObject {
// Changes made to SharedObject in one thread may not be
// immediately reflect in other thread
static int sharedVariable = 8;
}

/**
 * Suppose two threads are working on SharedObject. If two threads run on
 * different processes each thread may have its own local copy of
 * sharedVariable. If one thread modifies its value the changes might not
 * reflect in the original one in the main memory instantly.
 * 
 */

public class SharedObject {
// Changes made to SharedObject in one thread may not be
// immediately reflect in other thread
static volatile int sharedVariable = 8;
}

Explanation: here changes made by one thread to shared data are visible to other threads.

import java.util.logging.Level;
import java.util.logging.Logger;

public class VolatileExe {
private static final Logger LOGGER = Logger.getLogger(VolatileExe.class.getName());

private static volatile int MY_INT = 0;

public static void main(String[] args) {
new ChangeListener().start();
new ChangeMaker().start();
}

static class ChangeListener extends Thread {
@Override
public void run() {
int local_value = MY_INT;
while (local_value < 5) {
if (local_value != MY_INT) {
LOGGER.log(Level.INFO, "Got Change for MY_INT : {0}", MY_INT);
local_value = MY_INT;
}
}
}
}

static class ChangeMaker extends Thread {
@Override
public void run() {

int local_value = MY_INT;
while (MY_INT < 5) {
LOGGER.log(Level.INFO, "Incrementing MY_INT to {0}", local_value + 1);
MY_INT = ++local_value;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...