Static function issue?
hi,
i am having a static function which fetch some values from data base and put it to an arraylist and return this array list.
some times the returned array list empty even though values are exists in db,all the varibles used in this static functions are local and
this function is very frequently acceessing from diffrent threads
when a static function calls then all the variables in the fuction will have diffrent copies right?
in my example i wondered like one thread is executing this function then in beetween another thread comes and re initilise the variables so i am getting the abive specified error...
please any one help ...
My J2SE version (no EJB's, direct JDBC, no ConnectionPooling) might look something like this, except the connect and close methods are allready in my krc.utilz.jdbc.JDBC class.
package david;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Sql
private final String className;
private final Logger log;
private final Connection conn;
public Sql() throws ClassNotFoundException, SQLException, IOException {
className = this.getClass().getName();
log = Logger.getLogger(className);
try {
conn = connect(this.getClass().getResourceAsStream("database.properties"));
} catch (SQLException e) {
log.throwing(className, "noargs constructor", e);
throw e;
* Executes the given query and returns the resulting rows as a List(rows)
* of Maps(Column name to value).
* @param String sql - the sql-select-query to execute
* @param String[] args - the query paramaters (if
* @return List<Map<String,String>> rows
* @throws java.sql.SQLException
public List<Map<String,String>> select(String sql, String[] args) throws SQLException {
final String methodName = "select";
log.entering(className, methodName, new String[] {"sql="+sql, "args="+args});
List<Map<String,String>> rows = new ArrayList<Map<String,String>>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql);
for (int i=0; i<args.length; i++) {
stmt.setString(i+1, args);
rs = stmt.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int numCols = md.getColumnCount();
while (rs.next()) {
Map<String,String> cols = new HashMap<String,String>(numCols);
for (int c=1; c<=numCols; c++) {
cols.put(md.getColumnName(c).toUpperCase(), rs.getString(c));
rows.add(cols);
} finally {
close(rs, stmt, null);
log.exiting(className, methodName, "rows="+rows.size());
return rows;
public void close(ResultSet rs, PreparedStatement st, Connection cn) {
if(rs!=null)try{rs.close();}catch(SQLException e){log.severe(e.toString());}
if(st!=null)try{st.close();}catch(SQLException e){log.severe(e.toString());}
if(cn!=null)try{cn.close();}catch(SQLException e){log.severe(e.toString());}
* Connects to the database specified in the given connectionProperties.
* @param propertiesStream a java.io.InputStream from which to read
* java.util.Properties - Example contents:
* jdbc.driver=com.mysql.jdbc.Driver
* jdbc.url=jdbc:mysql://localhost/test
* jdbc.username=user
* jdbc.password=pass
* @return Connection - an open connection to the given database.
* @throws ClassNotFoundException if the class named in the
* jdbc.driver property can't be initialized.
* The root cause exception is enclosed.
* Double check the name of the driver class in the properties file.
* Ensure that the named driver class exists is in the classpath.
* @throws SQLException if a database access error occurs.
* The root cause exception is enclosed.
* Check the jdbc.url, jdbc.username, and jdbc.password properties.
private Connection connect(InputStream propertiesStream)
throws IOException, ClassNotFoundException, SQLException
Properties props = new Properties();
props.load(propertiesStream);
String driver = props.getProperty("jdbc.driver");
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
try {
Class.forName(driver).newInstance();
} catch (ClassNotFoundException e) {
throw e;
} catch (Exception e) {
String msg = "Failed to connect to url: "+url+" as "+username+" via driver "+driver;
throw new ClassNotFoundException(msg, e);
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
String msg = "Failed to connect to url: "+url+" as "+username+" via driver "+driver;
throw new SQLException(msg, e);
BTW... search the forums and you'll find something similar to (but a tad more flexible than) this... I wrote a simple "squirrel" in swing about a year or so ago... execute the query, populate a table with the results.
Another trick is the close the database connection on ANY SQLException (to keep it clean)... easy when you use a connection pool.
Cheers. Keith.
Edited by: corlettk on 7/11/2008 00:47 ~~ Wrong file. Doh!
Similar Messages
-
Is Using Static functions advisable from performance(speed) point of view
I was wondering if using a static function would be slower than using a normal function, especially when the function is to be accessed by multiple threads since the same memory area is used each time the static function is accessed from any of the threads. Thus is it right if I say that static functions are not suitable for multiThreaded access ?
I was wondering if using a static function would be
slower than using a normal function,Static functions are linked at compile time, while normal functions have to be linked based on the runtime type of the object they are called on. This lookup means that static function invocations are likely to be faster.
especially when
the function is to be accessed by multiple threads
since the same memory area is used each time the
static function is accessed from any of the threads.If you are talking about the code segment, where the function definition is held, there is only a single copy of each "normal" function as well. The code segment is also read-only, so there are no issues with multiple threads reading and executing the same code at the same time.
There are the normal issues with multi-threaded access to variables in static functions that exist with normal functions.
Thus is it right if I say that static functions are
not suitable for multiThreaded access ?Static functions are no safer than non-static functions in terms of thread safety. On the other hand, it is no more dangerous having multiple threads calling a static function than having multiple threads calling a non-static function on the same object. Exactly the same thread safety techniques apply whether you are working in a static or a non-static context.
With the above in mind, there is a great deal of design difference between static functions and non-static functions. They mean very different things when creating a system, and an operation that is suited for a static function is very likely not appropriate in a non-static context, and vice versa. The important thing is to make sure the design is appropriate for what the system is trying to do.
The most common use of static functions is for object creation... The Factory design pattern uses static methods to create objects of a given type, the Singleton design pattern uses static methods to allow access to itself. -
Documentat​ion tags and static functions
I'm an issue with the documentation tags. It appears that if the function is declared as a static function, it won't show up in the generated documentation (I'm using HTML). For example:
static int ArrayLocation(int i1, int i2, int num_coeff)
Will not show up, but if I remove the 'static' keyword then the function will show up in the generated documentation, i.e.:
int ArrayLocation(int i1, int i2, int num_coeff)
Thanks for any help with this.Hi Wolfgang,
here I send you the documentation of the three functions:
correlate: http://zone.ni.com/reference/en-XX/help/370051P-01/cvi/libref/cvicorrelate/
correlateEx: http://zone.ni.com/reference/en-XX/help/370051T-01/cvi/libref/cvicorrelateex/
normalizedCorrelate: http://zone.ni.com/reference/en-XX/help/370051T-01/cvi/libref/cvinormalizedcorrelate/
I hope this helps you.
Best regards
Suse
Certified LabVIEW Developer (CLD) -
Is Static Function faster than non-static function
Hi,
I am wondering the performances issues of static Vs non-static function.
To prevent object creation, I wrote some static function in my class but I wonder if it really did faster.
any pointers in this direction will be helpful
Jacinleto mattbunch
I still haven't pinpointed exactly the system
bottleneck
but I do think finding a better approach at the
earliest time is betterActually, the generally accepted best practice is to start with good algorithms and data structures, write the code, test the code, profile the code, and then do this kind of nickel and dime optimization after specific bottlenecks have been pinpointed. You absolultely should not make a static/non-static decision based on performance considerations. In fact, the idea that non-static is slower due to object creation is rather muddy thinking. You'd either already have the object and invoke its non-static method, or you'd invoke a static method. In the static case, your design would probably be different anyway, so you can't predict whether time saved by not creating an object would be lost by executing other code paths.
The case in which you count object creation time is if you're creating an object just to call this one method on it and get that method's result, and then not using the object anymore. In that case, the method should be static--not for performance reasons, but rather because the way you are using it suggests that the appropriate design is for it to be static.
>
so many decision to be made in designing software
I wonder if there is any practise I can follow
See "Thinking in Java" by Bruce Eckel, and "Practical Programming in Java" by Peter Haggar -
Can not call a static function with-in a instance of the object.
Another FYI.
I wanted to keep all of the "option" input parameters values for a new object that
i am creating in one place. I thought that the easiest way would be to use a
static function that returns a value; one function for each option value.
I was looking for a way to define "constants" that are not stored in
the persistent data of the object, but could be reference each time
the object is used.
After creating the static functions in both the "type" and "body" components,
I created the method that acutally receives the option input values.
In this method I used a "case" statement. I tested the input parameter
value, which should be one of the option values.
I used a set of "WHEN conditions" that called the same
static functions to get the exact same values that the user should
pass in.
When I try to store this new version, I get the error:
"PLS-00587: a static method cannot be invoked on an instance value"
It points to the first "when statifc_function()" of the case function.
This seems weird!
If I can call the static method from the "type object" without creating
and instance of an object, then why can't I call it within the body
of a method of an instance of the object type?
This doesn't seem appropriate,
unless this implementation of objects is trying to avoid some type
of "recursion"?
If there is some other reason, I can not think of it.
Any ideas?Sorry for the confusion. Here is the simplest example of what
I want to accomplish.
The anonymous block is a testing of the object type, which definition follows.
declare
test audit_info;
begin
test := audit_info(...);
test.testcall( audit_info.t_EMPLOYER() );
end;
-- * ========================================== * --
create or replace type audit_info as object
( seq_key integer
, static function t_EMPLOYER return varchar2
, member procedure test_call(input_type varchar2)
instantiable
final;
create or replace type body audit_info
as
( id audit_info
static function t_EMPLOYER return varchar2
as
begin
return 'EMPLOYER';
end;
member procedure test_call(input_type varchar2)
as
begin
CASE input_type
WHEN t_EMPLOYER()
select * from dual;
WHEN ...
end case;
end;
end;
The error occurs on the "WHEN t_EMPLOYER()" line. This code is only
an example.
Thanks. -
Problem with instantiation in static function
I have a problem with instatiation of objects in a static function. When I do something like this,
public static void test1() {
String s = new String();
everything works fine, but when I try to do the same with a internally defined class, I get the error "non-static variable this cannot be referenced from a static context".
My code looks roughly like this:
public static void test2() {
Edge e = new Edge();
class Edge {
public int y_top;
public double x_int;
public int delta_y;
public double delta_x;
The compiler complains with the mentioned error message over the creation of a new Edge object and I don't have the slightest clue why... :| When I put the class Edge into an external file, it works.
Can anyone help me out there?Your class Edge is a member of the instance of the current class. You don't have an implicit instance of the current class (the "this" reference) in a static context, therefore you get the error.
You need to either declare Edge as static, move it outside your class, or create an explicit instance of the outer class which you use to create instances of Edge ("Edge e = new YourMainClass().new Edge()") -
Function issue of Cross-Reference
Hi,
thanks for your attention on this topic.
there is function issue of Cross-Reference.
when click the Cross-Reference after re-installed the software (adobe Framemaker 7.10), the function is not working. please kindly check the screenshots below:
Error message below:
Please help to check this issue.
software: Adobe Framemaker 7.10
System: windows xp sp3
thanks in advance for your support .
Message was edited by: Lu StevenFire the error log off to the e-mail address indicated in the error message and then contact Adobe Support.
-
I working on .net MVC Entity Framework (Code First).
I am not able to get Datacontext in repository classes functions when i call these functions from a static function in controller . I am getting the Exception
"An exception of type 'System.NullReferenceException'
occurred in YYYYYY.Web.dll(Default
project dll) but was not handled in user code
Additional information: Object reference not set to an instance of an object."
i need to call static functions since i had to call some functions asynchronously.Like Report generation
This works perfectly fine when called from a non static function in controller.
Thanks in advance
PunnooseBut when i call a function in repository class, With dependency Injection(NInject).
eg:-
public Batch GetBatchDetail(string batchID)
return this.db.Batches.Where(x => x.ID=batchID).FirstOrDefault();
Db is Datacontext
I am getting the Exception "An exception of type 'System.NullReferenceException'
occurred in YYYYYY.Web.dll(Default
project dll) but was not handled in user code
Please do help me
regards
punnoose -
Hi,
Could somebody tell me if i can embed a static function (ABAP) in an XSLT.
Thanks in advance
RachanaHi,
Thanks a lot and this should help me. But I'm not that well-versed in XSLT.
Hence,
I'm getting an xml namespace not defined error now.
my XSLT looks like this
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="no"/>
<xsl:template match="TaskType">
<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0">
<asx:values>
<TASKTYPEDESIGN>
<SBTM_CR_TT_DESIGN>
<ORIGINAL_LANG>
<xsl:value-of select="../@origLang"/>
</ORIGINAL_LANG>
<sap:call-external class="CL_SBTM_XML_CONVERSION" method="GET_SYLANGU">
<sap:callvalue param="EXTERNAL" select="../@language"/>
<sap:callvariable param="INTERNAL" name="SY_LANG"/>
</sap:call-external>
</SBTM_CR_TT_DESIGN>
</TASKTYPEDESIGN>
</asx:values>
</asx:abap>
</xsl:template>
I tried to fit in that code there...but i guess this is not the way.
please help -
Abstract class and static function
Please tell me that why a static function can't be made abstract?
Thanks.
Edited by: RohitRawat on Sep 9, 2009 7:45 AMRohitRawat wrote:
Please tell me that why a static function can't be made abstract?
Thanks.Because the method belongs to the class. -
Member /static function and procedure
hi guys,
i'm trying to figure out diffrerences between the following;
1. member function and static function
2.*member* procdure and static procedure.
i wanna know when to use them when creating an object type.thanks.hope this enlighten you
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/objects.htm#CHDEFBEA -
Using static function in c++
Hi,
I'm using an static function on C++ program, as :
static int lRead(char ptr, Socket pSock);
but when I compiled recived the following error:
Error: "static" is not allowed here.
any idea about how do i need to set static functions and variables?
regards,You really should provide more information, but the statement looks fine. Probably, you've got a syntax error earlier in the translation unit, possibly in an include file.
... Dave -
How do i create a static function in a class and implement ActionListener?
i am trying to create a pop up dialog box in a seperate class.
and i want to make the Function static, so that i only need to access it with the class name.
But how do i have a ActionListener ?
everything in a static function is static rite?import java.awt.*;
import java.awt.event.*;
public class StaticFunction
Dialog dialog;
private Panel getUIPanel()
Button button = new Button("show dialog");
button.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
if(dialog == null)
dialog = OutsideUtility.showDialog("hello world");
else if(!dialog.isVisible())
dialog.setVisible(true);
else if(dialog.isVisible())
dialog.dispose();
dialog = null;
Panel panel = new Panel();
panel.add(button);
return panel;
private WindowListener closer = new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
public static void main(String[] args)
StaticFunction sf = new StaticFunction();
Frame f = new Frame();
f.addWindowListener(sf.closer);
f.add(sf.getUIPanel());
f.setSize(200,100);
f.setLocation(200,200);
f.setVisible(true);
class OutsideUtility
public static Dialog showDialog(String msg)
Button button = new Button("top button");
button.setActionCommand(msg);
button.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
Button button = (Button)e.getSource();
System.out.println(button.getActionCommand() +
" from anonymous inner listener");
button.addActionListener(new ButtonListener());
Button anotherButton = new Button("bottom button");
anotherButton.setActionCommand("another button");
anotherButton.addActionListener(localListener);
Panel north = new Panel();
north.add(button);
Panel south = new Panel();
south.add(anotherButton);
Dialog dialog = new Dialog(new Frame());
dialog.addWindowListener(closer);
dialog.add(north, "North");
dialog.add(new Label(msg, Label.CENTER));
dialog.add(south, "South");
dialog.setSize(200,200);
dialog.setLocation(425,200);
dialog.setVisible(true);
return dialog;
private static WindowListener closer = new WindowAdapter()
public void windowClosing(WindowEvent e)
Dialog dialog = (Dialog)e.getSource();
dialog.dispose();
private static ActionListener localListener = new ActionListener()
public void actionPerformed(ActionEvent e)
Button button = (Button)e.getSource();
System.out.println(button.getActionCommand() +
" from localListener");
private static class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent e)
Button button = (Button)e.getSource();
String ac = button.getActionCommand();
System.out.println(ac + " from ButtonListener");
} -
How to trace static functions inside binary?
Hello Everybody
Is it possible to trace all statically linked functions inside some application with DTrace?
Here is an explanation. I have an application with source code like this:
int main(int argc, char * argv[])
custom_init();
�
void custom_init()
function1();
function2();
�
This code compiled into one binary so all functions like function1, function2 and so on are �statically linked�. I�d like to see calls tree say for function custom_init. I do not know all function names that maybe called from custom_init so I need to log everything down from custom_init.
Is this possible with DTrace if I only have a binary and it contains symbolic info?
Thank youjonathan
Thanks, I got huge list of function names with
supplied command (# dtrace -l -n
'pid$target:myprog::entry' -c /myprog)
Now I'd like to trace all that comes from function
myfunc() inside binary myprog - how do I do this?The usual idiom for this is something like:
# cat > trace.d <<EOF
#!/usr/sbin/dtrace -s
#pragma D option flowindent
pid$target:a.out:myfunc:entry
self->on++;
pid$target:a.out::entry
/self->on/
pid$target:a.out::return
/self->on/
pid$target:a.out:myfunc:return
/self->on/
self->on--;
pid$target:a.out:myfunc:return
/self->on <= 0/
exit(0); /* we've gotten the data we wanted, so exit dtrace */
EOF
# chmod +x trace.d
# ./trace.d -c 'command args'
...This will only get the static functions in the binary; to get all shared library functions as well, s/:a.out::/:::/g.
Inside the {}s for :entry and :return, you can do additional work; for
example, you could print a nanosecond timestamp:
trace(timestamp);
or (for ::return) the return value:
trace(arg1);
etc.
Cheers,
- jonathan -
Static function behaviour...
what happns when a static function is used from several classes simultaneously,,,,,,...
will it be multithreaded or synchronized or will it become unstablePotentially, just like an object field used in a regular non-synchronized method. Ordinary local variables are fine, though.
Think of static methods and variables as being attached to the Class object instead of an object instance.
Maybe you are looking for
-
I am unable to retrieve my emails since yesterday. I called Time Warner Cable, my Internet provider, but they could not help me; they stated that the settings had changed, since they were upgrading. I adjusted the settings, but still get an error m
-
Slideshow Export over QuickTime didn't work
Hi, today i try after a long time (and first time with iPhoto 8) an export over QuickTime. But the first time ever in my iPhoto history i have a big problem who i can't fix and i didn't found any informations here what i can do. So... If i create an
-
I got a new laptop for college and all my music is on my computer at home. I came home this weekend expeting to be able to use homeshare to transfer my music to my laptop. I went through step by step how to start homeshare from the apple website an
-
I plugged something else into Headphone jack
I unplugged my headphones, and plugged in a power source for an electronic keyboard but it had the same head as headphones (I don't know why i did it, I just did). Then I plugged my headphones back in and tried to listen to it and music only comes ou
-
Oracle 10gR2 (10.1.2.0.0)
is there any way to install 10gR2 (10.1.2.0.0) on unbreakable Linux ? i had install 10.1.2.0.2 on unbreakable but it's not possible installation 10.1.2.0.0 ! ! !