Accesing an instance of Class from another class - java

Im writing a project using an API .
So overall my program looks like so .
public class Programm extends bridge {
Client Eclient = new Client() ;
public static void main(String[] args) {
Programm MyProgramm = new Programm();
MyProgramm.MyMethod();
public void MyMethod(){
Runnable countdown = new flipper();
Thread worker = new Thread(countdown);
worker.start();
}
}
abstract bridge implements API{}
class flipper implements runnable {
public void run(){MyProgramm.Eclient.ApiMethod()}
}
Basiclly i need to access the EClient class instance as it would be accesed by MyProgramm instance from class flipper

Option 2: Make Flipper an inner class
public class Program extends bridge {
Client eClient = new Client() ;
public void main(String[] args) {...}
public void myMethod(){...}
class Flipper implements Runnable {
public void run(){Program.eClient.apiMethod()}
}
}

class flipper implements Runnable {
private ESocket lEClient;
public flipper (Object pEClient) {
lEClient = pEClient;
}
And then you call use the constructor like this:
public void MyMethod()
{
Runnable countdown = new flipper(Eclient);
Thread worker = new Thread(countdown);
worker.start();
}
public void run() {lEClient .Apimethod()}

Related

Java Runnable without static reference

I am trying to learn multi-threading using the runnable interface but I am having some trouble figuring out how to pass information. Basically, in the example below, I want to remove the static reference from the Hashmap but if I do that, the program breaks. How do I pass the hashmap to the runnable interface class without using the static keyword?
public class ThreadDemo {
static HashMap <String, Integer>map = new HashMap<>();
public String Hi() {
return "hi";
}
public String Hello() {
return "Hello";
}
public void addToMap(String item) {
if (map.containsKey(item)) {
map.put(item, map.get(item) + 1);
} else {
map.put(item, 1);
}
}
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> all = new ArrayList<>();
for (int i = 0; i < 50; ++i) {
threader threader = new threader();
all.add(new Thread(threader));
}
for (Thread thread : all) {
thread.start();
}
for (Thread thread : all) {
thread.join();
}
ThreadDemo td = new ThreadDemo();
System.out.println(td.map);
}
}
And a class that implements Runnable
public class threader implements Runnable {
ThreadDemo td = new ThreadDemo();
#Override
public void run() {
synchronized(td.map) {
td.addToMap(td.Hi());
td.addToMap(td.Hello());
}
}
}
A class instance is all about information.
public class threader implements Runnable {
final private ThreadDemo td;
public threader(ThreadDemo td) {
this.td = td;
}
#Override
public void run() {
..
}
}
then to use (details omitted, just the idea):
ThreadDemo theTd = new ThreadDemo();
for (...) {
threader threader = new threader(theTd);
all.add(new Thread(threader));
}
....
Of course, all threads are using the same ThreadDemo, with the same map, so you'll need to ensure access is interlocked in some way, e.g., by using synchronized. The ThreadDemo.addToMap method should be synchronized in this example, rather than the caller of addToMap. This puts the responsibility for the "care of the map" into the place that actually owns the map, and is consequently a better design.
I chose to share the ThreadDemo rather than just the map inside the ThreadDemo, since it looks to me that the intent of ThreadDemo is just to be a wrapper around the map.

How to determine whether java class is anonymous?

I have such code:
package x.y.z;
public class Test
{
private static class MyRunnable implements Runnable
{
#Override
public void run()
{
System.out.println("World");
}
}
public static void main(String[] args)
{
final Runnable r1 = new Runnable() {
#Override
public void run()
{
System.out.println("Hello");
}
};
final Runnable r2 = new MyRunnable();
r1.run();
r2.run();
}
}
I am working on some code analysis module, and I want to prove that r1 is an anonymous class instance and r2 is not. Both of them are valid objects having the same base class or an interface. How can I do this?
Refinement: All classes are being loaded, so I do not need to analyze the text.
There's the isAnonymousClass method on Class, so:
if (r1.getClass().isAnonymousClass()) {
// ...

Objects and getting parents methods

Here is the best way I could summarise my situation:
Class1 makes new Thread(new Class2)
Is there a way from inside objects 2 code I can access non-static public methods from object 1?
Not sure if I have explained myself enough but I can answer any questions that could help describe it better
Edit: To elaborate Class1 is a multithreaded server and Class2 is the WorkerClass and i want to access Class1.stop() to stop the server from inside the workerClass
There are at least 3 ways to do this:
(1) Use an anonymous inner class:
public class Class1 {
public void foo() {}
public void bar() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
foo();
}
});
}
}
(2) Use a named inner class:
public class Class1 {
public void foo() {}
public void bar() {
Thread t = new Thread(new MyRunnable());
}
private class MyRunnable implements Runnable {
#Override
public void run() {
foo();
}
}
}
(3) Pass this to the constructor of another top-level class:
public class Class1 {
public void foo() {}
public void bar() {
Thread t = new Thread(new MyRunnable(this));
}
}
class MyRunnable implements Runnable {
private Class1 class1;
public MyRunnable(Class1 class1) {
this.class1 = class1;
}
#Override
public void run() {
class1.foo();
}
}

