Java Multi threading semaphore - java

The counter variable does not accurately reflect how many times increment
method is invoked. Why not, and how can it be fixed? (You do not have to write code,
just use English.)
Original:
import java.util.*;
import java.lang.*;
import java.io.*;
class Foopadoop
{
public static int counter = 0;
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
public void run() {
while(true){
counter++;
}
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
Mine, I added a semaphore but I'm not sure if I'm doing it right or am I suppose to use a lock.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.Semaphore;
class Foopadoop
{
public static int counter = 0;
Semaphore lock = new Semaphore(0);
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
try{public void run() {
while(true){
counter++;
lock.acquire();
}
}
}finally{
lock.release();
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}

That's not how you use a Semaphore.
You acquire it before you access the shared resource, and release it after:
while (true) {
try {
lock.acquire();
counter++;
} finally {
lock.release();
}
}
Since you acquire first, you will also need at least 1 permit, otherwise there is nothing to acquire:
static Semaphore lock = new Semaphore(1);
A synchronized block is easier than a Semaphore:
while (true) {
synchronized (Foopadoop.class) {
counter++;
}
}
or an AtomicInteger:
static AtomicInteger counter = new AtomicInteger();
// ...
while (true) {
counter.getAndIncrement();
}

Also you can add Thread.sleep(ms) inside the while loop, so that it will pause the current thread for some time, & start executing other threads. Otherwise the current thread might run in a selfish manner (selfish thread).

Related

Synchronized, join, and thread safety

I have read through other examples, but do not understand why this code with the commented out t.join() does not always have the end value 5000 for count, but when the code is commented in, count always is 5000 at the end. But why? I thought that the static lock object can only be owned by one thread at a time and when it is owned that the other threads have to wait until it is released. So I do not understand why join() is necessary and what exactly is happening.
import java.util.ArrayList;
public class MyClass implements Runnable {
private static int count = 0;
private static Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 1; i <= 5000; i++)
threads.add(new Thread(new MyClass()));
for (Thread t : threads)
t.start();
// for (Thread t : threads)
// t.join();
System.out.println("Total count = " + MyClass.getCount());
}
public void run() {
synchronized (lock) {
count++;
}
}
public static int getCount() {
return count;
}
}

How can I call a same method with three different thread

Suppose I have a method called Magic() I want to execute this method with three different thread.
I know how to execute Magic() method with a single thread, but I am confuse, How do I do with three different threads?
Suppose I have a method called Magic() I want to execute this method with three different thread
Create a MagicTask class that represents the task that each Thread will execute and call the magic() method inside run() :
class MagicTask implements Runnable {
public void run() {
magic();
}
public void magic() { //do magic }
}
Then create three threads and pass it the task :
Thread t1 = new Thread(new MagicTask());
Thread t2 = new Thread(new MagicTask());
Thread t3 = new Thread(new MagicTask());
Then start the threads :
t1.start();
t2.start();
t3.start();
Note You can pass the same MagicTask instance to all three Thread instances as well. Remember that if MagicTask has state that can get inconsistent when accessed by different threads, you also need to make your class thread-safe by using intrinsic locking using synchronized or other such constructs which are out of the scope for this answer.
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
call();
}
void call(){
System.out.println("method call by"+Thread.currentThread().getName());
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
Thread t2 =new Thread(m1);
Thread t3 =new Thread(m1);
t1.start();
t2.start();
t3.start();
}
}
Here Thread t1,t2,t3 are calling the same method call().
If you are using Java 8, function references are straightforward:
public class Main {
public static void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
new Thread(Main::magic).start();
new Thread(Main::magic).start();
new Thread(Main::magic).start();
}
}
And if magic isn't a static method use:
public class Main {
public void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
Main m = new Main();
new Thread(m::magic).start();
new Thread(m::magic).start();
new Thread(m::magic).start();
}
}
You can try Like.
I am dividing the task to different thread
Try your own logic it just a simple even count,
public class CountNumber implements Runnable {
int stop;
int start;
int totalEvenNo;
public CountNumber(int start, int stop)
{
this.start=start;
this.stop=stop;
}
public void run()
{
int total= countEven(start, stop);
System.out.println("Total Even numbers are :"+total);
}
public int countEven(int str,int stp)
{
for(int i=str;i<=stp;i++)
{
if(i%2==0)
{
totalEvenNo +=1;
System.out.println(totalEvenNo);
}
}
return totalEvenNo;
}
}
public class MainClassNumber {
public static void main(String[] args) {
System.out.println("Spawaning Thread.........");
Thread t1 = new Thread(new CountNumber(0, 500000));
Thread t2 = new Thread(new CountNumber(500001, 2000000));
Thread t3 = new Thread(new CountNumber(2000001, 5000000));
Thread t4 = new Thread(new CountNumber(5000001, 10000000));
Thread t5 = new Thread(new CountNumber(10000001, 20000000));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Call it directly like magic(); And for better result synchronize that method like below
public synchronized void magic(){
//your code
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
public void run() {
Magic();
}
private void Magic() {
// consider synchronizing this method, but if you do method will be accessable by one thread at a time.
}
}
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3)
for (int i = 0; i < 3; i++) {
Runnable worker = new WorkerThread();
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
}
}
}

