How to work volatile with multithread java - multithreading

Volatile provides reading and writing to program memory bypassing cache. We should use volatile when there is a common resource, such as an integer variable
So, I did a little experiment.
First I had the following classes:
public class Main3 {
static int j = 0;
public static void main(String[] args) throws InterruptedException {
new Thread1().start();
new Thread2().start();
}
static int i = 0;
static class Thread1 extends Thread{
#Override
public void run() {
while(i<5){
System.out.println("thread1 i = "+i);
i++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Thread2 extends Thread{
#Override
public void run() {
int val = i;
while(val<5){
if(val!=i) {
System.out.println("thread2 i = " + i);
val = i;
}
}
}
}
}
In the first thread, the variable changes its value. The second thread monitors the change and displays the text on the console if it happened
i variable is a shared resource. And without volatile the program prints what was expected and cant :
thread1 i = 0
thread1 i = 1
thread1 i = 2
thread1 i = 3
thread1 i = 4
But, if i make this (add sleep to Thread2 class):
static class Thread2 extends Thread{
#Override
public void run() {
int val = i;
while(val<5){
if(val!=i) {
System.out.println("thread2 i = " + i);
val = i;
}
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
the program prints this and successfully finished:
thread1 i = 0
thread2 i = 1
thread1 i = 1
thread2 i = 2
thread1 i = 2
thread2 i = 3
thread1 i = 3
thread2 i = 4
thread1 i = 4
thread2 i = 5
So, if threads cache values, then why does sleep caching disappear with the advent of sleep?

Related

Java Multithreading Using locks to achieve method level locking

public class MainLock {
public static void main(String[] args) throws Exception {
LockClass lock = new LockClass();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
lock.incrementa();
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
lock.incrementb();
}
});
Thread t3 = new Thread(new Runnable() {
#Override
public void run() {
lock.incrementa();
}
});
t1.start();
t2.start();
t3.start();
}
}
public class LockClass {
int a;
int b;
ReentrantLock lock = new ReentrantLock();
public void incrementa() {
lock.lock();
try {
for (int i = 0; i < 3; i++) {
System.out.println("a " + a++);
Thread.sleep(1000);
}
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void incrementb() {
try {
lock.lock();
for (int i = 0; i < 3; i++) {
System.out.println("b " + b++);
Thread.sleep(1000);
}
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The output above result is
a0 a1 a2 b0 b1 b2 a3 a4 a5
I want to achieve a0 b0 a1 b1 a2 b2 a3 a4 a5, thread t1 and t2 should run parallely and t3 should be blocked because of lock by t1.
I know using static synchronization in incrementb() will work but I am looking something only with locks.
I am looking for Method level locking, not object level or class level
I there any way in java to achieve this.
I am looking something only with locks
That's not what locks are for. Pretty much the only thing you should use locks* for is to ensure safe access to shared variables. You should not try to use locks for signaling between threads.
I want to achieve a0 b0 a1 b1 a2 b2...
The best way to make certain things happen in a certain order is to do all of those things in the same thread. You can make threads take turns like that, but it completely defeats the purpose of using threads. The purpose of using threads is to allow different parts of a program to run concurrently, and that is exactly what you are not allowing the threads to do when you force them to take turns.
If you really want to make the threads take turns (e.g., if this is a homework assignment**) then IMO the best way to do that is to pass a virtual token from thread to thread. Holding the token means, "it's your turn."
One way to do it is to use Semaphore objects: Make one semaphore per thread, but give each thread a reference to two of them. Each thread will use one semaphore to receive the token, and the other semaphore to pass the token off to the next thread:
class MyRunnable {
private Semaphore token_in;
private Semaphore token_out;
public MyRunnable(Semaphore token_in, Semaphore token_out) {
this.token_in = token_in;
this.token_out = token_out;
}
public void Run() {
while (...thread should keep running...) {
token_in.acquire(); // wait to receive the token.
...do stuff...
token_out.release(); // hand the token to the next thread.
}
}
}
When you start this up, you must make sure that each thread's token_out is the next thread's token_in:
static void main(...) {
int TOKEN = 1;
int EMPTY = 0;
Semaphore s1 = new Semaphore(TOKEN);
Semaphore s2 = new Semaphore(EMPTY);
Semaphore s3 = new Semaphore(EMPTY);
MyRunnable r1 = new MyRunnable(s1, s2);
MyRunnable r2 = new MyRunnable(s2, s3);
MyRunnable r3 = new MyRunnable(s3, s1);
...create and start the three threads for r1, r2, and r3...
}
* "Locks" includes any use of a synchronized block or a synchronized method or a ReentrantLock.
** If you want to tell your instructor what I said about making threads take turns, that's up to you. You'd be doing the world a favor if you can help eradicate this assignment, but only you can decide whether it's politically smart to talk to your instructor about ideas that are above the level of what they're teaching.

java jstack How many threads run in the same moment?

I run the following code, when I use jstack check thread information, found 100 threads in the runnable state. I know what is the maximum number of CPU thread of execution core * 2, but I'm very confused, even jstack is not instantaneous, why is a runnable thread?Or is not executed by the CPU thread state is runnable.
Has not been thread of execution, his status is also a runnable?
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
long last = System.currentTimeMillis();
try {
byte[] buf = new byte[1024];
FileInputStream fileInputStream = new FileInputStream("");
while (fileInputStream.read(buf) != -1) {
}
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("read over " + (System.currentTimeMillis() - last) );
}, "name" + i).start();
}
}

Hystrix thread-isolation based on Group Key or Command name?

I noticed that Hystrix has two thread-isolation strategy: Thread and Semaphore.
By default Hystrix used Thread strategy and controls it by hystrix.threadpool.default.coreSize and because of ca ommand with same group key will use the same thread pool. So it is based on group key.
When Hystrix is using Semaphore strategy, the Semaphore will save in a ConcurrentHashMap and the key is command name, will it be based on command name?
Here is the code:
/**
* Get the TryableSemaphore this HystrixCommand should use for execution if not running in a separate thread.
*
* #return TryableSemaphore
*/
protected TryableSemaphore getExecutionSemaphore() {
if (properties.executionIsolationStrategy().get() == ExecutionIsolationStrategy.SEMAPHORE) {
if (executionSemaphoreOverride == null) {
TryableSemaphore _s = executionSemaphorePerCircuit.get(commandKey.name());
if (_s == null) {
// we didn't find one cache so setup
executionSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphoreActual(properties.executionIsolationSemaphoreMaxConcurrentRequests()));
// assign whatever got set (this or another thread)
return executionSemaphorePerCircuit.get(commandKey.name());
} else {
return _s;
}
} else {
return executionSemaphoreOverride;
}
} else {
// return NoOp implementation since we're not using SEMAPHORE isolation
return TryableSemaphoreNoOp.DEFAULT;
}
}
Why they have difference scope? I write some testing code to prove it:
public static void main(String[] args) throws InterruptedException {
int i = 0;
while (i++ < 20) {
final int index = i;
new Thread(() -> {
System.out.println(new ThreadIsolationCommand(index).execute());
System.out.println(new SemaphoreIsolationCommand(index).execute());
}).start();
}
}
static class ThreadIsolationCommand extends HystrixCommand<String> {
private int index;
protected ThreadIsolationCommand(int index) {
super(
Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadIsolationCommandGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey(String.valueOf(index)))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
)
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(10)
)
);
this.index = index;
}
#Override
protected String run() throws Exception {
Thread.sleep(500);
return "Hello Thread " + index;
}
#Override
protected String getFallback() {
return "Fallback Thread " + index;
}
}
static class SemaphoreIsolationCommand extends HystrixCommand<String> {
private int index;
protected SemaphoreIsolationCommand(int index) {
super(
Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("SemaphoreIsolationCommandGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey(String.valueOf(index)))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(10)
)
);
this.index = index;
}
#Override
protected String run() throws Exception {
Thread.sleep(500);
return "Hello Semaphore " + index;
}
#Override
protected String getFallback() {
return "Fallback Semaphore " + index;
}
}
This command with same group key and different name, result is :
Fallback Thread 9
Fallback Thread 1
Fallback Thread 8
Fallback Thread 19
Fallback Thread 20
Fallback Thread 14
Fallback Thread 3
Fallback Thread 13
Fallback Thread 17
Fallback Thread 10
Hello Thread 5
Hello Semaphore 17
Hello Semaphore 14
Hello Thread 2
Hello Semaphore 3
Hello Thread 7
Hello Thread 15
Hello Thread 4
Hello Semaphore 13
Hello Semaphore 1
Hello Thread 11
Hello Semaphore 20
Hello Semaphore 19
Hello Thread 18
Hello Thread 12
Hello Semaphore 8
Hello Semaphore 9
Hello Thread 6
Hello Thread 16
Hello Semaphore 10
Hello Semaphore 5
Hello Semaphore 2
Hello Semaphore 7
Hello Semaphore 15
Hello Semaphore 4
Hello Semaphore 11
Hello Semaphore 12
Hello Semaphore 6
Hello Semaphore 18
Hello Semaphore 16
Only Thread strategy has failed. Is that right?

How to send signal from Singleton thread to another thread (Not singleton)

I'm facing a problem while creating a Singleton class with it's own thread that sends signal to another thread which is not a singleton class.
Consumer.h
class Consumer : public QThread
{
Q_OBJECT
public:
explicit Consumer(QObject *parent = 0);
Consumer(Worker *Worker);
signals:
void toMessage(const bool& keepCycle);
public slots:
void getMessage(const QString& str);
private:
int m_counter;
};
Consumer.cpp
Consumer::Consumer(QObject *parent) :
QThread(parent)
{
m_counter = 0;
connect(Worker::Instance(), SIGNAL(sendMessage(QString)), this, SLOT(getMessage(QString)));
connect(this, SIGNAL(toMessage(bool)), Worker::Instance(), SLOT(fromMessage(bool)));
}
// Get's message from Singleton thread if counter > 5 sends signal to terminate cycle in Singleton thread
void Consumer::getMessage(const QString &str)
{
m_counter++;
if(m_counter <= 5) {
qDebug() << "Got message " << m_counter << ": " << str << "\n";
return;
}
else {
emit toMessage(false);
}
}
Singleton is done as follows (suspect it's Not Thread-safe):
template <class T>
class Singleton
{
public:
static T* Instance()
{
if(!m_Instance) m_Instance = new T;
assert(m_Instance != NULL);
return m_Instance;
}
protected:
Singleton();
~Singleton();
private:
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
static T* m_Instance;
};
template <class T> T* Singleton<T>::m_Instance = NULL;
And Worker Singleton class
class Worker : public QThread
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0);
void run();
signals:
void sendMessage(const QString& str);
public slots:
void fromMessage(const bool& keepCycle);
private:
volatile bool m_keepCycle;
};
typedef Singleton<Worker> Worker;
Worker.cpp
Worker::Worker(QObject *parent) :
QThread(parent)
{
m_keepCycle = true;
}
void Worker::run()
{
while(true) {
if(m_keepCycle) {
QString str = "What's up?";
ElWorker::Instance()->sendMessage(str);
}
else {
qDebug() << "Keep Alive" << false;
break;
}
}
qDebug() << "Value of keepCycle" << m_keepCycle;
}
void Worker::fromMessage(const bool &keepCycle)
{
m_keepCycle = keepCycle;
qDebug() << "\nMessage FROM: " << keepCycle << "\n";
}
The main.cpp
Consumer consumer;
ElWorker::Instance()->start();
consumer.start();
Can you help me to create thread-safe Singleton and to send signals between threads?
First of all, it is highly recommended to separate worker from it's thread:
class Object : public QObject
{
...
public slots:
void onStarted(); // if needed
void onFinished(); // if needed
...
};
...
mObject = QSharedPointer < Object >(new Object);
mThread = new QThread(this);
mObject->moveToThread(mThread);
connect(mThread, SIGNAL(started()), mObject, SLOT(onStarted())); // if needed
connect(mThread, SIGNAL(finished()), mObject, SLOT(onFinished())); // if needed
mThread->start();
Second of all, there are a lot of ways of creating a singleton. My favourite is this:
Object * obj(QObject *parent = 0)
{
static Object *mObj = new Object(parent);
return mObj;
}
...
obj(this); // creating
obj()->doStuff(); // using
Now, about thread-safety. Sending signals is thread-safe, unless you're sending pointers or non-constant references. Which, according to your code, you are not. So, you should be fine.
UPDATE
Actually, I didn't get how created thread-safe singleton above and I'm
sending a signal from Worker TO Consumer Not a Thread itself? – hiken
Static values inside of function are created and initialized only once, so the first time you call obj function mObj is created and returned and each other time you call it, previously created mObj is returned. Also, I didn't say, it's thread-safe, all I said - I like this way better, then template one, because:
it is simplier
requires less code
works with QObject without problems
Yes, you should send signals from worker class, not thread one. Qt's help has a good example (the first one, not the second one): http://doc.qt.io/qt-5/qthread.html#details. The only thing QThread should be used for - is controlling thread's flow. There are some situations, when you need to derive from QThread and rewrite QThread::run, but your case isn't one of them.