Passing a Runnable object to a class extending Thread class and then starting it prints unexpected result

I heard about an interview question from one of my friend.
What happens when we pass a Runnable object to an object of a class extending Thread class and start the class.
public class A extends Thread {
Runnable obj;
public A(Runnable obj) {
this.obj=obj;
}
public void run() {
System.out.println("Printing A")
}
}
public class B implements Runnable {
public void run() {
System.out.println("Printing B");
}
}
public class MainApp {
public static void main() {
B b = new B();
A a = new A(b);
a.start();
}
}
Now it outputs Printing A
I was expecting Printing B as it is a perfect analogy to
Thread obj = new Thread(Runnable runnableObj)
Can someone please explain me this weird output??
Thread has a run method which essentially calls runnable.run(). Except that in your class A you have overriden that method to do something else.
So runnable.run() is not called any longer...
You are creating an instance of class A (Now it is a Thread).
Then you are calling start() of that Thread using instance a.
You are just passing a Runnable object as a normal instance variable to class A.
There is nothing complicated in that.
The result is normal.
With a tiny adjustment your code runs as expected.
public class A extends Thread {
Runnable obj;
public A(Runnable obj) {
this.obj = obj;
}
public void run() {
System.out.println("Printing A");
obj.run();// <---- I added this.
}
}
public class B implements Runnable {
public void run() {
System.out.println("Printing B");
}
}
public void test() {
B b = new B();
A a = new A(b);
a.start();
}
The problem is that you are overriding the run() method on Thread and never pass the Runnable obj to super(). Try this:
public class A extends Thread {
public A(Runnable obj) {
super(obj);
}
public class B implements Runnable {
public void run() {
System.out.println("Printing B");
}
}
public void test() {
B b = new B();
A a = new A(b);
a.start();
}
}

How to send message to a static handler?

I had to declare a static handler because of some Java nonsense with leaks.
static class ParsingCompleteHandler extends Handler {
private final WeakReference<BackupActivity> mTargetActivity;
ParsingCompleteHandler(BackupActivity targetActivity) {
mTargetActivity = new WeakReference<BackupActivity>(targetActivity);
}
#Override
public void handleMessage(Message msg) {
BackupActivity targetActivity = mTargetActivity.get();
targetActivity.updateDialog();
}
};
Elsewhere in the code (inside a runnable) I was trying to sendEmptyMessage() to this handler
Runnable runnable = new Runnable() {
#Override
public void run() {
lastBackupDataObject = getBackupDataObjectFromFile(file);
parsingCompleteHandler.sendEmptyMessage(0);
}
};
Thread parsingThread = new Thread(runnable);
parsingThread.start();
but since the sendEmptyMessage() method is not static (and the handler now is), obviously I can't do it. And I need to send a message to the handler because that's what it's there for. How do I do it?
You can do this by making your handler object as class global object and than call this message this should work
eg.
public class SomeClass{
ParsingCompleteHandler parsingCompleteHandler;
static class ParsingCompleteHandler extends Handler {
private final WeakReference<BackupActivity> mTargetActivity;
ParsingCompleteHandler(BackupActivity targetActivity) {
mTargetActivity = new WeakReference<BackupActivity>(targetActivity);
}
#Override
public void handleMessage(Message msg) {
BackupActivity targetActivity = mTargetActivity.get();
targetActivity.updateDialog();
}
};
than do
Runnable runnable = new Runnable() {
#Override
public void run() {
lastBackupDataObject = getBackupDataObjectFromFile(file);
parsingCompleteHandler.sendEmptyMessage(0);
}
};
Thread parsingThread = new Thread(runnable);
parsingThread.start();

Categories

Resources