wait for N-1 out of N threads to end, then issue an instruction for the last thread

So, i apologize for the title. It's quite hard to explain in one sentence what i would like to do if you have no idea on how it is called.
So assume i can only use primitive thread functions (wait, notify, no concurrent package)
The program has 3 threads, all of them are the same and are called by the main thread. They behave normally until one of the three get an exception and so it must wait for the end of the remaining 2 threads in order to start a recovery process.
I was thinking about a static variable but I'm not really sure about it, i would love to keep it as simple as possible.
Each thread starts at the same time.
I don't see any reason why you can't use a static variable like you suggest. Here's how I would do it with an inner class...
private static boolean running = true;
public void test26546397() {
while (true) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
Thread t3 = new Thread(new MyRunnable());
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
running = true;
// Do recovery
}
}
public class MyRunnable implements Runnable {
#Override
public void run() {
while (running) {
try {
// doStuff
} catch (Exception ex) {
running = false;
}
}
}
}
I would of course replace the while (true) with something a little more suitable.
I think you need java.concurrent.CountdownLatch, however if the java.concurrent package is not available to you can code this yourself using Object.wait/notify and synchronized blocks.
The latch can then be decremented in a finally {} on each Thread, this will be run if the Thread completes, or an exception occurs.
Your main program then just needs to wait for count to become 0.
public class StackOverflow26546397 {
static class CountdownLatch {
private int count;
private Object monitor = new Object();
public CountdownLatch(int count) {
this.count = count;
}
public void countDown() {
synchronized (monitor) {
count--;
monitor.notifyAll();
}
}
public void await() throws InterruptedException {
synchronized (monitor) {
while (count > 0) {
monitor.wait();
}
}
}
}
static class Job implements Runnable {
private CountdownLatch latch;
public Job(CountdownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
try {
// do work.
Thread.sleep((long) (Math.random() * 3000d));
} catch (InterruptedException e) {
//
} finally {
latch.countDown();
}
}
}
public static void main(String[] args) throws InterruptedException {
CountdownLatch latch = new CountdownLatch(3);
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
latch.await();
System.out.println("All threads finished");
}
}
Not sure what you are trying to do but this is as simple as I can think of (just native concurrency):
Create a static or shared volatile boolean
private static volatile boolean exceptionOccured=false
Set the above to 'true' when exception occurs:
....}catch(Exception e){
exceptionOccured=true;
}
Check this periodically in you normal thread flow:
if (exceptionOccured)
//enter you synchronized call here
the synchronized method could look something like:
public synchronized void checkAndRecover(){
//decrement a counter or other logic to identify which is the last Thread and then
//perform any recovery logic
}

Understanding ReentrantLocks and Thread basics

