I'm trying, for academic purpose, to implement something similar to Java high level locks, using the low level mechanism.
I want to implement a different semantics, in which the signaler thread has to wait until the signaled terminates its critical regional, but when the signaled terminates, the signaler has the precedence in order to get the lock.
My doubt is the following: in the attached code, the presence of two adjacent synchronized block is a problem?
I tried to solve the problem used the boolean modified in the synchronized sections, but because the sections locked on different things, I'm not sure about this solution.
public class FIFOLock {
private final Queue<QueueElement> entrySet;
private boolean busy;
private Thread owner;
protected Queue<Object> urgentQueue;
public FIFOLock() {
this.entrySet = new LinkedList();
this.urgentQueue = new LinkedList();
this.busy = false;
this.owner = null;
}
public void lock() throws InterruptedException {
QueueElement queued;
synchronized (this) {
if ((owner != null) && (owner.equals(Thread.currentThread())))
return; /* Lock already achieved */
if (!busy) {
busy = true;
this.owner = Thread.currentThread();
System.out.println("LockOwner: " + Thread.currentThread().getName());
// System.out.println("FREE");
return;
}
queued = new QueueElement(true);
entrySet.add(queued);
}
synchronized (queued) {
if (queued.isWaiting())
queued.wait();
this.owner = Thread.currentThread();
}
}
public void unlock() throws InterruptedException {
Object urgentElement = new Object();
QueueElement entryElement = new QueueElement(false);
boolean urgent = false;
synchronized (this) {
if (urgentQueue.size() != 0) {
urgentElement = urgentQueue.poll();
urgent = true;
} else {
if (entrySet.size() == 0) {
busy = false;
return;
}
entryElement = entrySet.poll();
}
}
if (urgent) {
synchronized (urgentElement) {
urgentElement.notify();
}
} else {
synchronized (entryElement) {
owner = null;
if (entryElement.isWaiting())
entryElement.notify();
entryElement.setWaiting(false);
}
}
}
}
Related
In my opinion, run method in Thread is invoked by jvm, is there a concurrency problem? when I read FutureTask's source code, I found it use CAS to set current thread. Why can't use:
runner = Thread.currentThread()
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
}
Also, why don't use if (state != NEW && !UNSAFE.compareAndSwapObject(this, runnerOffset,null, Thread.currentThread())) so that run method can only be execute once,then set(result) can replace to
protected void set(V v) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
not
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
Is there necessary to use CAS?
when I use Future<Integer> futureTask1 = executor.submit(callable),submit method will RunnableFuture<T> ftask = newTaskFor(task). If I use
FutureTask futureTask = new FutureTask(new Callable() {
#Override
public Object call() throws Exception {
return null;
}
})
new Thread(futureTask);
new Thread(futureTask);
this is useless. So in diffrent threads there are diffrent RunnableFuture Object,therefore, there is no need for guarantee concurrent calls to run(), Could someone tell me what I miss,thanks
Developers who are new to the workplace are trying hard to learn multithreading knowledge, thank you for your answers
I am learning multithreading. I am implementing producer and consumer problem. I am stuck on scenario where i want that when I press anything apart from integer from keyboard, all my threads should die and there is no memory in use by threads. Please have your valuable inputs to help me achieve it. Below is all the code I am using.
package com.java.concurrency;
public class ThreadSignaling {
private int i = -1;
private boolean valueSet = false;
private boolean stopFlag = false;
public void put(int value) {
synchronized (this) {
while (valueSet) {
if (stopFlag) {
System.out.println("Byeeeeeeeeeeeee");
break;
}
try {
this.wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException while waiting in put() : " + e);
}
}
this.i = value;
this.valueSet = true;
System.out.println("Value put : " + this.i);
this.notify();
}
}
public void get() {
synchronized (this) {
while (!valueSet) {
if (stopFlag) {
System.out.println("Byeeeeeeeeeeeee");
break;
}
try {
this.wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException while waiting in get() : " + e);
}
}
System.out.println("Value get : " + this.i);
valueSet = false;
this.notify();
}
}
public void finish() {
synchronized (this) {
stopFlag = true;
this.notifyAll();
}
}
}
public class Producer implements Runnable {
private ThreadSignaling sharedObj = null;
private final Scanner input = new Scanner(System.in);
public Producer(ThreadSignaling obj) {
this.sharedObj = obj;
}
#Override
public void run() {
int value = -1;
System.out.println("Press Ctrl-c to stop... ");
while (true) {
System.out.println("Enter any integer value : ");
if (input.hasNextInt()) {
value = input.nextInt();
} else {
this.sharedObj.finish();
return;
}
this.sharedObj.put(value);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("InterruptedException while sleeping" + e);
}
}
}
}
public class Consumer implements Runnable {
private ThreadSignaling sharedObj = null;
public Consumer(ThreadSignaling obj) {
this.sharedObj = obj;
}
#Override
public void run() {
while (true) {
this.sharedObj.get();
}
}
}
public class MainThread {
public static void main(String[] args) {
ThreadSignaling sharedObj = new ThreadSignaling();
Producer in = new Producer(sharedObj);
Consumer out = new Consumer(sharedObj);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
} enter code here
The problem with your code is that you do not have an exit condition for the Consumer. The run() method of the Consumer will run forever, and while doing repeated get calls on the shared object.
What you need to do is to make aware the Consumer that the Producer has set the stopFlag in the shared object. And if that stopFlag is true then the loop in the Consumer should also finish. There are several ways you can do that:
redefine get method to return the value of stopFlag;
define a new method to return just the value of stopFlag;
In either cases, make a test in the Consumer.run() and if the value is true, just do a return so the infinite loop ends.
I have the following work queue implementation, which I use to limit the number of threads in use. It works by me initially adding a number of Runnable objects to the queue, and when I am ready to begin, I run "begin()". At this point I do not add any more to the queue.
public class WorkQueue {
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedList queue;
Integer runCounter;
boolean hasBegun;
public WorkQueue(int nThreads) {
runCounter = 0;
this.nThreads = nThreads;
queue = new LinkedList();
threads = new PoolWorker[nThreads];
hasBegun = false;
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
public boolean isQueueEmpty() {
synchronized (queue) {
if (queue.isEmpty() && runCounter == 0) {
return true;
} else {
return false;
}
}
}
public void begin() {
hasBegun = true;
synchronized (queue) {
queue.notify();
}
}
public void add(Runnable r) {
if (!hasBegun) {
synchronized (queue) {
queue.addLast(r);
runCounter++;
}
} else {
System.out.println("has begun executing. Cannot add more jobs ");
}
}
private class PoolWorker extends Thread {
public void run() {
Runnable r;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException ignored) {
}
}
r = (Runnable) queue.removeFirst();
}
// If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run();
synchronized (runCounter) {
runCounter--;
}
} catch (RuntimeException e) {
// You might want to log something here
}
}
}
}
}
This is a runnable I use to keep track of when all the jobs on the work queue have finished:
public class QueueWatcher implements Runnable {
private Thread t;
private String threadName;
private WorkQueue wq;
public QueueWatcher(WorkQueue wq) {
this.threadName = "QueueWatcher";
this.wq = wq;
}
#Override
public void run() {
while (true) {
if (wq.isQueueEmpty()) {
java.util.Date date = new java.util.Date();
System.out.println("Finishing and quiting at:" + date.toString());
System.exit(0);
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(PlaneGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void start() {
wq.begin();
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.setDaemon(false);
t.start();
}
}
}
This is how I use them:
Workqueue wq = new WorkQueue(9); //Get same results regardless of 1,2,3,8,9
QueueWatcher qw = new QueueWatcher(wq);
SomeRunnable1 sm1 = new SomeRunnable1();
SomeRunnable2 sm2 = new SomeRunnable2();
SomeRunnable3 sm3 = new SomeRunnable3();
SomeRunnable4 sm4 = new SomeRunnable4();
SomeRunnable5 sm5 = new SomeRunnable5();
wq.add(sm1);
wq.add(sm2);
wq.add(sm3);
wq.add(sm4);
wq.add(sm5);
qw.start();
But regardless of how many threads I use, the result is always the same - it always takes about 1m 10seconds to complete. This is about the same as when I just did a single threaded version (when everything ran in main()).
If I set wq to (1,2,3--9) threads it is always between 1m8s-1m10s. What is the problem ? The jobs (someRunnable) have nothing to do with each other and cannot block each other.
EDIT: Each of the runnables just read some image files from the filesystems and create new files in a separate directory. The new directory eventually contains about 400 output files.
EDIT: It seems that only one thread is always doing work. I made the following changes:
I let the Woolworker store an Id
PoolWorker(int id){
this.threadId = id;
}
Before running I print the id of the worker.
System.out.println(this.threadId + " got new task");
r.run();
In WorkQueue constructor when creating the poolworkers I do:
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker(i);
threads[i].start();
}
But it seems that that only thread 0 does any work, as the output is always:
0 got new task
Use queue.notifyAll() to start processing.
Currently you're using queue.notify(), which will only wake a single thread. (The big clue that pointed me to this was when you mentioned only a single thread was running.)
Also, synchronizing on Integer runCounter isn't doing what you think it's doing - runCounter++ is actually assigning a new value to the Integer each time, so you're synchronizing on a lot of different Integer objects.
On a side note, using raw threads and wait/notify paradigms is complicated and error-prone even for the best programmers - it's why Java introduced the java.util.concurrent package, which provide threadsafe BlockingQueue implementations and Executors for easily managing multithreaded apps.
I wanted to code the airport monitor (planes trying to arrive, planes trying to departure, etc.) and I have a problem with something. Only one thread seems to be working, others are stuck somewhere. Can somebody please look at this code and help?
public class Lotniskowiec {
public int K=5;
public int N = 10;
final Lock lock = new ReentrantLock();
final Condition toStart = lock.newCondition();
final Condition toLand= lock.newCondition();
boolean wantsToStart;
boolean wantsToLand;
int atAirport= 0;
boolean free= true;
private void free_landing_area(){
lock.lock();
if(atAirport< K){
if(wantsToLand){
toLand.signal();
}else toStart.signal();
}
else{
if(wantsToStart){
toStart.signal();
} else if (atAirport< N){
toLand.signal();
}
}
lock.unlock();
}
public void wants_to_start(){
lock.lock();
if(!free){
lock.unlock();
try {
toStart.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.lock();
free=false;
lock.unlock();
}
public void started(){
lock.lock();
atAirport-=1;
free=true;
free_landing_area();
lock.unlock();
}
public void wants_to_land(){
lock.lock();
if(!free|| atAirport==N){
lock.unlock();
try {
toLand.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.lock();
free=false;
lock.unlock();
}
public void landed(){
lock.lock();
atAirport+=1;
free=true;
free_landing_area();
lock.unlock();
}
}
So sorry for names of variables ;)
threads:
public class Samolot implements Runnable{
Random random = new Random();
Lotniskowiec lotniskowiec = new Lotniskowiec();
int id;
public Samolot(int id, Lotniskowiec lotniskowiec){
this.id=id;
this.lotniskowiec=lotniskowiec;
}
#Override
public void run() {
while(true){
try {
Thread.sleep(random.nextInt(1000));
Lotniskowiec.wants_to_land();
System.out.println(id + " chce ladowac");
Thread.sleep(random.nextInt(1000));
Lotniskowiec.landed();
System.out.println(id + " wyladowal");
Thread.sleep(random.nextInt(1000));
Lotniskowiec.wants_to_start();
System.out.println(id + " chce startowac");
Thread.sleep(random.nextInt(1000));
Lotniskowiec.started();
System.out.println(id + " wystartowal");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
starting threads:
Samolot r = new Samolot(1,lotniskowiec);
Thread t = new Thread(r);
t.start();
Your wants_to_land and wants_to_start are booleans but they should be integers. Otherwise how will you be able to keep track of how many planes wish to land?
Also, I suspect it's good enough to lock.lock() at the start of each method called by the planes and lock.unlock() at the end of it. In your current code a plane can acquire the lock more times than it releases it, effectively stealing it from the others.
Also, it may help to make the lock fair.
So
public static int K = 5;
public static int N = 10;
final static Lock lock = new ReentrantLock(true);
final static Condition toStart = lock.newCondition();
final static Condition toLand = lock.newCondition();
static int wantsToStart = 0;
static int wantsToLand = 0;
static int atAirport = 0;
static boolean free = true;
private static void free_landing_area() {
if (atAirport < K) {
if (wantsToLand > 0) {
toLand.signal();
} else {
toStart.signal();
}
} else {
if (wantsToStart > 0) {
toStart.signal();
} else if (atAirport < N) {
toLand.signal();
}
}
}
public static void wants_to_start() {
lock.lock();
if (!free) {
try {
wantsToStart++;
toStart.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
free = false;
lock.unlock();
}
public static void started() {
lock.lock();
atAirport -= 1;
free = true;
wantsToStart--;
free_landing_area();
lock.unlock();
}
public static void wants_to_land() {
lock.lock();
if (!free || atAirport == N) {
try {
wantsToLand++;
toLand.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
free = false;
lock.unlock();
}
public static void landed() {
lock.lock();
atAirport += 1;
free = true;
wantsToLand--;
free_landing_area();
lock.unlock();
}
Finally, I believe you actually need to await() in a while loop, since threads may be woken accidentally in some cases.
When waiting upon a Condition, a "spurious wakeup" is permitted to
occur, in general, as a concession to the underlying platform
semantics. This has little practical impact on most application
programs as a Condition should always be waited upon in a loop,
testing the state predicate that is being waited for.
So the code above is not quite there yet. But that was not what was keeping your threads stuck.
Ok, here is the clue:
Other threads are locked in wants_to_land method at toLand.await() statement.
toLand.signal() never happens, because if(wantsToLand) and if(wantsToStart) are allways false (You aren't changing it nowhere).
Consider refreshing sync logic and see if that helps.
I'm having a bit of a problem with writing a multithreaded algorithm in Java. Here's what I've got:
public class NNDFS implements NDFS {
//Array of all worker threads
private Thread[] threadArray;
//Concurrent HashMap containing a mapping of graph-states and
//algorithm specific state objects (NDFSState)
private ConcurrentHashMap<State, NDFSState> stateStore;
//Whether the algorithm is done and whether a cycle is found
private volatile boolean done;
private volatile boolean cycleFound;
/**
Constructor that creates the threads, each with their own graph
#param file The file from which we can create the graph
#param stateStore Mapping between graph-states and state belonging to our algorithm
#param nrWorkers Number of working threads we need
*/
public NNDFS(File file, Map<State, NDFSState> stateStore, int nrWorkers) throws FileNotFoundException {
int i;
this.stateStore = new ConcurrentHashMap<State, NDFSState>(stateStore);
threadArray = new Thread[nrWorkers];
for(i=0;i<nrWorkers;i++){
Graph graph = GraphFactory.createGraph(file);
threadArray[i] = new Thread(new NDFSRunnable(graph, i));
}
}
/**
Class which implements a single thread running the NDFS algorithm
*/
class NDFSRunnable implements Runnable{
private Graph graph;
//Neccesary as Java apparently doesn't allow us to get this ID
private long threadId;
NDFSRunnable(Graph graph, long threadId){
this.graph = graph;
this.threadId = threadId;
}
public void run(){
try {
System.out.printf("Thread id = %d\n", threadId);
//Start by executing the blue DFS for the first graph
mcdfsBlue(graph.getInitialState(), threadId);
} catch (CycleFound e) {
//We must catch all exceptions that are thrown from within our thread
//If exceptions "exit" the thread, the thread will silently fail
//and we dont want that. We use 2 booleans instead, to indicate the status of the algorithm
cycleFound = true;
}
//Either the algorithm was aborted because of a CycleFound exception
//or we completed our Blue DFS without finding a cycle. We are done!
done = true;
}
public void mcdfsBlue(State s, long id) throws CycleFound {
if(done == true){
return;
}
//System.out.printf("Thread %d begint nu aan een dfsblue\n", id);
int i;
int counter = 0;
NDFSState state = stateStore.get(s);
if(state == null){
state = new NDFSState();
stateStore.put(s,state);
}
state.setColor(id, Color.CYAN);
List<State> children = graph.post(s);
i = state.incNextBlue();
while(counter != children.size()){
NDFSState child = stateStore.get(children.get(i%children.size()));
if(child == null){
child = new NDFSState();
stateStore.put(children.get(i % children.size()),child);
}
if(child.getLocalColor(id) == Color.WHITE && !child.isRed()){
mcdfsBlue(children.get(i % children.size()), id);
}
i++;
counter++;
}
if(s.isAccepting()){
state.incRedDFSCount();
mcdfsRed(s, id);
}
state.setColor(id, Color.BLUE);
}
public void mcdfsRed(State s, long id) throws CycleFound {
if(done == true){
return;
}
int i;
int counter = 0;
NDFSState state = stateStore.get(s);
state.setPink(id, true);
List<State> children = graph.post(s);
i = state.incNextRed();
while(counter != children.size()){
NDFSState child = stateStore.get(children.get(i%children.size()));
if(child == null){
child = new NDFSState();
stateStore.put(children.get(i%children.size()),child);
}
if(child.getLocalColor(id) == Color.CYAN){
throw new CycleFound();
}
if(!child.isPink(id) && !child.isRed()){
mcdfsRed(children.get(i%children.size()), id);
}
i++;
counter++;
}
if(s.isAccepting()){
state.decRedDFSCountAndWait();
}
state.setRed();
state.setPink(id, false);
}
}
public void init() {}
public void ndfs() throws Result {
int i;
done = false;
cycleFound = false;
for(i=0;i<threadArray.length;i++){
System.out.printf("Launch thread %d\n",i);
threadArray[i].run();
}
try {
for(i=0;i<threadArray.length;i++){
threadArray[i].join();
}
} catch (InterruptedException e) {
}
//We want to show the result by throwing an exception (weird, but yeah :-/)
if (cycleFound) {
throw new CycleFound();
} else {
throw new NoCycleFound();
}
}
}
However, when I run this, it seems like the first thread is called, completes, and then the next is called etc. What I want obviously, is that all threads are started simultaneously! Otherwise the algorithm has very little use...
Thanks for your time/help!
Regards,
Linus
Use threadArray[i].start(); to launch your thread.
If you use threadArray[i].run();, all it does is call the method normally, in the same thread as the caller.