Semaphore not working as expected ,it is getting locked

i am using semaphore for thread communication i have two threads one is OddThread and another is EvenThread ,i am printing value from 1 to 10 OddThread will print only odd numbers between 1 to 10 and EvenThread thread is printing only even numbers between 1 to 10. for that i have used semaphore for threads to communicate properly .what is actually happening is that OddThread is printing only 1 and EvenThread only 2 and then both get stopped. I am not under standing what is actually happening.can any body suggest.
public class ThreadProducerConsumerSemaphore {
/**
* #param args
*/
public static void main(String[] args) {
Semaphore p = new Semaphore(1);
Semaphore c = new Semaphore(0);
OddThread producer = new OddThread(p, c);
EvenThread consumer = new EvenThread(p, c);
Thread t1 = new Thread(producer, "Thread producer");
Thread t2 = new Thread(consumer, "Thread consumer");
t1.start();
t2.start();
}
}
class OddThread implements Runnable {
Semaphore p;
Semaphore c;
public OddThread(Semaphore p, Semaphore c) {
super();
this.p = p;
this.c = c;
}
int counter = 1;
#Override
public void run() {
while (true) {
try {
p.acquire(1);
System.out.println(Thread.currentThread().getName() + " "
+ counter);
if (counter == 10) {
break;
}
counter++;
c.release(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class EvenThread implements Runnable {
Semaphore p;
Semaphore c;
int counter = 2;
public EvenThread(Semaphore p, Semaphore c) {
super();
this.p = p;
this.c = c;
}
#Override
public void run() {
while (true) {
try {
c.acquire(1);
System.out.println(Thread.currentThread().getName() + " "
+ counter);
if (counter == 10) {
break;
}
counter=counter+2;
p.acquire(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Your code can't be correct, it's not even symmetrical.
p.acquire(1);
c.release(1);
c.acquire(1);
p.acquire(1);
Your EvenThread.run method acquires both c and p, rather than releasing one of them.
Note, however, that your code doesn't look like it'll exit properly even once it's been fixed. Consider: neither thread releases a semaphore before it exits, so one of the threads will inevitably be blocked.
here is your problem:
............
c.acquire(1);
System.out.println(Thread.currentThread().getName() + " "
+ counter);
if (counter == 10) {
break;
}
counter=counter+2;
p.acquire(1); <--deadlock this has already been acquired by the other thread.
..............
you should release p here, to allow the other thread to continue; so replace the line I indicated with p.release(1) and it should be fine.

Resources