I have a class with a function which is synchronized like so:
public synchronized void enqueue(int number) {...}
In my program I have several threads running all wanting to use this function on a specific object of the class. What I would like to happen is for the threads to simply try using the function and if it is locked to not wait on it simply skip running that function.
Can this be done without using the Java.util.concurency library and only using syncronization primatives?
The restriction of not using concurrency is not optional
I like the AtomicInteger solution, but of course AtomicInteger is part of the concurrency package. You can follow the same principle (with lower efficiency, though) with the following simple code:
private boolean locked = false;
public void enqueue(int number) {
synchronized (this) {
if (locked) {
return;
}
locked = true;
}
try {
// Synchronized goodness goes here.
} finally {
synchronized (this) {
locked = false;
}
}
}
Since you're restricted here, here's what I would do:
Make a class with the ability to tell it that you want to lock on it. There are two types of locks: passive lock, and active lock. A passive lock will allow an unlimited number of threads to pass. An active lock will make it belong only to that thread.
When you want a passive lock, you have to register yourself, and unregister yourself when you're done. You'll wait on an internal object until all active locks are done.
When you want an active lock, you wait for all current passive locks have unregistered. If there's currently an active lock (store a thread reference to see if there is, utilizing Thread.currentThread()) then wait until notified. You can then set yourself as the referred thread. When you unregister, if there are waiting active locks, notify one of them (consider a Set<Thread> to register this). If there aren't, notify all the passive locks that are waiting and they can go through.
There's going to be a lot of unanswered questions here, and I doubt it's perfect, but this is most of what you're looking for...
Rather than use any synchronization primitives I'd recommend using something like the AtomicInteger class to leverage a CAS (compare-and-swap) operation for your anti-concurrency strategy:
public void enqueue(int number) {
if (!atomicInteger.compareAndSet(0, 1) {
return;
}
try {
// Synchronized goodness goes here.
} finally {
atomicInteger.set(0);
}
}
May be you can you synchronize the object that handles the Queue. If someone else ois using the queue the enqueue does nothing. I have an example that compiles and run. Very simple example but not pretty:
class Queue {
public void enqueue(int number) {
// something in this method for demo purposes only
try {
Thread.sleep(100);
} catch (InterruptedException e){}
System.out.println(Thread.currentThread().getName()+" done");
}
}
class Demo {
private static Queue e = new Queue();
public void enqueue(int number) {
Queue q = getQueue();
if (q!=null) {
q.enqueue(number);
releaseQueue(q);
} else {
// do nothing since the queue is being used
System.out.println(Thread.currentThread().getName()+" done doing nothing");
}
}
public synchronized Queue getQueue() {
Queue b = e;
e = null;
return b;
}
public synchronized void releaseQueue(Queue q) {
e = q;
}
public static void main(String[] args) {
for (int j = 0; j < 5; j++) {
Thread t = new Thread(new Runnable() {
public void run() {
Demo d = new Demo();
d.enqueue(5);
}
}, "Thread "+j);
t.start();
try {
Thread.sleep(50);
} catch (InterruptedException e){}
}
}
}
YES You can implement locking on your own by managing a static variable in that class, or a using a "lock" text file, for example.
HOWEVER Although this simplistic hack would not be terribly difficult --- the java.util.concurrency package solution would be EVEN EASIER, AND is a better choice because, as you will quickly find, when building multithreaded resources into applications our needs will quickly exceed your current expectations
Don't worry about the WHOLE concurrency package -- I find that just taking 3 minutes to learn how to use the AtomicBoolean or AtomicLong fields can be enough to enable simple, multithreaded logic with a minimal effort.
Related
I have a Thread that only has to work when a certain circumstance comes in. Otherwise it just iterates over an empty infinite loop:
public void run() {
while(true) {
if(ball != null) {
// do some Calculations
}
}
}
Does it affect the performance when the loop actually does nothing but it has to check if it has to do the calculation every iteration?
Only creating a this Thread when needed is not an option for me, because my class which implements Runnable is a visual object which has be shown all the time.
edit: so is the following a good solution? Or is it better to use a different method (concerning performance)?
private final Object standBy = new Object();
public void run() {
while(true) {
synchronized (standBy) {
while(ball != null) // should I use while or if here?
try{ standBy.wait() }
catch (InterruptedException ie) {}
}
if(ball != null) {
// do some Calculations
}
}
public void handleCollision(Ball b) {
// some more code..
ball = b;
synchronized (standBy) {
standBy.notify();
}
}
You might want to consider putting the thread to sleep and only waking it up only when your 'ball' variable becomes true. There are multiple ways of doing this, from using the very low level, wait and notify statements to using the java.util.concurrent classes which provide a less error prone way of doing this. Have a look at the documentation for the condition interface. A data structure like a BlockingQueue would also be a solution.
Yes it does. This is the most simple implementation of busy waiting, and should be avoided whenever possible. Use wait/notify or java.util.concurrent mechanisms. Maybe you should be more specific about what exactly you want to achieve to get more useful responses.
Yes, it will certainly affect performance. To increase performance, you can consider putting in a bit of a time delay (say 500ms or 1000ms or even higher) in your code depending how crucial timing is to you.
Share a BlockingQueue between your threads.
class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) { queue = q; }
public void run() {
try {
while (true) { queue.put(produce()); }
} catch (InterruptedException ex) { ... handle ...}
}
Object produce() { ... }
}
class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) { queue = q; }
public void run() {
try {
while (true) { consume(queue.take()); }
} catch (InterruptedException ex) { ... handle ...}
}
void consume(Object x) { ... }
}
I found the following interesting thing. In task manager, running that infinite loop like that, would consume 17% of my CPU. Now, if I added a simple
Thread.sleep(1)
inside the loop, which is only one milisecond, the CPU use dropped to almost zero as if I was not using the program, and the response time of the program was still pretty good on average (in my case it needed to reply things fast)
I am studying for java certification, and I see this example from Mughal's book:
public class Smiley extends Thread
{
#Override
public void run()
{
while(true)
{
synchronized(this)
{
try
{
System.out.print(":");
Thread.sleep(100);
System.out.print("-");
Thread.sleep(100);
System.out.println(")");
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public static void main(String[] args)
{
new Smiley().start();
new Smiley().start();
}
}
The purpose is to print one smiley :-) per line. My question is that why synchronizing on instance (this) doesn't achieve this? Why we need to synchronize on static level?
Thanks,
Because note that the main() function creates two Smiley classes. And they each run on their own thread. Since they are locking on this, they are both going to acquire the lock immediately, with no contention with the other thread. In this case, their locking scheme of synchronize(this) accomplishes nothing.
When dealing with multithreading issues, you have to think "What am I trying to protect?" In this case, you need to protect System.out, to ensure that you are accessing it in the order you want to. Since System.out is static, you need some sort of outer scope lock which each thread has to acquire before they can write to it.
You can use ReentrantLock to achieve this.
Please do not use synchronized (this) - this is bad practice in general
As explained above - the lock should be shared between the two threads, and in this case the lock is the instance of each class (i.e - the objects created by new Smiley).
What you should have is a shared lock, maybe by using a static variable, which is shared among all instances of the same class,
or pass a lock as parameter to the CTOR of smiley.
I will give example for the 2nd option, based on the suggestion of #Jonathon Reinhart to use a Reentrant Lock
public class Smiley extends Thread
{
private ReentantLock lock;
public Smiley(ReentrantLock lock) {
this.lock = lock;
}
#Override
public void run()
{
while(true)
{
try {
lock.lock();
System.out.print(":");
Thread.sleep(100);
System.out.print("-");
Thread.sleep(100);
System.out.println(")");
Thread.sleep(100);
}
catch(InterruptedException e) {
e.printStackTrace();
}
finally {
lock.unlock();
}
}
}
}
public static void main(String[] args)
{
ReentrantLock lock = new ReentantLock();
new Smiley(lock).start();
new Smiley(lock).start();
}
Some pointers -
a. bare in mind that the unlock code must be in a finally clause - this is a good practice (you can also have try block and finally block, without a catch block).
b. You may consider replacing ReentrantLock with other locks from java.util.concurrent package - based on your needs
It's actually two questions you are asking, and the answers are:
Why synchronizing on instance (this) doesn't achieve this?
Because you are acquiring two different implicit locks, so the instructions inside the synchronized block are allowed to be executed concurrently by the two threads and may be actually interleaved.
Why we need to synchronize on static level?
You don't need to synchronize on a static level. You need to synchronize on the same instance of an object shared by the threads.
The simplest way to achieve what you want is to synchronize on System.out in the following way:
#Override
public void run() {
while (true) {
synchronized (System.out) {
try {
System.out.print(":");
Thread.sleep(100);
System.out.print("-");
Thread.sleep(100);
System.out.println(")");
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have a Java book I'm learning from and in one of the examples, I saw something suspicious.
public class ThreadExample extends MIDlet {
boolean threadsRunning = true; // Flag stopping the threads
ThreadTest thr1;
ThreadTest thr2;
private class ThreadTest extends Thread {
int loops;
public ThreadTest(int waitingTime) {
loops = waitTime;
}
public void run() {
for (int i = 1; i <= loops; i++) {
if (threadsRunning != true) { // here threadsRunning is tested
return;
}
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println(e);
}
}
}
}
public ThreadExample() {
thr1 = new ThreadTest(2);
thr2 = new ThreadTest(6);
}
public void startApp() throws MIDletStateChangeException {
thr1.start();
thr2.start();
try {
Thread.sleep(4000); // we wait 4 secs before stopping the threads -
// this way one of the threads is supposed to finish by itself
} catch(InterruptedException e) {
System.out.println(e);
}
destroyApp();
}
public void destroyApp() {
threadsRunning = false;
try {
thr1.join();
thr2.join();
} catch(InterruptedException e) {
System.out.println(e);
}
notifyDestroyed();
}
}
As it is a MIDlet app, when it's started, the startApp method is executed. To keep it simple, the startApp method itself calls destroyApp and so the program destroys, stopping the threads and notifying the destruction.
The question is, is it safe to use this 'threadsRunning' variable and would its use inside both threads and in the destroyApp method cause any trouble at some point? Would 'volatile' keyword put in front of the declaration help to synchronize it?
Setting a boolean value is atomic, and there is no "read then modify" logic in this example, so access to the variable doesn't need to be synchronised in this particular case.
However, the variable should at least be marked volatile.
Marking the variable volatile does not synchronise the threads' access to it; it makes sure that a thread doesn't miss another thread's update to the variable due to code optimisation or value caching. For example, without volatile, the code inside run() may read the threadsRunning value just once at the beginning, cache the value, and then use this cached value in the if statement every time, rather than reading the variable again from main memory. If the threadsRunning value gets changed by another thread, it might not get picked up.
In general, if you use a variable from multiple threads, and its access is not synchronised, you should mark it volatile.
I am trying to get familiar with Java threads for the SCJP and I had a question.
In the below-written code i simply created:
two Runnables with
a common data storage (an array) and
a synchronized write() method to fill it with data successively leaving a letter as a mark for each Runnable (A and B) in sequence.
I know the code is rough and could be better written but I was seeking the moral of the threads.
So now when I run it, it never terminates and the results stop at:
Still good.
A0.
But when I change wait() to wait(100) it works just fine counting from 0 to 9 and it terminates normally. Could someone explain the reason behind that for me please?
Thank you.
public class ArrayThreads {
Object[] array = new Object[10];
boolean isA = true;
int position = 0;
int getIndex(){
return position;
}
class ThreadA implements Runnable{
synchronized void write(String value){
while(!isA){
try {
wait();
} catch (InterruptedException ex) {
System.out.println("An error in" + value);
ex.printStackTrace();
}
}
array[position] = value + position;
System.out.println(array[position]);
position++;
isA = !isA;
notify();
}
public void run() {
while(getIndex()<array.length){
if (getIndex()==9) return;
else
write("A");}
}
}
class ThreadB implements Runnable{
synchronized void write(String value){
while(isA){
try {
wait();
} catch (InterruptedException ex) {
System.out.println("An error in" + value);
ex.printStackTrace();
}
}
array[position] = value + position;
System.out.println(array[position]);
position++;
isA = !isA;
notify();
}
public void run() {
while(getIndex()<array.length){
if (getIndex()==9) return;
else
write("B");}
}
}
public static void main(String[] args){
ArrayThreads threads = new ArrayThreads();
Thread threadA = new Thread(threads.new ThreadA());
Thread threadB = new Thread(threads.new ThreadB());
System.out.println("Still good");
threadB.start();
threadA.start();
}
}
Your threads are each waiting and notifying separate objects - so they're not communicating with each other at all. If you want them to effectively release each other, they'll need a shared monitor to synchronize, wait on and notify.
It's "working" when you specify a timeout because it's effectively turning the wait call into a sleep call... still nothing is really waiting/notifying usefully, because the two threads are still dealing with separate monitors.
your objects are not working in same monitor.
you need to either move the wait() and notify() to same object like:
http://www.java-samples.com/showtutorial.php?tutorialid=306
or you can notify the target object:
http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ315_016.htm
when you set wait(100). you are setting a timeout. and definitely it will wake up after 100ms.
I have few asynchronous tasks running and I need to wait until at least one of them is finished (in the future probably I'll need to wait util M out of N tasks are finished).
Currently they are presented as Future, so I need something like
/**
* Blocks current thread until one of specified futures is done and returns it.
*/
public static <T> Future<T> waitForAny(Collection<Future<T>> futures)
throws AllFuturesFailedException
Is there anything like this? Or anything similar, not necessary for Future. Currently I loop through collection of futures, check if one is finished, then sleep for some time and check again. This looks like not the best solution, because if I sleep for long period then unwanted delay is added, if I sleep for short period then it can affect performance.
I could try using
new CountDownLatch(1)
and decrease countdown when task is complete and do
countdown.await()
, but I found it possible only if I control Future creation. It is possible, but requires system redesign, because currently logic of tasks creation (sending Callable to ExecutorService) is separated from decision to wait for which Future. I could also override
<T> RunnableFuture<T> AbstractExecutorService.newTaskFor(Callable<T> callable)
and create custom implementation of RunnableFuture with ability to attach listener to be notified when task is finished, then attach such listener to needed tasks and use CountDownLatch, but that means I have to override newTaskFor for every ExecutorService I use - and potentially there will be implementation which do not extend AbstractExecutorService. I could also try wrapping given ExecutorService for same purpose, but then I have to decorate all methods producing Futures.
All these solutions may work but seem very unnatural. It looks like I'm missing something simple, like
WaitHandle.WaitAny(WaitHandle[] waitHandles)
in c#. Are there any well known solutions for such kind of problem?
UPDATE:
Originally I did not have access to Future creation at all, so there were no elegant solution. After redesigning system I got access to Future creation and was able to add countDownLatch.countdown() to execution process, then I can countDownLatch.await() and everything works fine.
Thanks for other answers, I did not know about ExecutorCompletionService and it indeed can be helpful in similar tasks, but in this particular case it could not be used because some Futures are created without any executor - actual task is sent to another server via network, completes remotely and completion notification is received.
simple, check out ExecutorCompletionService.
ExecutorService.invokeAny
Why not just create a results queue and wait on the queue? Or more simply, use a CompletionService since that's what it is: an ExecutorService + result queue.
This is actually pretty easy with wait() and notifyAll().
First, define a lock object. (You can use any class for this, but I like to be explicit):
package com.javadude.sample;
public class Lock {}
Next, define your worker thread. He must notify that lock object when he's finished with his processing. Note that the notify must be in a synchronized block locking on the lock object.
package com.javadude.sample;
public class Worker extends Thread {
private Lock lock_;
private long timeToSleep_;
private String name_;
public Worker(Lock lock, String name, long timeToSleep) {
lock_ = lock;
timeToSleep_ = timeToSleep;
name_ = name;
}
#Override
public void run() {
// do real work -- using a sleep here to simulate work
try {
sleep(timeToSleep_);
} catch (InterruptedException e) {
interrupt();
}
System.out.println(name_ + " is done... notifying");
// notify whoever is waiting, in this case, the client
synchronized (lock_) {
lock_.notify();
}
}
}
Finally, you can write your client:
package com.javadude.sample;
public class Client {
public static void main(String[] args) {
Lock lock = new Lock();
Worker worker1 = new Worker(lock, "worker1", 15000);
Worker worker2 = new Worker(lock, "worker2", 10000);
Worker worker3 = new Worker(lock, "worker3", 5000);
Worker worker4 = new Worker(lock, "worker4", 20000);
boolean started = false;
int numNotifies = 0;
while (true) {
synchronized (lock) {
try {
if (!started) {
// need to do the start here so we grab the lock, just
// in case one of the threads is fast -- if we had done the
// starts outside the synchronized block, a fast thread could
// get to its notification *before* the client is waiting for it
worker1.start();
worker2.start();
worker3.start();
worker4.start();
started = true;
}
lock.wait();
} catch (InterruptedException e) {
break;
}
numNotifies++;
if (numNotifies == 4) {
break;
}
System.out.println("Notified!");
}
}
System.out.println("Everyone has notified me... I'm done");
}
}
As far as I know, Java has no analogous structure to the WaitHandle.WaitAny method.
It seems to me that this could be achieved through a "WaitableFuture" decorator:
public WaitableFuture<T>
extends Future<T>
{
private CountDownLatch countDownLatch;
WaitableFuture(CountDownLatch countDownLatch)
{
super();
this.countDownLatch = countDownLatch;
}
void doTask()
{
super.doTask();
this.countDownLatch.countDown();
}
}
Though this would only work if it can be inserted before the execution code, since otherwise the execution code would not have the new doTask() method. But I really see no way of doing this without polling if you cannot somehow gain control of the Future object before execution.
Or if the future always runs in its own thread, and you can somehow get that thread. Then you could spawn a new thread to join each other thread, then handle the waiting mechanism after the join returns... This would be really ugly and would induce a lot of overhead though. And if some Future objects don't finish, you could have a lot of blocked threads depending on dead threads. If you're not careful, this could leak memory and system resources.
/**
* Extremely ugly way of implementing WaitHandle.WaitAny for Thread.Join().
*/
public static joinAny(Collection<Thread> threads, int numberToWaitFor)
{
CountDownLatch countDownLatch = new CountDownLatch(numberToWaitFor);
foreach(Thread thread in threads)
{
(new Thread(new JoinThreadHelper(thread, countDownLatch))).start();
}
countDownLatch.await();
}
class JoinThreadHelper
implements Runnable
{
Thread thread;
CountDownLatch countDownLatch;
JoinThreadHelper(Thread thread, CountDownLatch countDownLatch)
{
this.thread = thread;
this.countDownLatch = countDownLatch;
}
void run()
{
this.thread.join();
this.countDownLatch.countDown();
}
}
If you can use CompletableFutures instead then there is CompletableFuture.anyOf that does what you want, just call join on the result:
CompletableFuture.anyOf(futures).join()
You can use CompletableFutures with executors by calling the CompletableFuture.supplyAsync or runAsync methods.
Since you don't care which one finishes, why not just have a single WaitHandle for all threads and wait on that? Whichever one finishes first can set the handle.
See this option:
public class WaitForAnyRedux {
private static final int POOL_SIZE = 10;
public static <T> T waitForAny(Collection<T> collection) throws InterruptedException, ExecutionException {
List<Callable<T>> callables = new ArrayList<Callable<T>>();
for (final T t : collection) {
Callable<T> callable = Executors.callable(new Thread() {
#Override
public void run() {
synchronized (t) {
try {
t.wait();
} catch (InterruptedException e) {
}
}
}
}, t);
callables.add(callable);
}
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(POOL_SIZE);
ExecutorService executorService = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 0, TimeUnit.SECONDS, queue);
return executorService.invokeAny(callables);
}
static public void main(String[] args) throws InterruptedException, ExecutionException {
final List<Integer> integers = new ArrayList<Integer>();
for (int i = 0; i < POOL_SIZE; i++) {
integers.add(i);
}
(new Thread() {
public void run() {
Integer notified = null;
try {
notified = waitForAny(integers);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("notified=" + notified);
}
}).start();
synchronized (integers) {
integers.wait(3000);
}
Integer randomInt = integers.get((new Random()).nextInt(POOL_SIZE));
System.out.println("Waking up " + randomInt);
synchronized (randomInt) {
randomInt.notify();
}
}
}