I am trying to write a basic program using threads. Assuming I have two threads, t1 and t2 and lock x. Assuming lock x is assigned to t1. When would be a situation where t2 would be unable to process due to lock x being assigned to t1? I am trying to create a simple example to demonstrate how locks/threads work.
I appreciate any assistance in this matter.
This is what I got so far:
Class Skywalker:
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Skywalker{
public static void main(String args[]){
Thread t1 = new Thread("station 1");
Thread t2 = new Thread("station 2");
t1.start();
t2.start();
}
}
Class Darth:
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Darth implements Runnable{
String stationName;
Lock x = new ReentrantLock();
Random r = new Random();
public Darth(String name){
stationName = name;
}
public void run(){
try{
x.lock();
System.out.println(stationName + "is working");
sleep(randomTime);
x.unlock();
} catch(Exception e) {
}
}
}
You should put the lock in one single class to protect a "resource access", for instance:
class SharedResource {
private static Lock lock = new ReentrantLock();
public static void consumeResource(){
try{
lock.lock();
//just one thread a time here
int i = 10;
//mock consuming shared resource:
while(i>0){
i--;
System.out.println(Thread.currentThread().getName() + " is in");
Thread.sleep(1000);
}
}finally{
lock.unlock();
}
}
}
Now just one thread a time will be able to access the lines of code in consumeResource method that are within the lock/unlock statements. It is easy to show that invoking consumeResource from Darth run method.

Thread Waits for a lock when it shouldn't be

i am practicing on java threads, and i am confused with Locking mechanism,
What i am trying to achieve is when a thread is taking much time to execute a block of code whose lock it has acquired, the other thread should just not wait and go for the else condition,
this is my code as follows
import java.util.concurrent.locks.*;
import java.util.concurrent.*;
class MySharedData{
private volatile boolean bFlag;
private int counter=1;
public void abuseIt() throws Exception{
while(!bFlag){
System.out.println(" THREAD "+Thread.currentThread().getName()+" WITH COUNTER "+counter);
counter++;
Thread.sleep(1000);
if(counter > 20){
bFlag=true;
}
}
}
}
class RequesterThree implements Runnable{
private Lock lock;
RequesterThree(){
lock = new ReentrantLock();
}
#Override
public void run(){
MySharedData myShared = null;
try{
myShared = new MySharedData();
if(lock.tryLock(250,TimeUnit.MILLISECONDS)){
myShared.abuseIt();
}else{
System.out.println(Thread.currentThread().getName()+": SHARED DATA IS NON-ACCESSIBLE !!!!");
}
}catch(Exception e){
System.out.println(e);
}finally{
lock.unlock();
}
}
}
public class Ex03{
public static void main(String [] args){
Thread[] requests = new Thread[]{
new Thread(new RequesterThree(),"MICHEAL"),
new Thread(new RequesterThree(),"SHAWN"),
new Thread(new RequesterThree(),"JOHN"),
new Thread(new RequesterThree(),"TRON"),
new Thread(new RequesterThree(),"FINCH")
};
for(int x=0; x < requests.length; x++){
requests[x].start();
}
}
}
But here all of the five threads wait for the lock, and not a single thread prints the SOP in the else condition,
What i am expecting is,
When Thread T1 is started, it acquires the lock, and execute the abuseIt() method, there it sleeps for 1 sec,
Now thread T2 should wait for the lock to get free for only 250 milisec, but T1 is any how waiting for 1 sec, so T2 should execute the else condition in the run method,
How can i achieve this,
In your code, each RequesterThree object has a separate lock, so there is no synchronization across them.
Additionally, each thread calls myShared.abuseIt() on its own dedicated instance of MySharedData.
To fix:
private static final Lock lock = new ReentrantLock();
private static final MySharedData myShared = new MySharedData();
Also, remove the constructor and the change the run() method:
#Override
public void run(){
try{
if(lock.tryLock(250,TimeUnit.MILLISECONDS)){
Finally, your code can call unlock() even if tryLock() hasn't succeeded. This needs to be fixed.
Make your lock field final static
...
class RequesterThree implements Runnable{
private static final Lock lock = new ReentrantLock();
RequesterThree(){
}
...

Categories