Is there an elegant way to do that? Or it can always be avoided because one can use a better design patter?
import java.util.ArrayList;
import java.util.List;
public class ForTest {
List<String> ls = new ArrayList<String>();
public static void main(String[] args) {
ForTest forTest=new ForTest();
System.out.println(forTest.ls.size());
new Thread(new Worker(forTest.ls)).start();
//size() does not change at all
System.out.println(forTest.ls.size());
}
}
class Worker implements Runnable{
List<String> list;
public Worker(List<String> li) {
this.list = li;
}
public void run(){
this.list.add("newItem");
}
}
There are several issues with your code (in particular you use ArrayList which is not thread safe without proper synchronization).
But the most obvious one is that the second println statement is almost always going to be called before your run method has had a chance to be executed.
You need to make your main thread sleep() for a while. The size() is getting called before the new Thread gets a chance to update it.
new Thread(new Worker(forTest.ls)).start();
Thread.sleep(2000);
System.out.println(forTest.ls.size());
An even better way would be to join() on to the worker thread. This would make the main thread automatically wake up when the worker is finished.
Thread worker = new Thread(new Worker(forTest.ls));
worker.start();
worker.join();
System.out.println(forTest.ls.size());
In addition to that make use of a synchronized ArrayList to prevent a race condition if the List would be shared and modified by multiple threads.
List<String> ls = Collections.synchronizedList(new ArrayList<String>());
You seem to be missing the idea of Threading. Your code will not work because your worker has likely not updated ls by the time you print it. If you're using threading, the threads need to communicate state. This is all quite complex, I suggest you read the java tutorials on threading http://docs.oracle.com/javase/tutorial/essential/concurrency/
Please note that ArrayList is not synchronized, but Vector is. You cannot expect the worker to run just a moment after you started its thread. That's why the list size is not changed yet. I guess this is not your complete example, so it is difficult to help you. (If this was your complete example I would wonder why you bother implementing a multi-threaded solution.)
For knowing when the worker finished you could join the threads.
wait for the new thread to actually start running your code + make forTest final to be able to access it (also use a thread-safe collection - best non-synchronous a.k.a. non-blocking) e.g.
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ForTest {
Collection<String> ls = new ConcurrentLinkedQueue<String>();
public static void main(String[] args) throws InterruptedException {
final ForTest forTest = new ForTest();
System.out.println(forTest.ls.size());
int threads = 10;
for ( int i=0; i<threads; i++ ) {
new Thread(new Runnable() {
#Override
public void run() {
forTest.ls.add("newItem");
}
}).start();
}
Thread.sleep(1000);// wait for it !
System.out.println(forTest.ls.size()); // 10 unless your threads are really slow
}
}
Related
I am pretty new to using multithreading, but I want to invoke a method asynchronously (in a separate Thread) rather than invoking it synchronously. The basic idea is that I'm creating a socket server with an object in memory, so for each client I will have to run something like object.getStuff() asynchronously.
The two constructs I found were:
having the class implement Runnable and threading this and
declaring a runnable class within a method.
Additionally this method needs a return value- will it be necessary to use Executor and Callable to achieve this? Could someone point me in the right direction for implementing this?
I have tried implement option 2, but this doesn't appear to be processing concurrently:
public class Test {
private ExecutorService exec = Executors.newFixedThreadPool(10);
public Thing getStuff(){
class Getter implements Callable<Thing>{
public Thing call(){
//do collection stuff
return Thing;
}
}
Callable<Thing> callable = new Getter();
Future<Thing> future = exec.submit(callable);
return future.get();
}
}
I am instantiating a single test object for the server and calling getStuff() for each client connection.
Threading Tutorial
The Java tutorial on concurrency has a good section on this. It's at https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html. Essentially, you can either implement Runnable or Callable, or inherit from Thread.
Subclassing Thread
You can write a class, including an anonymous inner class, that extends Thread. Instantiate it, then invoke the start() method.
public class MyThread extends Thread {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
}
}
Implementing Runnable
You can write a class that implements Runnable, then wrap an instance in a Thread and invoke start(). Very much like the previous.
public class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
(new Thread(r)).start();
}
}
Return Value
Runnable doesn't allow for return values. If you need that, you need to implement Callable instead. Callable looks a lot like Runnable, except you override the call() method instead of the run() method, and you need to give it to an ExecutorService.
public class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println("A thread using Callable<Integer>");
return 42;
}
public static void main(String[] args) {
MyCallable c = new MyCallable();
Future<Integer> f = Executors.newSingleThreadExecutor().submit(c));
System.out.println("The thread returned: " +
f.get());
}
}
The two constructs I found were 1) having the class implement Runnable and threading 'this' and 2) declaring a runnable class within a method.
Option (2) probably is better. Most programs would be improved if they had more classes, not fewer. Each named entity in a program—each package, class, method, whatever—should have just one responsibility. In your option (1), you are asking the class to do two things.
For your option (2), you don't actually have to declare a whole class. You can either use an anonymous inner class, or if you can go with Java8 all the way, you can use a lambda expression. Google for either one to learn more.
Additionally this method needs a return value.
The classic way, is for the Runnable object to return the value through one of its own fields before the thread terminates. Then the parent thread, can examine the object and get the return value afterward.
Will it be necessary to use Executor and Callable to achieve this?
Necessary? A lot of people think that ExecutorService is a Good Thing.
Sounds like you are creating a server that serves multiple clients. Do these clients continually connect and disconnect? The advantage of using a thread pool (i.e., ThreadPoolExecutor) is that it saves your program from continually creating and destroying threads (e.g., every time a client connects/disconnects). Creating and destroying threads is expensive. If you have a lot of clients connecting and disconnecting, then using a thread pool could make a big difference in the performance of your server.
Creating and managing threads by yourself is generally bad approach.
As you already pointed - use Executors utility class to create executor and submit Callables to it.
public class RunWResult implements Runable{
private volatile ResultType var;
//the thread method
public void run(){
...
//generate a result and save it to var
var = someResult();
//notify waiting threads that a result has been generated
synchronized(this){
notify();
}
}
public ResultType runWithResult(){
//run the thread generating a result
Thread t = new Thread(this);
t.start();
//wait for t to create a result
try{
wait();
}catch(InterruptedException e){}
//return the result
return var;
}
}
This code is from Effective Java (Item 66): (without sync or volatile this never ends)
public class ThreadPractice {
static boolean canrunstatic;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!canrunstatic){i++;}
System.out.println("finished");
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
canrunstatic = true;
}
As Bloch mentioned in that chapter it will never write "finished" to the console. I've been playing around with this class, and add that line to the runnable run method:
System.out.println("im still running");
With this the while loop doesn't only increment i but prints out this string in every loop. But what drives me crazy, that this way the thread stops after 1 sec, when main thread comes back from sleep.
modified: (stops without volatile/sync)
public class ThreadPractice {
static boolean canrunstatic;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!canrunstatic){i++;System.out.println("im still running");}
System.out.println("finished");
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
canrunstatic = true;
}
So what is the logic behind this?
Precisely, it is just not guaranteed that the thread will ever stop, but it is not forbidden that it does stop. The logic behind this is provided by the Java Memory Model, which is a rather complicated topic, but needed in order to understand Multithreading in Java.
The concept is that a write to a non-volatile field of one thread is only required to be seen by another thread if these two actions synchronize with each other. A compiler is allow to reorder some actions if the behavior exhibited by the thread it is executed in does not change. But another thread might see this. So you need proper synchronization in order to tell the compiler that reordering is not allowed in some parts.
Read the full paper about this here: JSR-133
Writing data to the console is often implemented a thread safe operation.
In that case your act of writing data to the console can also trigger updating of the canrunstatic variable as seen by your backgroundThread.
Note that this is not promised by the Java Memory Model, nor by the implementation of java System.out
If have a class implementing runnable class with following code:
public class MyRunnable implements Runnable {
public Thread t;
// Other variables;
public MyRunnable() {
t = new Thread(this, "MyRunnable Thread");
// Initialise other variables.
}
public void run() {
//Do something.
}
}
And i am making an instance of the above class in the following way:
public class MyFunc () {
satic void main (String ards[]) {
MyRunnable mr = new MyRunnable();
mr.t.start();
while (true) {
Thread.sleep(10000);
if (!mr.isAlive()) {
//Execute mr again.
// How to do it ?
}
}
}
}
How should i do it?
I have two ways in mind, but not sure which one is correct:
1. mr.t.start();
2. MyRunnable mr = new MyRunnable();
mr.t.start();
Should i make a new instance of mr?
Or should i work with the existing instance or mr ?
Remove reference to Thread from MyRunnable.
Starting thread idiom in Java looks like this
new Thread(new MyRunnable()).start()
Normal rules of garbage collection applies to cleaning runnables. If no object references runnable it may be garbage collected.
There are several idioms around writing multi-threaded code in Java, see the Java tutorials. Keep it simple and separate:
public class YourTask implements Runnable {
#Override
public void run() {
// do something
}
}
A minimal example application:
public class YourApp {
public static void main(final String[] args) throws InterruptedException {
final YourTask yourTask = new YourTask();
final Thread thread = new Thread(yourTask);
thread.start();
thread.join();
}
}
Be careful with concurrency - you shouldn't use this code in production until you have a proper understanding, for example by reading Java Concurrency in Practice.
Runnable has the method run(), so you do not need separate Thread inside that.And nothing gets destroyed unless if you go out from the context of your variable (object) definition and you loose the reference.
http://www.javamex.com/tutorials/threads/thread_runnable_construction.shtml
I don't like this code.
Your Runnable shouldn't have a Thread member, public or private. I'd recommend removing it. Think simple: separation of concerns. This is what your Runnable ought to look like:
public class MyRunnable implements Runnable {
public void run() {
//Do something.
}
}
That's it. Let other classes that know how to run things handle that part.
You're better off looking at the newer concurrent package classes, like Executor.
You shouldn't be trying to do a lot of multi-threaded programming unless you've read Brian Goetz' "Java Concurrency In Practice" and understood it thoroughly. You're less likely to run into trouble.
I Want to execute a Certain Task to take only 1000 MS , if it exceeds , i dont want to continue with the task ,
i have used join for this .
Please tell me and guide me if this is correct or not
import java.util.List;
public class MainThread {
public static void main(String args[]) throws InterruptedException {
Thread mainthread = Thread.currentThread();
ChildThread child = new ChildThread();
Thread childThread = new Thread(child);
childThread.start();
mainthread.join(1000);
List list = child.getData();
if(list.size()<0)
{
System.out.println("No Data Found");
}
}
}
ChildTHread
import java.util.ArrayList;
import java.util.List;
public class ChildThread implements Runnable
{
List list = new ArrayList();
public List getData() {
return list;
}
public void run() {
// This List Data is feteched from Database currently i used some static data
list.add("one");
list.add("one2");
list.add("one3");
}
}
Nope. Incorrect. You do not need MainThread at all, you should call childThread.join(1000) instead.
But there is a problem with this approach as well - it will mean that the child thread will anyhow continue to be running.
Therefore you should call also childThread.interrupt() after join:
childThread.join(1000);
childThread.interrupt();
and in your child thread periodically in your childThread perform something like that:
if (interrupted()) {
return;
}
and handle InterruptedException where needed - usually around any wait() methods you have.
Interrupting a thread is the more common (and better) approach. If you want the task to execute for at most 1 second and then stop, use Thread.interrupt(), otherwise the thread will continue to run. It is important to note that depending on how your actual code is structured, you may need to propagate the interrupt.
EXAMPLE
public class Demo {
public static void main(String[] args){
final List<String> list = new ArrayList<String>(3);
final Thread t = new Thread(new Runnable(){
#Override
public void run() {
synchronized(list){
list.add("one");
list.add("one2");
list.add("one3");
}
}
}, "DemoThread");
t.start();
try {
t.join(1000);
t.interrupt();
} catch (InterruptedException e) {
// handle exception
}
synchronized(list){
if(list.isEmpty()){
System.out.println("No data found");
}else{
System.out.println(list);
}
}
}
}
No, this will not work, because this code will wait for one second, and if the thread is not finished, it will just go on. The thread will continue to run. Call thread.interrupt() to interrupt the thread, or close the connection so that it throws an exception and stops the thread, and then join on the thread.
yup that's the way, the only problem i see is in ChildThread list, i suggest you to use synchronized method like this so that you won't have race conditions
List list = Collections.synchronizedList(new ArrayList());
also if you want the running thread to be stoped if it's execution time exceeded 1000 ms i suggest you to use interrupt method of Thread object and don't forget to catch interrupt exception in child thread so you won't have unnecessary exceptions in log
I have one Runnable that is used by more than one thread:
Runnable myRunnable = new MyWorker();
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
How can I get all threads that are created with myRunnable?
(Of course the example is simplified. I create new threads with myRunnable on several places in different classes.)
Use case (as requested): MyWorkerOfMyPage is a delayed worker that is bound to a page. If the user leaves this page (e.g. by navigating to another page) all threads that belong to MyWorkerOfMyPage should be killed ungracefully as their result is not needed anymore.
As already said best way is to track this yourself. This forces you to get a clear understanding of what you are doing. A good thing if you work with threads ... hmmm ... a good thing in every case ;).
But if you realy want to detect the threads you can use reflection with the Thread class to get the required information. First make the method "getThreads" accessible to get all running Threads, then make the field "target" accessible to get the runnables of the Threads.
Heres an example program (but I would advise against the usage in a real application. You should now what threads you are starting, it might harm compability with future JDKs, might harm portability ...):
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Runnable myRunnable = new Runnable() {
#Override
public void run() {
try {
System.out.println("Start: " + Thread.currentThread().getName());
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
List<Thread> threads = getThreadsFor(myRunnable);
for (Thread thread : threads)
System.out.println("Found: " + thread.getName());
}
private static List<Thread> getThreadsFor(Runnable myRunnable) throws Exception {
Method getThreads = Thread.class.getDeclaredMethod("getThreads");
Field target = Thread.class.getDeclaredField("target");
target.setAccessible(true);
getThreads.setAccessible(true);
Thread[] threads = (Thread[]) getThreads.invoke(null);
List<Thread> result = new ArrayList<Thread>();
for (Thread thread : threads) {
Object runnable = target.get(thread);
if (runnable == myRunnable)
result.add(thread);
}
return result;
}
}
The best way to do this is to track this yourself. Use a global singleton for instance that launches the threads and track which ones you started.
Although my first thoughts are along #Bengt's lines, perhaps you could use Class.isAssignableFrom if you had a list of runnables and you just want to know which ones use your interface.
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html
In Java there is no simple way to find all the places a object is referenced, its something you have to maintain a collection of yourself.
If you want to know this staticly you can Find Usages in your ide.
If you want to know this dynamically you can have the Runnable add the Thread to a collection (and remove it when finished)
Generally speaking, the developer should only create Threads deliberately. i.e. the Developer should know when he/she is creating thread and what those threads will be doing. Its not something you should be trying to track at runtime if you have a good design.