I am working on a project in which I have multiple interface and two Implementations classes which needs to implement these two interfaces.
Suppose my first Interface is -
public Interface interfaceA {
public String abc() throws Exception;
}
And its implementation is -
public class TestA implements interfaceA {
// abc method
}
I am calling it like this -
TestA testA = new TestA();
testA.abc();
Now my second interface is -
public Interface interfaceB {
public String xyz() throws Exception;
}
And its implementation is -
public class TestB implements interfaceB {
// xyz method
}
I am calling it like this -
TestB testB = new TestB();
testB.xyz();
Problem Statement:-
Now my question is - Is there any way, I can execute these two implementation classes in parallel? I don't want to run it in sequential.
Meaning, I want to run TestA and TestB implementation in parallel? Is this possible to do?
Sure it is possible. You have actually many options. Preferred one is using callable and executors.
final ExecutorService executorService = Executors.newFixedThreadPool(2);
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
executorService.invokeAll(tasks);
This method gives you opportunity to get a result from executions of your tasks. InvokeAll returns a list of Future objects.
final List<Future<String>> futures = executorService.invokeAll(tasks);
for (Future<String> future : futures)
{
final String resultOfTask = future.get();
System.out.println(resultOfTask);
}
You can make your code easier to use if you make your classes implements Callable, then you will reduce amount of code needed to prepare list of tasks. Let's use TestB class as an example:
public interface interfaceB {
String xyz() throws Exception;
}
public class TestB implements interfaceB, Callable<String>{
#Override
public String xyz() throws Exception
{
//do something
return "xyz";
}
#Override
public String call() throws Exception
{
return xyz();
}
}
Then you will need just
Lists.newArrayList(new TestB(), new TestA());
instead of
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
Whats more, executors gives you power to maintain and reuse Thread objects which is good from performance and maintainability perspective.
Create Two Thread and run two implementation parallely. Code snippet -
ThreadA{
public void run(){
TestA testA = new TestA();
testA.abc();
}
}
...
ThreadB{
public void run(){
TestB testB = new TestB();
testB.xyz();
}
}
Start this two thread from main method -
public static void main(String[] args){
new ThreadA().start();
new ThreadB().start();
}
Try this one
Collect all the classes of same interface and call them in Multi threading.
Use Callback mechanism to get the result back
import java.util.ArrayList;
import java.util.List;
public class Demo123 {
public static void main(String[] args) {
List<InterfaceA> a = new ArrayList<InterfaceA>();
List<InterfaceB> b = new ArrayList<InterfaceB>();
TestA testA = new TestA();
TestB testB = new TestB();
a.add(testA);
b.add(testB);
for (final InterfaceA i : a) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.abc());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
for (final InterfaceB i : b) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.xyz());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
interface MyCallback {
public void callback(String value);
}
interface InterfaceA extends MyCallback {
public String abc() throws Exception;
}
class TestA implements InterfaceA {
#Override
public String abc() throws Exception {
return "abc";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
interface InterfaceB extends MyCallback {
public String xyz() throws Exception;
}
class TestB implements InterfaceB {
#Override
public String xyz() throws Exception {
return "xyz";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
You may try it like this:
public static void main(String[] args) throws InterruptedException {
Executors.newCachedThreadPool().invokeAll(Arrays.asList(
new Callable<String>() {
#Override public String call() { return new TestA().abc(); }
},
new Callable<String>() {
#Override public String call() { return new TestB().xyz(); }
}));
}
public interface InterfaceA {
public String abc() throws Exception;
}
public interface InterfaceB {
public String xyz() throws Exception;
}
class TestA implements InterfaceA {
#Override public String abc() {
System.out.println("Inside A"); return null;
}
}
class TestB implements InterfaceB {
#Override public String xyz() {
System.out.println("Inside B"); return null;
}
}
Related
How can I determine whether a method is running in another method ?
This is my way.
However, there may be some performance problems.
public class Main {
public static final ThreadLocal<Object> THREAD_LOCAL = new ThreadLocal<>();
public static void main(String[] args) {
f1();
foo(i -> f1());
}
public static void f1() {
Object o = THREAD_LOCAL.get();
if (o == null) {
System.out.println("not in foo");
} else {
System.out.println("in foo");
}
}
public static void foo(Handler<Integer> handler) {
new Thread(() -> {
THREAD_LOCAL.set(new Object());
handler.handle(10);
}).start();
}
public interface Handler<A> {
void handle(A a);
}
}
Is there a better way?
Do not use threads ?
I was going through Handlers, the post method in it accepts a parameter of type Runnable. There's a following code snippet I came across
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
timeView.clearComposingText();
Integer hours = seconds/3600;
Integer minutes = (seconds % 3600)/60;
Integer secs = seconds % 60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
Now since Runnable is an Interface in Java, how are we able to create a new instance of Runnable directly?
Anonymous classes can implement interfaces, and that's the only time you'll see a class implementing an interface without the "implements" keyword.
A complete example might look like:
public class MyClass {
public interface A {
void foo();
}
public interface B {
void bar();
}
public interface C extends A, B {
void baz();
}
public void doIt(C c) {
c.foo();
c.bar();
c.baz();
}
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.doIt(new C() {
#Override
public void foo() {
System.out.println("foo()");
}
#Override
public void bar() {
System.out.println("bar()");
}
#Override
public void baz() {
System.out.println("baz()");
}
});
}
}
The output of this example is:
foo()
bar()
baz()
I am trying to create a new thread process, after thread process ends i want to get a result from that class.how can i do it?
For example this two classes. Lets say abThread class returns String array. How should I get those String values.
Class A{
public static void main(String[] args){
abThread bb=new abThread();
bb.start();
// when bb.run() returns data catch it
}
}
Class abThread extends Thread{
public void run(){
**// do smth here**
// then return result to the main Class
}
}
What you are looking for is a Callable like so:
public class MyCallable implements Callable<String[]>
{
#Override
public String [] call() throws Exception
{
//Do your work
return new String[42]; //Return your data
}
}
public static void main(String [] args) throws InterruptedException, ExecutionException
{
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<String[]> future = pool.submit(new MyCallable());
String[] myResultArray = future.get();
}
What is the preferred mechanism for verifying the effects of a callback in Jmockit?
For example, assume I have this class.
class ResultGenerator {
AsyncLauncher asyncLauncher = new AsyncLauncher();
public void getResultAsync(final ResultSignal resultSignal) {
asyncLauncher.getResult(new FutureCallback<Result>() {
#Override
public void onSuccess(#Nullable Result result) {
resultSignal.success(result);
}
#Override
public void onFailure(Throwable t) {
resultSignal.failure();
}
});
}
}
How do I verify resultSignal.success(result) when writing a test for ResultGenerator#getResultAsync?
For example
#RunWith(JMockit.class)
public class ResultGeneratorTest {
// Synchronous invocation, mocked AsyncLauncher
#Test
public void testGetResultAsync(#Mocked final ResultSignal resultSignal, #Mocked final Result result) throws Exception {
new MockUp<AsyncLauncher>() {
#Mock
void getResult(FutureCallback<Result> futureCallback) {
futureCallback.onSuccess(result);
}
};
ResultGenerator resultGenerator = new ResultGenerator();
resultGenerator.getResultAsync(resultSignal);
new Verifications() {{
resultSignal.success((Result) any); times = 1;
resultSignal.failure(); times = 0;
}};
}
// Asynchronous invocation, real AsyncLauncher in use
#Test
public void testGetResultAsyncDelayed(#Mocked final Result result) throws Exception {
final AtomicBoolean latch = new AtomicBoolean(false);
MockUp<ResultSignal> resultSignalMockUp = new MockUp<ResultSignal>() {
#Mock(invocations = 1)
public void success(Result result) {
latch.set(true);
}
#Mock(invocations = 0)
public void failure() {
latch.set(true);
}
};
ResultGenerator resultGenerator = new ResultGenerator();
final ResultSignal resultSignal = resultSignalMockUp.getMockInstance();
resultGenerator.getResultAsync(resultSignal);
Awaitility.await().untilTrue(latch);
}
}
Couple of notes:
ResultGenerator is your SUT (System Under Test) and you should not mock internals
ResultSignal is a test collaborator, so it is natural to mock it out
because you can verify the functionality as such, the only "correct" solution from unit testing theory is to mock out the collaborator
You have to be sure that you handle timeout correctly, otherwise the test might never end
so one possible solution is:
#Test
public void getResultAsync_ShouldNotifyResultSignal() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
ResultGenerator generator = new ResultGenerator();
generator.getResultAsync(new MyResultSignal(latch));
assertTrue(latch.await(1, SECONDS));
}
private static final class MyResultSignal implements ResultSignal {
private final CountDownLatch latch;
private MyResultSignal(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void success(Result result) {
latch.countDown();
}
#Override
public void failure() {}
}
I have a class like this , where I am updating a static variable in a thread. And I need to access this variable from another class.
import java.util.ArrayList;
import java.util.List;
public class VariableUpdater implements Runnable {
static List < String > abc = new ArrayList < String > ();
private static VariableUpdater instance = null;
private VariableUpdater() {}
public static synchronized VariableUpdater getInstance() {
if (instance == null) {
instance = new VariableUpdater();
}
return instance;
}
public static void main(String[] args) {
Thread th = new Thread( VariableUpdater.getInstance());
th.start();
}
#Override
public void run() {
while (true) {
System.out.println();
try {
abc.add("aa");
Thread.sleep(1000);
printContent();
} catch (Exception e) {
// TODO: handle exception
}
}
}
public synchronized void printContent() {
for (String string: abc) {
System.out.println(string);
}
}
}
And this variable needs to be accessed from another class like this :
public class Accessor {
public static void main(String[] args) {
VariableUpdater.getInstance().printContent();
}
}
The problem is, when running the Accessor class the list is empty.
Am I missing something here?
UPDATE/Solution
It turns out we can achieve this by using Hazelcast or some sort of messaging/caching utility. I will post a full solution soon.
Source: How to share object between java applications?
From this code u can access the List in another class object
import java.util.ArrayList;
import java.util.List;
public class VariableUpdater implements Runnable {
static List < String > abc = new ArrayList < String > ();
private static VariableUpdater instance = null;
private VariableUpdater() {}
public static synchronized VariableUpdater getInstance() {
if (instance == null) {
instance = new VariableUpdater();
}
return instance;
}
public static void main(String[] args) {
Thread th = new Thread(new VariableUpdater());
th.start();
Accessor.print();
}
#Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println();
try {
abc.add("aa");
// Thread.sleep(1000);
//printContent();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void printContent() {
System.out.println("List :: " + abc);
}
}
class Accessor {
public static void print() {
System.out.println("Accessor");
VariableUpdater.getInstance().printContent();
}
}
You have two main() methods in two different classes. On running two main() methods there will be two instances of JVM and those do not share anything. So your list will always be empty.
Use one main() method to start threads.
public class Main{
//shared state
public static void main(String[] args){
VariableUpdator variableUpdatorInstance = ...
Accessor accessorInstance = ...
variableUpdatorInstance.start();
accessorInstance.start();
//or in your case
new Thread(new VariableUpdater()).start();
Thread.sleep(9000); //runs eventually after 9 seconds
Accessor.print();
}
}
UPDATE:
class Thread1 extends Thread{
static List<String> list = new ArrayList<String>();
}
class OtherClass{
public void someMethod(){
Thread1.list; //this is how you access static variable of one class in other
}
}