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();
}
}
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();
}
}
}
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();
I want to register several agents.
For doing this I'm using the following code
The clases
public class Main {
public static void main(String[] args) {
String[] services = {"-gui"};
Boot.main(services);
Agent1 = new Agent1(0,0,"a");
}
}
public class Agent1 extends Agent{
public Agent1(int x, int y, String name) {
super(x, y, name);
setup();
}
protected void setup(){
System.out.println("hi");
ServiceDescription sd = new ServiceDescription();
sd.setType( "buyer" );
sd.setName( "asa" );
register( sd );
}
void register( ServiceDescription sd){
DFAgentDescription dfd = new DFAgentDescription();
dfd.setName(getAID());
dfd.addServices(sd);
try {
DFService.register(this, dfd );
}
catch (FIPAException fe) { fe.printStackTrace(); }
}
protected void takeDown(){
System.out.println("bye");
}
}
But I am getting the following error:
jade.domain.FIPAAgentManagement.MissingParameter: (missing-parameter
df-agent-description name)
How can I fix the error?
Thanks
You're not creating the agent correctly. The getAID() will return null, and the DFAgentDescription becomes invalid.
You should pass -agents to jade.Boot, and it will create the agent for you.
public static void main(String[] args) {
// the agent's name is agent1, change xy.zy to your package
String[] services = {"-gui", "-agents", "agent1:xy.zy.Agent1"};
Boot.main(services);
}
You don't need Agent1 = new Agent1(0,0,"a"); and you don't need the constructor in Agent1. The method setup() is called automatically.
I want to route certain chars to methods, so that when the char is typed in the command-line the method is then executed.
Based on the answer How to call a method stored in a HashMap, I'm mapping these chars to methods by using the "Command" design-pattern.
However I want to generically implement this, so it seems that I need to implement reflection in order to use the Method class as a parameter. My attempt is getting a NullPointerException on the field private Method method in my anonymous class...
Here is my code:
import java.lang.reflect.Method;
public interface InvokesMethod {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
} // end of interface
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
public HashMap<Character, InvokesMethod> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethod>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
this.commands.put(letter, new InvokesMethod() {
// NullPointerException starts here in the stack-trace:
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}).setMethod(method);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
} // end of class
public class Main() {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Regards to your code you didn't initiate method. Bear in mind that execute with null you must call public static method:
Your other issue , you didn't initiated interface properly. Here is working example:
InvokesMethodItf
public interface InvokesMethodItf {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
}
InvokesMethod
public class InvokesMethod implements InvokesMethodItf{
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}
Terminal
public class Terminal {
public HashMap<Character, InvokesMethodItf> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethodItf>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printHelloWorld() {// method.invoke(null) looking for "static" method
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
InvokesMethodItf inv = new InvokesMethod();
inv.setMethod(method);
this.commands.put(letter, inv);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
}
Main
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Hello World!
Thanks to #Maxim's original suggestion here, I have an alternate solution by setting the methods as Strings in the HashMap instead --
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
private HashMap<Character, String> commands;
public Terminal() {
this.commands = new HashMap<Character, String>();
this.commands.put('p', "printHelloWorld");
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
public void executeCommand(char letter) throws Exception {
Method method = getClass().getDeclaredMethod(this.commands.get(letter));
method.invoke(this);
}
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Output:
Hello World!
Now to figure out how to pass parameters to the reflected methods...
I have the following class:
class MyClass{
private static final int VERSION_VALUE = 8;
private static final String VERSION_KEY = "versionName";
public boolean myPublicMethod(String str) {
try {
return myPrivateMethod(str, VERSION_KEY, VERSION_VALUE,
new MyInnerClass() {
#Override
public InputStream loadResource(String name) {
//do something important
}
});
}
catch (Exception e) {
}
return false;
}
private boolean myPrivateMethod(String str, String key, int version,
ResourceLoader resourceLoader) throws Exception
{
//do something
}
private static abstract class MyInnerClass {
public abstract InputStream loadResource(String name);
}
}
I want to write unit test for myPrivateMethod for which I need to pass resourceLoader object and override it's loadResource method.
Here is my test method:
#Test
public void testMyPrivateMethod() throws Exception {
Class<?> cls = Class.forName("my.pack.MyClass$MyInnerClass");
Method method = cls.getDeclaredMethod("loadResource", String.class);
//create inner class instance and override method
Whitebox.invokeMethod(myClassObject, "testValue1", "testValue2", "name1", 10, innerClassObject);
}
Note, that I can't change code.
Well, you could use Javassist...
See this question. I haven't tried this, but you can call this method when you want the override:
public <T extends Object> T getOverride(Class<T> cls, MethodHandler handler) {
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(cls);
factory.setFilter(
new MethodFilter() {
#Override
public boolean isHandled(Method method) {
return Modifier.isAbstract(method.getModifiers());
}
}
);
return (T) factory.create(new Class<?>[0], new Object[0], handler);
}
Well, the problem i see with your code is that you are calling myPublicMethod and you are giving fourth parameter as new MyInnerClass(). Now in your private method fourth parameter is given as ResourceLoader and from your code i see no relation between MyInnerClass and ResourceLoader. So you can try out following code. It might help.
Despite your warning that you cannot change the code i have changed it because i was trying to run your code.
class MyClass{
private static final int VERSION_VALUE = 8;
private static final String VERSION_KEY = "versionName";
public boolean myPublicMethod(String str) {
try {
return myPrivateMethod(str, VERSION_KEY, VERSION_VALUE,
new MyInnerClass() {
#Override
public InputStream loadResource(String name) {
return null;
//do something important
}
});
}
catch (Exception e) {
}
return false;
}
private boolean myPrivateMethod(String str, String key, int version,
MyInnerClass resourceLoader) throws Exception
{
return false;
//do something
}
private static abstract class MyInnerClass {
public abstract InputStream loadResource(String name);
}
}
Hope it helps.