Starting thread in static block - java

I wonder if the following code is OK:
public class MyClass {
...
static {
new MyClass().start();
}
private void start() {
//running the thread
}
}
I must add, I don't have access to something like main method, because this part of code is called from outside.
Does exists more sophisticated way of starting this thread?

Related

Thread safe access to private field

So I have the following scenario (can't share the actual code, but it would be something like this):
public class Test
{
private Object obj;
public void init()
{
service.registerListener(new InnerTest());
}
public void readObj()
{
// read obj here
}
private class InnerTest implements Listener
{
public synchronized void updateObj()
{
Test.this.obj = new Object();
// change the obj
}
}
}
The InnerTest class is registered as listener in a service. That Service is running in one thread the calls to readObj() are made from a different thread, hence my question, to ensure consistency of the obj is it enough to make the UpdateObj() method synchronized?
I would suggest using another object as a lock to ensure that the class only blocks when the obj is accessed:
public class Test
{
private final Object lock = new Object();
private Object obj;
public void init()
{
service.registerListener(new InnerTest());
}
public void readObj()
{
synchronized(lock){
// read obj here
}
}
private class InnerTest implements Listener
{
public void updateObj()
{
synchronized(Test.this.lock){
Test.this.obj = new Object();
// change the obj
}
}
}
}
Then use that lock in all methods that need to have consistent access to obj. In your current example the readObj and updateObj methods.
Also as stated in the comments, using synchronized on the method level in your InnerTest class, will not really work as you probably intended. That is, because synchronized methods will use a synchronized block on the this variable. Which just blocks your InnerTest class. But not the outer Test class.

showing error while im trying to override the run method

package com.jspiders.thread;
public class Mthrd1 extends Thread {
{
#Override
//error line public void run()
{
// TODO Auto-generated method stub
super.run();
}
}
}
This is a valid way to override the run method for creating threads:
class Test extends Thread
{
public void run()
{
System.out.println("Thread Started and is Running");
}
public static void main(String args[])
{
Test t=new Test();
t.start();
}
}
There is also another way to create threads in java by implementing the runnable interface. In you posted code you are calling the run method explicitly whereas, for calling the run method of Thread class you need to call start() method which implicitly calls the run method of Thread, your program is showing error because as you are calling run method explicitly and in your class you have no method called run.

Getting the method that creates runnable from thread which runs the runnable

Suppose I have a custom Thread class which is responsible for running runnables
public class MyThread extends Thread{
public MyThread(Runnable r) {
super(r);
}
#Override
public void run() {
super.run(); // Can I put something here to get info about where the runnable is submitted from?
}
}
Then in some method, I submit the runnable
public void someMethod() {
new MyThread(new Runnable() {
#Override
public void run() {
System.out.println("Blah");
}
});
}
Suppose I have no control over someMethod, can I modify MyThread such that whenever a runnable is submitted to MyThread, I can get info about someMethod (e.g. method name someMethod, class name) ?
Edit
In fact the original question is part of my problem.
I am providing a ThreadFactory that can be used by a threadpool (ExecutorService).
public class MyThreadFactory implements ThreadFactory {
#Override
public Thread newThread(Runnable r) {
return new MyThread(r);
}
}
User can create a threadpool with MyThreadFactory
ExecutorService pool = Executors.newCachedThreadPool(new MyThreadFactory());
By calling pool.execute(runnable), a instance of MyThread will be created to perform the task specified by runnable. It is possible that the thread will be reused by multiple runnables. So I would like to retrieve Method and Class info in the public void run() method of MyThread. Since runnable is stored in a private field in the base Thread class, I cannot use a modified version of the solution provided by Laerte like:
#Override
public void run() {
super.run();
// Not working, Since MyThread cannot access private field target of Thread class
Method m = target.getClass().getEnclosingMethod();
System.out.println(m.toString());
}
Can I still obtain Method and Class about where the runnable is instantiated , at the moment public void run() is invoked?
To know things related to calling methods, class names, and so on, you should use reflection.
In your case, you should modify your code like this.
class MyThread extends Thread{
public MyThread(Runnable r) {
super(r);
Method m = r.getClass().getEnclosingMethod();
System.out.println(m.toString());
}
#Override
public void run() {
super.run();
}
}
The Method class will have the method reference. Using this call Method m = r.getClass().getEnclosingMethod();, you will receive the method that is enclosing the Runnable object. In your case, oneMethod.
That's the idea. Tell me if it helps.

Define method with object instantiation in java

I'm slowly transitioning from C++ to java and I do not understand the following piece of code:
public class TestThread
{
public static void main (String [] args)
{
Thread t = new MyThreads()
{
public void run()
{
System.out.println(" foo");
}
};
t.start();
System.out.println("out of run");
}
}
An object type "MyThreads" is being instantiated, but what does the function "void run" mean?
Why is it written using that syntax right after the object instantiation?
Is that function being overriden?
When is this kind of syntax (where I define a function with an object instantiation) necessary/required? and where is it preferred/useful?
It means that the class MyThreads either require you to first write a method with name run or the way you are doing provides the ability to change the existing run method behaviour where you are declaring.
It is like overriding if run method is already there or creating the method when you want to create object.
This provides the ability to create objects of MyThreads without having to change the original class or creating multiple classes.
public class TestThread
{
public static void main (String [] args)
{
Thread t = new MyThreads()
{
public void run()
{
System.out.println(" foo");
}
};
t.start();
Thread t1 = new MyThreads()
{
public void run()
{
System.out.println(" this time it is somethidn else");
}
};
t1.start();
System.out.println("out of run");
}
}
Little modification to your code shows the advantage of having this feature. If you observe run method of t1 is doing something different than what is in t. So it is now completely new thread.
This code is equivalent to
public class TestThread
{
static class MyThreadSubclass extends MyClass {
public void run() {
System.out.println("foo");
}
}
public static void main (String [] args)
{
Thread t = new MyThreadSubclass();
t.start();
System.out.println("out of run");
}
}
It's just a convenient way of defining a subclass inline, without having to give it a name; it's just syntactic sugar. It's creating an object of a subclass that overrides the method run() from MyThreads.

Inner class runnable in java

say I have a class called "Example"
inside "Example" I have an inner class which is a runnable
I execute the runnable inside "Example"
public class Example {
public Example() {
//executing the runnable here
}
private void a() {
}
public void b() {
}
public class RunMe implements Runnable {
public void run() {
a();
b();
}
}
}
what happens here assuming that Example runs on the main thread?
does a and b run from the RunMe thread or the main thread?
does it matter that a is private and b is public?
You missed out the key piece of code to enable us to answer your question - the constructor.
If your constructor looks like this:
public Example() {
(new Thread(new RunMe())).start();
}
Then a() and b() will run on the thread you just created (the "RunMe" thread as you call it).
However, if your constructor looks like this:
public Example() {
(new RunMe()).run();
}
Then you're not actually running it on another thread (you're just calling a method in another class, it just happens to be called 'run'), and so a() and b() will run on the 'main' thread.
The private/public thing is irrelevant here because RunMe is an inner class so can access even private methods of Example.
If your Example constructor has in it
new Thread(new RunMe()).start()
then a() and b() will run on that thread.
However, they may run before the constructor has finished executing, so their behaviour will be undefined.
Inner class are just some magic kind of extracted/transformed.
public static class Example$RunMe implements Runnable {
// Autocode
private final Example $this;
public RunMe(Example _this){
$this=_this;
}
public void run() {
$this.a(); // even if private
$this.b();
}
}
So the thread you are calling run is the Thread a() and b() are called, it makes no difference if they are public or private.

Categories