Sorry for another vague example...but I have a single class where I'm starting a new thread instance. However, if I add a new thread instance, it interrupts (destroys?) the first.
But, if I run two instances of the class (separately, after I turn them into jar files) where each instance only opens up a single thread, they both run concurrently and fine.
I'm convinced the error is the way I'm implementing multi-threading.
Any suggestions for things to look for? Thanks! Sorry for the vague example.
You cannot assume that an arbitrary class is thread-safe.
Authors of a class should be explicit about the thread-safety of their classes, but it's very common that they do not. Given that environments such as Servlets may be intrinsically mulit-threaded this can be a real problem.
You need to study the class and discover which, if any, methods are thread safe. It is possible that the class InstanceOfClassIDontControl has static variables that are getting confused by multithreaded access. If you not only don't control the class, but can't even see its source then you are going to need the owners support.
Ok, here's an example:
public class driver {
public static void main(String args[])
{
Thread x;
Thread y;
x = new Thread(new pow());
y = new Thread(new pow());
x.start();
y.start();
}
}
public class pow extends Thread {
public void run() {
InstanceOfClassIDontControl a = new InstanceOfClassIDontControl();
a.doVariousProcesses();
}
}
In the example, I (obviously) don't control the class whose instance is created and called in the thread. Each thread may run for minutes. But whenever a concurrent thread is ran (in this case, with y.start()), it destroys the actions of the object called in the run() instance of x.start().
Related
In one of my existing Spring Java code some one has written code like below :
I am not sure why we need to synchronize String class for thread safety. Can anyone suggest?
public class MyTimerTask extends TimerTask{
#Autowired
MyService service;
public void run(){
synchronized(String.class){
service.callSomeMethod();
}
}
}
There is no need to use String.class. You can synchronize on any object, including any Class instance. Using the String class is a poor choice, but it would work.
The reason it's a poor choice is because (a) it's public—your code could interact in unexpected ways with some other part of a large program where some other programmer also decided to write synchronized(String.class)—But more important is (b) it's completely demented. It will make other programmers waste time trying to understand what you did and why you thought it was smart to do it.
There's maybe a third reason (c) but hard to tell without seeing more of your code. Reason (c) would be that String.class is a static instance, and if you're using that one global object to synchronize many different MyTimerTask instances, and if those instances do not interact with each other through shared, static variables, then using the one global synchronization object probably adds an un-necessary performance bottleneck.
This would be better (takes care of reasons (a) and (b)):
public class MyTimerTask extends TimerTask{
private final static Object mutex = new Object();
...
public void run(){
synchronized(mutex){
service.callSomeMethod();
}
}
}
Or, depending on how MyTimerTask is used, removing static from the declaration of mutex might be better still (takes care of reason (c)).
This is a piece of code I am using as an example of how to run multiple threads:
import javax.swing.SwingUtilities;
public class ThreadDem {
//field
Runnable doRun;
//constructor
public ThreadDem(){
//instantiates a runnable object
doRun = new Runnable(){
//have to override the abstract method run of runnable and am
//declaring method here in this block statement
#Override
public void run() {
System.out.println("Hello from thread: "
+ Thread.currentThread());
}
};
}
public static void main (String[] args){
ThreadDem demo = new ThreadDem();
System.out.println("Hello this is from thread: " +
Thread.currentThread());
//I use the invokelater method to invoke the run method of do run on a
//seperate thread
SwingUtilities.invokeLater(demo.doRun);
}
}
I more or less just took it from the docs on runnable. However I am finding it hard to understand why it works like this. I am still new to OOP and don't really understand how I can instantiate an interface(runnable) and if indeed my runnable object is not a class how can I define it a method(run())... can someone please explain to me in simple terms step by step exactly what is happening in that constructor so I can make sense of the process? Thankyou!
What you have created is called an Anonimous class. The link contains the official tutorial which explains what it is, but in a nutshell - you created a one-off class implementing Runnable and instantiated an object of said class.
As a suggestion - Don't try to tackle multithreading before you grasp the basic concepts of the language like OOP and grammar.
In Java interfaces can not be instantiated, they are simply guidelines of what a method must implement in order to implement that interface. In order to instantiate a thread in Java it's best to use
public class ThreadDem extends Runnable (recommended)
or
public class ThreadDem extends Thread.
At that point you're required to implement a "public void run" method that overwrites the empty one from Runnable. At that point you can simply call run on any object of type ThreadDem.
I know three ways of creation threads, tasks in Java. In job interview one guy asked me if it is possible to create thread in Java in other way. Is it is possible? If is, please put some example.
The only way to create a thread in Java is by creating a Thread object and starting it.
Quoting java language specification:
The only way for a user to create a thread is to create an object of this class; each thread is associated with such an object. A thread will start when the start() method is invoked on the corresponding Thread object.
Runnable and Callable are two interfaces that the JDK uses for submitting code to be executed in threads. For example, in its various java.util.concurrent classes.
Runnable, by convention, is an interface accepted for arguments to Thread's constructor. You can extend Thread so that constructors of child class accept any other type of argument. Similary, Callable is accepted by thread pools in java.util.concurrent. You can develop other kinds of thread pools, which accept any other types of tasks.
Creating a thread anonymously. For example as given below :
import java.util.Date;
class TestDemo
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
while(true)
{
System.out.println(new Date());
try
{
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
t.start();
}
}
I just started learning java and I ran into a slight road block involving threads. I have a static method that I would like to run in its own thread, is this possible? In python I know it would look something like this:
import thread;thread.start_new_thread( my_function, () );
And I know how to use threading with non-static methods by implementing Runnable or extending thread, but this is not what I am trying to do.
Have a Thread's run method call the static method:
new Thread(Call::yourStaticMethod).start();
The above would create a Static Method that executes in another Thread:
public static void yourStaticMethod() {
new Thread(new Runnable(){
// This happens inside a different Thread
}).start();
}
You need to create a new Thread.(As far as I understand)
Thread t = new Thread(){
#Override
public void run(){
method();
}
static void method(){// do stuff
}
}
//finally
t.start();
You can always make a class inside a method and pass more arguments to the thread.
You dont need to wrap Runnable with Thread. Use whichever you like, it is the same thing!
The fact that the method is static is of little importance here.
If the static method really does only use local variables, no object fields or methods, then it is thread-safe. If it accesses any object fields or methods, it may not be thread-safe, depending on what those fields or methods are used for, in other code.
You can either create a new thread inside of a static method or other stuff. It depends on what you want to do.
If you are using Java 8+, you can also use Java lambda expresions. Like this:
new Thread(()-> MyApp.myStaticMethod()).start();
So I have been reading a tutorial on Android development, and I have come across something that I have never seen during my Java developing (mainly school work):
Thread th = new Thread() {
public void run() {
if (iotdHandler == null) {
iotdHandler = new IotdHandler();
}
iotdHandler.processFeed(); resetDisplay(
iotdHandler.getTitle(),
iotdHandler.getDate(),
iotdHandler.getUrl(),
iotdHandler.getDescription());
dialog.dismiss();
}
};
th.start();
Now the book says extend thread, and I kind of understand what its doing, in a sense, but it doesn't follow the usual way to extend a normal class in java like so:
public Class Dog extends Animal...
and then you can follow on and override methods and such. But my question is, what is it actually doing in making a reference to new Thread object, but at the same time creating a method right after it, and what I assume is overriding some sort of method in the Thread class? Since I do not know what it is called, I can't really search for it, so I apologize for the obvious question if it is one. Any help would be much appreciated.
Revise your Java books :) It's called an anonymous inner class and was originally introduced to facilitate Java GUI development (with AWT/Swing). Since Android UI development follows many of the same patterns, it is used quite often in Android.
What it does is instantiating a class in place (without defining it in a separate file, etc.), overriding some of its methods (int this case run()). You can also implement an interface this by if you provide implementations for all of its methods.
first of all, that is nothing Android specific. You can extend the same way in "normal Java". The reason for doing an class extend like that is to reduce classes, when this "class extension" is needed only once. In your example it would be the same to write
public class MyThread extends Thread
{
#Override
public void run() {
[...]
}
};
and later on:
MyThread thread = new MyThread();
thread.start();
So the advantage is, that you don't need to implement a class and instantiate it later on.