I'm having a trouble with Runnable and Thread implementations. I have this abstract class, that can not be modified:
abstract class Ordenador {
...
protected Ordenador(String nombre, int[] array) {
...
}
protected void escribir() {
...
}
protected abstract void ordenar();
}
And this sort algorithm that inherit from the class above and implements the run() method, which call the sorting one.
class Burbuja extends Ordenador implements Runnable {
protected Burbuja(String nombre, int[] array) {
super(nombre, array);
}
protected void ordenar() {
....
}
public void esperar() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public void run() {
this.ordenar();
}
}
Finally I have my main class that creates a random array and create a new Burbuja object that sort the array. The problem is that when calling b.join() the array stay the same so de ordenar() method doesn't get called.
class Aplicacion {
public static void main(String[] args) {
...
Burbuja burbuja = new Burbuja("Burbuja", array);
Thread b = new Thread(burbuja);
...
try {
b.join();
s.join();
... more sorting algorithms...
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
System.out.println("");
burbuja.escribir();
}
}
I tried modificating some parts of the code but doesn't work neither.
You have to call the start() method on your thread object
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Your Thread b = new Thread(burbuja); is right, but you forget to call the start method, b.start();
Related
I'm sending more than 1 request to a web service, below there is an example of that requests. Its important for my application to get the answer from the web service so if there is an exception application will try couple of times to get the answer.
Because of that getting something simple like
deviceList = serviceAdapter.getDevices(); is turn into below code.
boolean flag = true;
int counter = 1;
List<Device> deviceList = null;
while (flag) {
try {
deviceList = serviceAdapter.getDevices();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
}
}
}
And in my application i have lots of requests which means there will be more ugly codes. Is there a way where i will call my request methods as parameter for another method something like this:
deviceList = wrapperMethod(serviceAdapter.getDevices());
Problem is there will be different type of requests, so they will return different type objects (list,array,string,int) and their paramaters will change. Is there a suitable solution in java for this problem?
You can pass a Supplier<T> to the wrapperMethod:
public static <T> T wrapperMethod (Supplier<T> supp) {
boolean flag = true;
int counter = 1;
T value = null;
while (flag) {
try {
value = supp.get();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
}
}
}
}
And call it with:
List<Device> deviceList = wrapperMethod (() -> serviceAdapter.getDevices());
I'm afraid, though, that it will limit the methods you call within the lambda expression to throw only RuntimeExceptions.
You can use some command implementation to execute some specific codes :
Here is a simple example of a command
interface Command{
void run();
}
And a couple of implementations :
class SayHello implements Command{
#Override
public void run() {System.out.println("Hello World");}
}
class KillMe implements Command{
public void run() { throw new RuntimeException();};
}
All we have to do to execute those method is to receive an instance of Command and run the method :
public static void execCommand(Command cmd) {
cmd.run();
}
And to use this
public static void main(String[] args) {
execCommand(new SayHello());
execCommand(new KillMe());
}
Hello World
Exception in thread "main" java.lang.RuntimeException
It also accepts lambda expression :
execCommand(() -> System.out.println("Say goodbye"));
And method reference :
public class Test{
public static void testMe() {
System.out.println("I work");
}
}
execCommand(Test::testMe);
Note that I didn't specify that this could throw Exception so I am limited to unchecked exception like RuntimeException but of course void run() throws Exception could be a solution. That way you can do what ever you want.
Full example (with exceptions) :
public class Test {
public static void main(String[] args) {
try {
execCommand(new SayHello());
execCommand(() -> System.out.println("Say goodbye"));
execCommand(Test::testMe);
execCommand(new KillMe());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testMe() throws IOException{
System.out.println("I work");
}
public static void execCommand(Command cmd) throws Exception {
cmd.run();
}
}
interface Command{
void run() throws Exception;
}
class SayHello implements Command{
#Override
public void run() {System.out.println("Hello World");}
}
class KillMe implements Command{
public void run() { throw new RuntimeException();};
}
Output:
Hello World
Say goodbye
I work
Exception in thread "main" java.lang.RuntimeException
at main.KillMe.run(Test.java:39)
at main.Test.execCommand(Test.java:25)
at main.Test.main(Test.java:17)
You can use #RetryOnFailure annotation from jcabi-aspects
Create a wrapper method then annotate it to enable auto retry upon Exception
As an example:
#RetryOnFailure(attempts = 5)
List<Device> retryWhenFailed(ServiceAdapter serviceAdapter) throws Exception {
return serviceAdapter.getDevices();
}
This solution uses Generics to be able to handle different Object with most of the same code and a Runnable to execute the fetching.
With this solution, you would need only to write the different adapters extending from ServiceAdapter<T extends Fetchable> to implement the logic to fetch the data for each different class (which would have to implement Fetchable).
Define an interface that abtracts the objects that can be fetched by the different services.
package so50488682;
public interface Fetchable {
}
The ojbect that are to be retrieved implement this interface so you can use the same code for different classes.
package so50488682;
public class Device implements Fetchable{
private String id;
public Device(String id) {
this.id = id;
}
public String toString() {
return "I am device " + id;
}
}
Define an abstract ServiceAdapter that the different service adapters will extend to implement the logic for each kind of object to be retrieved. We add throws Exception to the get() method so this method cand just delegate the exception handling to the FetcherService and decide if it should retry or fail.
package so50488682;
import java.util.List;
public abstract class ServiceAdapter<T extends Fetchable> {
public abstract List<T> get() throws Exception;
}
This is an example of an implementation done to get objects of class Device.
package so50488682;
import java.util.ArrayList;
import java.util.List;
public class DeviceServiceAdapter extends ServiceAdapter<Device>{
#Override
public List<Device> get() throws Exception{
List<Device> rtn = new ArrayList<>();
// fetch the data and put it into rtn, this is a mock
Device d = new Device("1");
rtn.add(d);
d = new Device("2");
rtn.add(d);
d = new Device("3");
rtn.add(d);
//
return rtn;
}
}
Finally this is a generic solution to run the different service adapters.
public class FetcherService<T extends Fetchable> implements Runnable{
List<T> result = new ArrayList<>();
ServiceAdapter<T> serviceAdapter;
#Override
public void run() {
boolean flag = true;
int counter = 1;
while (flag) {
try {
result = serviceAdapter.get();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
throw new RuntimeException("Got Interrupted in sleep", e);
}
}
}
}
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
public void setAdapter(ServiceAdapter<T> adapter) {
this.serviceAdapter = adapter;
}
}
From the main or calling program it work like this:
package so50488682;
import java.util.List;
public class SO50488682 {
public static void main(String args[]) {
try {
DeviceServiceAdapter deviceServiceAdapter = new DeviceServiceAdapter();
FetcherService<Device> deviceFetcherService = new FetcherService<>();
deviceFetcherService.setAdapter(deviceServiceAdapter);
deviceFetcherService.run();
List<Device> devices = deviceFetcherService.getResult();
for(Device device : devices) {
System.out.println(device.toString());
}
}catch(Exception e) {
System.out.println("Exception after retrying a couple of times");
e.printStackTrace();
}
}
}
In an interview I was asked to come up with an approach which will ensure that while thread T1 and T3 can access a method of a class, T2 cannot access the method.
I am unable to provide any solution to this. Could you please provide an example with an explanation?
I have later come up with the following solution. Is it efficient?
package JavaProgramming;
public class EligibleThread implements Runnable {
public void method1() {
System.out.println("Hello");
}
public static void main(String[] args) {
EligibleThread t1 = new EligibleThread();
EligibleThread t2 = new EligibleThread();
Thread t11 = new Thread(t1, "t1");
Thread t22 = new Thread(t2, "t2");
t11.start();
t22.start();
}
public void run() {
if (Thread.currentThread().getName() != "t2") {
method1();
} else{
try {
throw new Exception("Access is denied");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You can use protected modifier, like following code. T1 can call aMethod() by extending Main class, but T2 can't call aMethod().
public class Main {
protected void aMethod() {
}
}
class T1 extends Main implements Runnable{
#Override
public void run() {
aMethod();
}
}
class T2 implements Runnable{
#Override
public void run() {
// here can't call Main.aMethod()
}
}
In my project, I have a method which loads a big model from local disk. Loading the model takes about 15 minutes and sometimes more. What i'm thinking to do is to create a runnable method which loads the model for once and then, from different classes i call this method to execute some code.
in fact, i'm not sure how to achieve that, could you please guide me?
Here is simple pseudo code:
// class A has two method , load the model , and does some calculation
Class A: 1.Runnable method: LoadModel();
2.Mehtod2: distance();
// here i would like to run this programe anytime, pass some parameters and call the method "distance" in class A
Class B: 1.import Loadmodel() class and invoke distance ();
in my mind i'd like to create something similar to server but not server:)
Updated:The code below is what I've tried so far.
public class load implements Runnable {
WordVectors wordVectors;
public void run() {
try {
load();
} catch (FileNotFoundException ex) {
java.util.logging.Logger.getLogger(load.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
java.util.logging.Logger.getLogger(load.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void load() throws FileNotFoundException, UnsupportedEncodingException {
//Your display method implementation.
wordVectors = WordVectorSerializer.loadTxtVectors(new File("glove.twitter.27B.200d.txt"));
}
public double Simmiraty(String a, String b){
return wordVectors.similarity(a,b);
}
public static void main(String[] args) {
load Obj= new load ();
Obj.run();
}
}
The Second class:
public class B{
public static void main(String[] args) throws Exception {
load ob =new load();
System.out.println( ob.Simmiraty("iphone", "battery"));
}
}
I have to prolem with the above code:
1. it stops running once it has loaded the model.
2. I can't invoke any method from the frist class.
public class Load implements Runnable{
private InputStream stream;
private static final Load instance;
private WordVectors wordVectors;
static {
instance = new Load();
instance.run();
}
public static Load GetLoad(){
return instance;
}
private Load(){
if(instance != null)
throw new UnsupportedOperationException();
}
public voir run() {
if(wordVectors != null)
throw new UnsupportedOperationException();
try {
load();
} catch (Exception ex) {
Logger.getLogger(load.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void load() throws FileNotFoundException, UnsupportedEncodingException {
stream = new InputStream(new File("glove.twitter.27B.200d.txt"));
wordVectors = WordVectorSerializer.loadTxtVectors(stream,false);
}
public void interrupt(){
if(stream != null)
stream.close();
}
public double Simmiraty(String a, String b){
return wordVectors.similarity(a,b);
}
public static void main(){
Load load = GetLoad();
}
}
public class B{
public void function(){
Load load = Load.GetLoad();
}
}
public abstract class Event implements Runnable {
public void run() {
try {
Thread.sleep(delayTime);
action();
} catch(Exception e) {e.printStackTrace();}
}
}
I have this event class above, when I try to start the thread it runs the first command of the thread - Thread.sleep(delayTime); Since the Event class is abstract I want to run some of its child class methods. For example, when I call action(); it should run the action method from the below child class
public class ThermostatNight extends Event {
public ThermostatNight(long delayTime) {
super(delayTime);
}
public void action() {
System.out.println(this);
thermostat = "Night";
}
public String toString() {return "Thermostat on night setting";}
}
There are many such child classes, like ThermostatDay, FanOn, FanOff who are very similar as above. What should I do the call action(); after sleep is called from the run() command in Event class ?
Any ideas?
Your help is appreciated!
Create and instance variable of type Event and a constructor that takes in an
Event as parameter
public class Event implements Serializable, Runnable {
private Event childClass;
public Event(long delayTime, Event childClass) {
this.delayTime = delayTime;
this.childClass = childClass;
}
public void run() {
try {
Thread.sleep(delayTime);
childClass.action();
} catch(Exception e) {e.printStackTrace();}
}
}
I realized the issue here.
You can see action() is called in try {} below:
public void run() {
try {
Thread.sleep(delayTime);
action();
} catch(Exception e) {e.printStackTrace();}
}
If you push it out like below, the code should work fine.
public void run() {
try {
Thread.sleep(delayTime);
} catch(Exception e) {e.printStackTrace();}
action();
}
I currently have several runnable classes, each printing a string upon completion using System.out.println().
In the main() I execute them using a ExecutorService ,executor.execute() for each of them.
I am wondering after executing those threads, how to get the output stream from them for future use ?
Pretty much like using .getInputStream for processes but there's no such method in the Thread class. Thanks!
There's a class which implements runnable interface like this:
public class A implements Runnable {
public void run() {
System.out.println(5); //this thread always print out number 5
}
}
and in the main function I need to get the printed number and store it
public static void main(String[] args) {
ExecutorService ThreadPool = Executors.newFixedThreadPool(1);
ThreadPool.execute(new A()); //This statement will cause the thread object A
//to print out number 5 on the screen
ThreadPool.shutdown();
......
}
Now I need to get the printed number 5 and store it into, say an integer variable.
I think below code will satisfy your requirement.
class MyCallable implements Callable<InputStream>
{
#Override
public InputStream call() throws Exception {
//InputStream inputStreamObject = create object for InputStream
return inputStreamObject;
}
}
class Main
{
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<InputStream>> list = new ArrayList<Future<InputStream>>();
for (int i = 0; i < 25; i++) {
Callable<InputStream> worker = new MyCallable();
Future<InputStream> submit = executor.submit(worker);
list.add(submit);
}
InputStream inputStreamObject = null;
for (Future<InputStream> future : list) {
try {
inputStreamObject = future.get();
//use inputStreamObject as your needs
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
Runnable and Callable in thread:
runnable interface has a method public abstract void run(); void - which means after completing run method, it will not return anything. Callable<V> interface has a method V call() throws Exception; which means after completing call method, it will return Object V that is parametrized as
public class Run_Vs_Call {
public static void main(String...args){
CallableTask call = new CallableTask();
RunnableTask run = new RunnableTask();
try{
FutureTask<String> callTask = new FutureTask<String>(call);
Thread runTask = new Thread(run);
callTask.run();
runTask.start();
System.out.println(callTask.get());
}catch(Exception e){
e.printStackTrace();
}
}
public static class CallableTask implements Callable<String>{
public String call( ){
String stringObject = "Inside call method..!! I am returning this string";
System.out.println(stringObject);
return stringObject;
}
}
public static class RunnableTask implements Runnable{
public void run(){
String stringObject = "Inside Run Method, I can not return any thing";
System.out.println(stringObject);
}
}
}
you can use new static class:
public class Global{
//example
public static ..
public static ..
}