About call method
hi, i want to open a new window when i presses the button, so , should the new window also be a class or just a component.
en, hehe,firstly, i am rookie in Java, i dont know lots about it.
what i want to do is :
if else(e.getSource()=j1){
display();
} ///j1 is one instance of JButton
so ,that's question. here, can i create a new class called display so i can design the panel or just call method display(), does that make sense to you, thx
Similar Messages
-
About calling method with arguments
Hi,
I have a problem about calling method using reflection. my method is like follows:
public myMethod(Integer var1, MyObject mobj) {
I've tried to call the method using the following code,
Class[] parameterTypes = new Class[] {Integer.class, MyObject.class};
Object[] arguments = new Object[] {new Integer(2), mobj};
Method met=cl.getMethod("myMethod", parameterTypes);
But the in the last line NoSuchMethodException is thrown.
How can I send the reference of MyObject to myMethod()?
Thanx
ronyShould work ok:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
static class MyObject {}
public static void main(String[] args) throws Exception {
Class c = Test.class;
Class[] parameterTypes = new Class[] {Integer.class, MyObject.class};
try {
Object[] arguments = new Object[] {new Integer(2), new MyObject()};
Method met = c.getMethod("myMethod", parameterTypes);
met.invoke(new Test(), arguments);
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
public void myMethod(Integer var1, MyObject mobj) {
System.out.println("myMethod");
} -
A problem about calling Labview vi in VB
Hi all:
I meeting a problem about data transfer and parallel operation between VB and Labview.
Actually, I want develop a VB program, in which, the Labview VI can be called and corresponding parameters can be transferred to Labview. and then, I also can operate my system by VB program at same time. something like parallel operation (VB and Labview program).
But the question is :
1. If I use "Call" method of ActiveX in VB, and the LabVIEW subvi is not stopped (for example, a loop structure), I can not do parallel operation on VB program. The error message is "other application is busy" which is attached below. The sample codes is also attached.
2. I tried to use other methods like "OpenFrontPanel" and "Run", but I am not sure how to transfer the parameter??
3. Then I tried to use "SetControlValue" to set the parameters, but there is a error " := expected", which is very strange, because the statement I wrote is followed with the help documents [ eg: VI.SetControlValue ("string", value)], why it is still need a "=" ??
Does anybody know something about it? Thanks a lot
Message Edited by hanwei on 11-07-2008 03:18 PM
Attachments:
vb_labview_error_message_1.JPG 14 KB
VB_to_LV.zip 10 KBI sure hope OP has solved it by now.
/Y
LabVIEW 8.2 - 2014
"Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
G# - Free award winning reference based OOP for LV -
How to call methods from within run()
Seems like this must be a common question, but I cannot for the life of me, find the appropriate topic. So apologies ahead of time if this is a repeat.
I have code like the following:
public class MainClass implements Runnable {
public static void main(String args[]) {
Thread t = new Thread(new MainClass());
t.start();
public void run() {
if (condition)
doSomethingIntensive();
else
doSomethingElseIntensive();
System.out.println("I want this to print ONLY AFTER the method call finishes, but I'm printed before either 'Intensive' method call completes.");
private void doSomethingIntensive() {
System.out.println("I'm never printed because run() ends before execution gets here.");
return;
private void doSomethingElseIntensive() {
System.out.println("I'm never printed because run() ends before execution gets here.");
return;
}Question: how do you call methods from within run() and still have it be sequential execution? It seems that a method call within run() creates a new thread just for the method. BUT, this isn't true, because the Thread.currentThread().getName() names are the same instead run() and the "intensive" methods. So, it's not like I can pause one until the method completes because they're the same thread! (I've tried this.)
So, moral of the story, is there no breaking down a thread's execution into methods? Does all your thread code have to be within the run() method, even if it's 1000 lines? Seems like this wouldn't be the case, but can't get it to work otherwise.
Thanks all!!!I (think I) understand the basics.. what I'm confused
about is whether the methods are synced on the class
type or a class instance?The short answer is; the instance for non-static methods, and the class for static methods, although it would be more accurate to say against the instance of the Class for static methods.
The locking associated with the "sychronized" keyword is all based around an entity called a "monitor". Whenever a thread wants to enter a synchronized method or block, if it doesn't already "own" the monitor, it will try to take it. If the monitor is owned by another thread, then the current thread will block until the other thread releases the monitor. Once the synchronized block is complete, the monitor is released by the thread that owns it.
So your question boils down to; where does this monitor come from? Every instance of every Object has a monitor associated with it, and any synchronized method or synchonized block is going to take the monitor associated with the instance. The following:
synchronized void myMethod() {...is equivalent to:
void myMethod() {
synchronized(this) {
...Keep in mind, though, that every Class has an instance too. You can call "this.getClass()" to get that instance, or you can get the instance for a specific class, say String, with "String.class". Whenever you declare a static method as synchronized, or put a synchronized block inside a static method, the monitor taken will be the one associated with the instance of the class in which the method was declared. In other words this:
public class Foo {
synchronized static void myMethod() {...is equivalent to:
public class Foo{
static void myMethod() {
synchronized(Foo.class) {...The problem here is that the instance of the Foo class is being locked. If we declare a subclass of Foo, and then declare a synchronized static method in the subclass, it will lock on the subclass and not on Foo. This is OK, but you have to be aware of it. If you try to declare a static resource of some sort inside Foo, it's best to make it private instead of protected, because subclasses can't really lock on the parent class (well, at least, not without doing something ugly like "synchronized(Foo.class)", which isn't terribly maintainable).
Doing something like "synchronized(this.getClass())" is a really bad idea. Each subclass is going to take a different monitor, so you can have as many threads in your synchronized block as you have subclasses, and I can't think of a time I'd want that.
There's also another, equivalent aproach you can take, if this makes more sense to you:
static final Object lock = new Object();
void myMethod() {
synchronized(lock) {
// Stuff in here is synchronized against the lock's monitor
}This will take the monitor of the instance referenced by "lock". Since lock is a static variable, only one thread at a time will be able to get into myMethod(), even if the threads are calling into different instances. -
Java code to call methods in .ocx file
dear friends,
i have an .ocx file with me which is used to communicate with a specific device.it is an already existing one. i wish to know whether i can call method sin that .ocx file using java .using vb6 we can do this.
if it is possible with java i wish to know how i can do this.please consider this query and please send me your responses. i know that using jni we can communicate with .dll files.but i am not sure about .ocx file. please help me.
thank you
aruni wish to know whether i can call method sin that .ocx file using java
Probably
db -
CALL METHOD ABAP run SQL wrong
Dear All
I have a problem in ABAP connect SQL,Below is my code snippet sentence.
CONCATENATE 'Insert Into [timportcortrol]'
'(zucode,zstate,zdate,zkind) Values('''
VG_PCID ''','''
'1'','''
SY-DATUM ''','''
'1' ''')'
INTO SQL.
CALL METHOD OF REC 'Execute'
EXPORTING #1 = SQL
#2 = CON
#3 = '1'.
IF NOT SY-SUBRC = 0.
MESSAGE I000 WITH 'Download to [timportcortrol] failure,Please Check the SQL Connect!!! '.
EXIT.
ENDIF.
Con:is the connect SQL String ,the connect SQL is Okay.
I debug this code,when I used u2018Select u2026sentenceu2019,the program can work.if I use u2018insert intou2019 then canu2019t work,but I copied the SQL of the u2018inset Into sentenceu2026u2019run it into SQL server then it can work also.
And I found the SY-SUBRC eq u20182u2019.whatu2019s mean about of the sy-subrc eq u20182u2019.
I think the insert into sentence in abap I have write the wrong ,but I canu2019t assurance.
The Insert Into Sentence is:u2019 Insert Into [timportcortrol](zucode,zstate,zdate,zkind) Values('20080807094713','1','20080807','1')u2019
Could you give me some advice for this issue?
Thanks of all
Sun.Have you checked whether it's a problem with mixed case? Some SQL dialects are case sensitive.
The not very helpful meanings of the sy-subrc value can be found in ABAP help.
0 Successful processing of the method meth.
1 Communication Error to SAP GUI.
2 Error when calling method meth.
3 Error when setting a property.
4 Error when reading a property
matt -
How to call methods at selection screen?
Hi all,
I am developing a program in object oriented abap.
i have defined a class and implementated, and we have to instantiate the class in start of selection.
now the problem is how to call a method at selection screen event.
i want to validate the inputs entered by users. so can i create a static method which can be called without instantiating a class?
please guide me
thanksHello Mr A,
Define the method as a Static Method and that will solve your problem. Static methods can be called directly and does not need the class to be instantiated before it can be called.
Data: my_class type ref to zcl_report_utilities.
At Selection-Screen.
Call Method zcl_report_utilities=>check_selections
exporting
iv_repnm = sy-cprog
importing
et_messages = lt_msgs.
Start-Of-Selection.
Create Object my_class
exporting
im_pernr = ls_e1plogi-objid
im_begda = c_lowdate
im_endda = c_hidate.
Call Method my_class->read_infotypes
exporting
im_infty = c_org_assn
changing
et_infty = it_infty.
Here you can see how the method check_selections is called before the class zcl_report_utilities is instantiated. The best part about the Static Methods is if you are writing the class in the Class Library (SE24), any other programs can call them directly (if they need to) without needing to instantiating the entire class before the call.
Also note the difference in syntax when calling the static method check_selections to when calling the Instance method read_infotypes.
Hope this solves your issue and please do not forget to reward points.
Cheers,
Sougata.
p.s. if you are defining your class locally (program specific) then use Class-Methods to define a static method.
Edited by: Sougata Chatterjee on May 1, 2008 9:53 AM -
Can I Call method on one JVM from another through a dll?
Let me explain.
I have this java jar file that I can only have one instance of running at any given time. I'm using a shared data segment in a dll to store a bool indicating whether the program is already running or not. If it's already running, I have to not run the second instance and give focus to the current running instance.
The jar file calls a native method "canInstantiate()" on a dll to see if there's already an app running. If there isn't, the env and obj are stored in the shared data segment of the dll and we return true. If there is already an instance of the program running, I want canInstantiate call a function on the current instance of the jar (like a callback) to tell it to request focus. It's not working. Can someone tell me if my code is right?
The .h file
#include "stdafx.h"
#include <jni.h>
#include "CardServer.h"
#pragma data_seg("SHARED") // Begin the shared data segment.
static volatile bool instanceExists = false;
static JavaVM *theJavaVM = NULL;
static JNIEnv* theJavaEnv= NULL;
static jobject instanceObject = NULL;
static jmethodID mid = NULL;
static jclass cls = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:SHARED,RWS")
jdouble canInstantiate(JNIEnv *env, jobject obj);
jdouble instantiate(JNIEnv *env, jobject obj);
jdouble uninstantiate(JNIEnv *env, jobject obj);
void grabFocus();
</code>
The .cpp file:
<code>
#include "MyFunctions.h"
#include <string.h>
#include <stdlib.h>
#include "stdafx.h"
#include <iostream.h>
jdouble canInstantiate(JNIEnv *env, jobject obj)
printf("In canInstantiate!!");
if (!instanceExists)
printf("No instance exists!!");
return (jdouble)0.0;
else
printf("An instance already exists!!");
grabFocus();
return (jdouble)1.0;
jdouble instantiate(JNIEnv *env, jobject obj)
printf("**In CPP: Instantiate!!\n");
cout << "At start, env is: " << env << endl;
cout << "At start, obj is: " << obj << endl;
if (instanceExists == false)
instanceExists = true;
theJavaEnv = env;
instanceObject = obj;
theJavaEnv->GetJavaVM(&theJavaVM);
cls = (theJavaEnv)->FindClass("TheMainClassOfTheJar");
if (cls == 0) {
fprintf(stderr, "Can't find Prog class\n");
exit(1);
mid = (theJavaEnv)->GetMethodID(cls, "grabFocusInJava", "(I)I");
if (mid == 0) {
fprintf(stderr, "Can't find grabFocusInJava\n");
exit(1);
printf("About to call grabFocusInJava\n");
grabFocus();
printf("CPP: After the grab focus command in instantiate!!\n");
cout << "At end, env is: " << env << endl;
cout << "At end, obj is: " << obj << endl;
return 0.0;
else
printf("CPP: Finished Instantiate!!\n");
return 1.0;
jdouble uninstantiate(JNIEnv *env, jobject obj)
printf("CPP: In uninstantiate!!\n");
if (instanceExists == true)
instanceExists = false;
theJavaVM = NULL;
instanceObject = NULL;
printf("CPP: Finishing uninstantiate!!\n");
return 0.0;
else
printf("CPP: Finishing uninstantiate!!\n");
return 1.0;
void grabFocus()
printf("In CPP::GrabFocus!!\n");
instanceObject = theJavaEnv->NewGlobalRef(instanceObject);
cls = (theJavaEnv)->FindClass("CardFormatter");
if (cls == 0) {
fprintf(stderr, "Can't find Prog class\n");
exit(1);
printf("Got the cls id again!!\n");
if (cls == 0)
printf("IT'S INVALID!!\n");
mid = (theJavaEnv)->GetMethodID(cls, "grabFocusInJava", "(I)I");
if (mid == 0) {
fprintf(stderr, "Can't find grabFocusInJava\n");
exit(1);
theJavaEnv->CallIntMethod(instanceObject, mid, 2);
printf("Called grabFocusInJava\n");
</code>
thanks in advanceCan I Call method on one JVM from another through a dll
...The rest of your question merely expands on your title.
And the answer to that question is no.
When you call a method you are executing a "thread of execution." A thread of execution exists only in a single process. It can not exist in another process.
If the dll is doing some interesting things then you could call a method that sets a flag. Data can move between instances. But you would then have to have a thread in that different process monitoring that flag. And sharing data in a dll is not a normal process, so it would have to be coded appropriately.
If all you want to do is set the current focus to the existing application, then that can be done with existing windows functionality. You don't need to do anything special in your dll. You can probably search these forums to find the exact code. If not there are countless examples in windows repositories (like MSDN) on how to do that. -
Oop report programme: call method
hi, i need ur guys advice about my oop report. its contain 2 class, lcl_main (main programme), lcl_disp(display report), lcl_update (upload report). all 3 class defination as below:
* C.L.A.S.S D.E.F.I.N.I.T.I.O.N
class lcl_main definition.
public section.
methods: init,
get_filename,
load_data,
chk_col,
chk_data,
chk_mandatory,
disp_status.
endclass.
class lcl_disp definition inheriting from lcl_main.
public section.
methods: chk_9700,
disp_success.
endclass.
class lcl_update definition inheriting from lcl_main.
public section.
methods: update9700.
endclass.
the idea was, i planned to put all methods which will be access by lcl_disp and lcl_update into lcl_main. i currently cofious to call method at lcl_main. currently i done as below, which if want to display (user will choose radio button display - p_view) i will create the object for lcl_disp and call all method in lcl_main and lcl_disp , for example o_disp-> init ... o_disp->loaddata .. and etc. the problem was if i want to choose the update , i need to object for lcl_update and call again the lcl_main with: o_update-> init ... o_update->loaddata .. and etc. the code as below.
the question , the programme can be successfully run with this method but i faced the problem when i tried to create a call method inside others method because at the START-OF-SELECTION i need to identify with object (lcl_disp or lcl_update) first.
2nd, i tried to figure out how at the start-of-selection , i no need to repeat to call method init, loaddata repeatly for different class (lcl_disp and lcl_update). really need advice. thank you.
*---------------------------------------------------------------------|
* INITIALIZATION |
*---------------------------------------------------------------------|
initialization.
data: o_main type ref to lcl_main.
create object: o_main.
* START OF SELECTION *
start-of-selection.
data: o_disp type ref to lcl_disp,
o_update type ref to lcl_update.
create object: o_disp, o_update.
if p_view = 'X'. "for view report
set handler o_handler->handle_event for all instances.
call method o_disp->init.
call method o_disp->load_data.
call method o_disp->chk_col.
"only proceeed if initial - col header and pernr syntax (pre 100 and length = 8)
if o_disp->status = 0.
call method o_disp->chk_data.
endif.
if o_disp->status = 0.
call method o_disp->chk_mandatory.
endif.
if o_disp->status = 0.
call method o_disp->chk_9700.
endif.
call method o_disp->disp_status.
elseif p_upld = 'X'."for update report
set handler o_handler->handle_event for all instances.
call method o_update->init.
call method o_update->load_data.
call method o_update->chk_col.
"only proceeed if initial - col header and pernr syntax (pre 100 and length = 8)
if o_update->status = 0.
call method o_update->chk_data.
endif.
if o_update->status = 0.
call method o_update->update9700.
endif.
call method o_update->disp_status.
endif.
class lcl_main implementation.
method get_filename.
endmethod.
method init.
endmethod.
method load_data.
endmethod.
method chk_col.
endmethod.
method chk_data.
endmethod.
method chk_mandatory.
endmethod.
method disp_status.
endmethod.
endclass.
class lcl_disp implementation.
method chk_9700.
endmethod.
method disp_success.
endclass.
class lcl_update implementation.
method update9700.
endmethod.
endclass.
Edited by: firdaus hashim on Nov 23, 2009 11:01 AMHello Sam,
Go to the class CL_DD_DOCUMENT (trxn SE24).
In the 'Attributes' tab, check for the attributes with SDYDO_ATTRIBUTE as the associated type.
It gives all the available attributes.
BR,
Suhas -
Call methods from view controller to another (enhanced) view controller!
Dear All,
Is it possible to use/call methods from view controller to another (enhanced) view controller? Iu2019ve created a view using enhancement in standard WD component. I would like to call one method from standard view controller in the enhanced view controller.
Is it possible to include text symbols as enhancement in standard class?
u2026NaddyHi,
If you have just enhanced an existing view then you can call the standard methods in one of the new methods which you will create as part of enhancement.
If you have created a totally new view using enhancement framework option ( Create as Enhancement ) then in this new view you won't be able to use existing methods in other view as a view controller is private in nature. So all the view attributes, context nodes and methods are Private to that view only.
Regarding text elements, I guess adding a new text element is just a table entry in text table and is therefore not recorded as enhancement.( Not very sure about this, need to double check )
Regards
Manas Dua -
CALL METHOD CL_GUI_CFW= DISPATCH.
what is the use of CALL METHOD CL_GUI_CFW=>DISPATCH. one?
Hi Vinay.
I would like to suggest,
[SDN - Reference for Usage of CALL METHOD cl_gui_cfw=>dispatch|cl_gui_cfw=>dispatch;
[SDN - Reference for Issue in cl_gui_cfw=>dispatch|About CL_GUI_ALV_GRID's event-handling & PAI/PBO;
Hope that's usefull.
Good Luck & Regards.
Harsh Dave -
Which of the following are true about abstract methods in EJB 2.0
Hi guys I'm beginner to EJB and i got some unanswered questions.
Can any one of you please.. give answers?
Thanks if you do...
Which of the following are true about abstract methods in EJB 2.0
CMP?
Choose all correct answers:
1. Abstract accessor methods should not be exposed in the EJB
component's interface
2.Abstract accessor/mutator methods are used to access and modify
persistent state and relationship information for entity objects
3.Abstract Accessor/Mutator methods do not throw exceptions
4.The EJB developer must implement the Accessor/Mutator methods
5.Abstract accessor methods may or may not be exposed in the EJB
component's interface
2.Which ONE of the following is true?
Choose the best answer:
1.Local interfaces cannot have a relationship with other Entity
components
2.Local interfaces cannot be used for Stateless Session EJB
3.Local interfaces can be a part of Object's persistent state
4.Local interfaces have the same functionality as that of a
stateless Session EJB
3.Which of the following describe the <cmr-field> in a EJB 2.0
descriptor?
Choose all correct answers:
1.A Local interface/Entity can be a value of a <cmr-field>
2.There is no <cmr-field> in EJB 2.0 descriptor
3.It is used to represent one meaningful association between any
pair of Entity EJBs, based on the business logic of the Application
4.It provides a particular mapping from an object model to a
relational database schema
5.It allows the Local Entity interfaces to participate in
relationships
4.Which of the following are the advantages of using Local interfaces
instead of dependent value classes?
Choose all correct answers:
1.Local Entity Interfaces can participate in Relationships
2.The life cycle of Local Entity Interfaces is managed by EJB
container, intelligently
3.Local Entity Interfaces can be used in EJB QL Queries
4.Local Entity Interfaces can be a part of the <cmp-field> but not
<cmr-field>
5.Which of the following are true about Local interfaces
1.A local interface must be located in the same JVM to which the EJB
component is deployed
2.Local calls involve pass-by-reference.
3.The objects that are passed as parameters in local interface
method calls must be serializable.
4.In general, the references that are passed across the local
interface cannot be used outside of the immediate call chain and must
never be stored as part of the state of another enterprise bean.
6.Which of the following specifies the correct way for a client
to access a Message driven Bean?
Choose the best answer:
1. via a Remote interface
2. via Home interface
3. Message driven bean can be accessed directly by the client
4. both 1 & 2
5. none of the above
------------------------------------------------------------------------7.Which of the following statements are true about message-driven
bean Clients?
------------------------------------------------------------------------Choose all correct answers:
They can create Queue and QueueConnectionFactory objects
They can create Topic and TopicConnectionFactory objects
They can lookup the JNDI server and obtain the references for
Queue and Topic and their connection Factories
Only 1 and 2 aboveHi guys I'm beginner to EJB and i got some unanswered
questions.
Can any one of you please.. give answers?
Thanks if you do...
Which of the following are true about abstract methods
in EJB 2.0
CMP?
Choose all correct answers:
1. Abstract accessor methods should not be exposed
d in the EJB
component's interfacefalse
2.Abstract accessor/mutator methods are used to
access and modify
persistent state and relationship information for
entity objectstrue
>
3.Abstract Accessor/Mutator methods do not throw
exceptionstrue
>
4.The EJB developer must implement the
Accessor/Mutator methodsfalse
5.Abstract accessor methods may or may not be exposed
in the EJB
component's interfacetrue
2.Which ONE of the following is true?
Choose the best answer:
1.Local interfaces cannot have a relationship with
other Entity
componentsfalse
2.Local interfaces cannot be used for Stateless
Session EJBfalse
3.Local interfaces can be a part of Object's
persistent statefalse
4.Local interfaces have the same functionality as
that of a
stateless Session EJBtrue
3.Which of the following describe the <cmr-field> in a
EJB 2.0
descriptor?
Choose all correct answers:
1.A Local interface/Entity can be a value of a
<cmr-field>true
2.There is no <cmr-field> in EJB 2.0 descriptorfalse
3.It is used to represent one meaningful association
between any
pair of Entity EJBs, based on the business logic of
the Applicationtrue
4.It provides a particular mapping from an object
model to a
relational database schematrue
5.It allows the Local Entity interfaces to
participate in
relationshipstrue
4.Which of the following are the advantages of using
Local interfaces
instead of dependent value classes?
Choose all correct answers:
1.Local Entity Interfaces can participate in
Relationshipsis
2.The life cycle of Local Entity Interfaces is
managed by EJB
container, intelligentlyis
3.Local Entity Interfaces can be used in EJB QL
Queriesnot
4.Local Entity Interfaces can be a part of the
<cmp-field> but not
<cmr-field>not
>
>
5.Which of the following are true about Local
interfaces
1.A local interface must be located in the same JVM
M to which the EJB
component is deployedtrue
2.Local calls involve pass-by-reference.true
3.The objects that are passed as parameters in local
l interface
method calls must be serializable.false
4.In general, the references that are passed across
s the local
interface cannot be used outside of the immediate
e call chain and must
never be stored as part of the state of another
r enterprise bean.true
>
6.Which of the following specifies the correct way for
a client
to access a Message driven Bean?
Choose the best answer:
1. via a Remote interfacefalse
2. via Home interfacefalse
3. Message driven bean can be accessed directly by
the clientfalse
4. both 1 & 2false
5. none of the abovetrue.
>
----------------7.Which of the following statements
are true about message-driven
bean Clients?
----------------Choose all correct answers:
They can create Queue and QueueConnectionFactory
objectsthe container can, dunno bout clients
>
They can create Topic and TopicConnectionFactory
objectsthe container can, dunno bout clients
>
They can lookup the JNDI server and obtain the
references for
Queue and Topic and their connection Factories
true
Only 1 and 2 abovefalse
somebody correct me if i'm wrong -
Java.util.concurrent.Callable synchronized call method
Hi all,
I'm currently developing an algorithm that uses Callable Interface. I'd like to know when should I use synchronized in the Call() method signature.
My scene is the following:
Class Test invoke Task Class.
The Task Class contains the following code:
ExecutorService execServ
=Executors.newCachedThreadPool();
CallableWorkerThread workers[]
=new CallableWorkerThread[numWorkers];
Future futures[]
=new Future[numWorkers];
for (int i = 0; i < numWorkers; i++) {
workers[i] = new CallableWorkerThread();
futures[i] = execServ.submit(workers);
The CallableWorkerThread class implements Callable and overwrite it's Call() method.
My doubt is about the following:
Should I use this:
public synchronized Object call() throws Exception {
// Code to execute........
}OR
public Object call() throws Exception {
// Code to execute........
}Tks.Hi David, I thank you for your answer.
My class CallableWorkerThread implements Callable Interface because I'm using submit method() from ExecutorService.
In other words, when I use the instructionexecServ.submit(workers); the object workers must be a collection of Callable Objects.
This is my Test_CallableWorkerThread:
public class Test_CallableWorkerThread {
ExecutorService execServ = Executors.newCachedThreadPool();
CallableWorkerThread workers[] = new CallableWorkerThread[10];
Future futures[] = new Future[10];
for (int i = 0; i < 10; i++) {
workers[i] = new CallableWorkerThread();
futures[i] = execServ.submit(workers);
This is my CallableWorkerThread:
public class CallableWorkerThread implements Callable {
private Collection<MyObject> collectionOfMyObjects = null;
private String threadName = null;
private Connection conn = null;
CallableWorkerThread(Collection<MyObject> collectionOfMyObjects, String threadName, Connection conn) {
this.collectionOfMyObjects = collectionOfMyObjects;
this.threadName = threadName;
this.conn = conn;
public Object call() throws Exception {
for (Iterator iter = collectionOfMyObjects.iterator(); iter.hasNext();) {
MyObject element = (MyObject) iter.next();
System.out.println(this.threadName + " is working with " + element.getName());
try {Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
return(threadName);
}According to the code above, I'm using CachedThreadPool. I read the documentation about this and this method creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
It's work fine, but until now I didn't undestand what is the real difference between using method with synchronized and without.
Thanks for the help! -
Can I know the caller method from callee
Hi,
I have a method which is called from multiple methods. Is it possible to know the method which called it wihtout sending the parameter to specify which method called it. i.e. without using something like send 1 for method 2 for other.
One way I thnk is build an exception. Throw & catch it in the same method & get the stackTrace();I would respectfully remark that it isn't your
method's job to police the callers. It still
shouldn't be concerned with who the caller
was. It should just throw an appropriate exception
indicating invalid parameters were passed. Then it's
the caller's responsiblity to do something about it.Yeah... that is why exceptions exist. Throw an IlegalArgumentException and then (since it's unchecked) if you want to watch out for it, watch for it in the calling method, which is after all the method in charge.
It is easy to get carried away with the "spot checking" philosophy and try to handle all errors exactly where they occur, but if you think about it, where did the error really occur? Up the stack at the caller.. that is where the bad arguments came from.
Also, strictly speaking, it should be a rare case when code throws an IllegalArgumentException. For the most part exceptions should represent just that - exceptions. It is not really in best form for them to be used as conditionals.
For example, instead of getting input from the user and then forcing it down the method's throat without checks, you should run your own checks on it first - for example, by telling the JTextField that it is not allowed to accept characters that would result in an IllegalArgumentException.
Exceptions should represent just that; hence, except for certain weird cases, a body of classes that you write that interact exclusively with each other should be designed to (almost) never throw exceptions.
When someone else starts using your classes, all bets are off.
Drake -
Spry and Permission denied to call method XMLHttpRequest.open
hi all,
I'm using Spry to call an RSS feed and display on a webpage.
I'm running this locally on my computer for testing measures and it
works fine in IE but i'm getting a message saying "Permission
denied to call method XMLHttpRequest.open" when using FF.
I googled around a bit and found that it has to do something
with FF's cross domain security, but nothing much more than that. I
was just wondering if anyone would be able to point me to a good
resource that explains the issue more and how to fix it, keeping it
in mind that i want to fix it using Dreamweaver's Spry
options.5h4k42u1u wrote:
> if i'd use the spry tables with an RSS feed, it'll work
with IE but not with
> FF, but then when i try it with a local XML file, it'll
work with FF but not
> IE? In fact, why does it have trouble at all with the
local file, there should
> be no cross domains to worry about, right?
You're right that there should be no problem with a local
file, but
without seeing the XML file and your code, it's impossible to
say what's
causing the problem. I think your best bet is to post a more
detailed
question in the Spry forum.
http://www.adobe.com/go/labs_spry_pr1_forum
David Powers, Adobe Community Expert
Author, "The Essential Guide to Dreamweaver CS3" (friends of
ED)
Author, "PHP Solutions" (friends of ED)
http://foundationphp.com/
Maybe you are looking for
-
Set contents of textedit document in automator
I'm creating .ini files to mirror actual files for a company program, and I need to put the same text in each of these files + the file name (which is different for each file). Using automator I can get the file created with the filename inside, but
-
Hello, I am confused on as to why I am only able to embed a source in my Servlet by referring to a remote file only. I have: out.println("<embed src=\"http://192.168.1.8:8081/alt1.svg\" width=\"1000\" height=\"1000\" type=\"image/svg+xml\">");and it
-
How to create navigation link between windows?
Hi experts, I have two windows under which there are several views. Now I want to make navigations (inbound/outbound plug) between these view which belong to their own windows. It seems that the navigation link can not be created directly on the navi
-
HT3180 MY Apple TV has locked up
MY Apple TV has locked up. I have unplugged everything waited over 10 minutes and re attached. Then I went on line and learned how to restart using down and menu on remote. It seemed to restart only to end up in same locked up screeen. please hel
-
I am getting the following error message while accessing the report deployed on Oracle application Server. Internal Server Error 500. Sometime it runs and many times it gives the error message. any help will be highly appreciated.