Mutlithreaded static function question
I want to know if a static function is thread safe.
Lets say I have two static functions in a class foo
public class foo
// vars
public static String stat = "";
//bad - not threadsafe
public static String bad( String test );
stat = test +" is mine";
return (stat);
//maybegood
public static String maybegood(String test );
String local_string_in_static = test+" is mine";
return local_string_in_static);
I am pretty sure that the first is not threadsafe, because the external variable stat can be altered by other threads. My question, is the function maybegood threadsafe because it uses a local string, or is the local string also psuedo-static because it is in a static funciton?
Thanks.
>
I am pretty sure that the first is not threadsafe,
because the external variable stat can be altered by
other threads. Correct.
My question, is the function maybegood
threadsafe because it uses a local string, or is the
local string also psuedo-static because it is in a
static funciton?It is a local string even though it appears in a static method. No different than if it was in a non-static method.
So it is safe.
Similar Messages
-
Question about synchronized static function.
Hi, everyone!
The synchronized statement often deals with an object (called monitor).
But a static function can be invoked without an object.
So if a static function is declared as static, what is the function of
static and synchronized here? Which lock it is using?
Can you give me a simple expplanation?
regards,
GeorgeHence try and avoid synchronizing static methods.
Try and use non static method if you are doing
multithreaded programming. That way you can have lockWell, I avoid static methods, not just when doing multithreading, but not for the reason you mention.
objects which allow non interfering methods to be
accessed in parallelThats easy to do with static methods anyway:
class Foo
static Object lock1 = new Object();
static Object lock2 = new Object();
static void method1()
synchronized( lock1 )
static void method2()
synchronized( lock2 )
}Maybe I just missunderstod you... -
Hi
I was wondering ,If I have multiple threads accessing a certain stateless static function,
do I have to worry about synchronization?
eg lets say my function is:
public static int addup(int a,int b,int c)
ans = a + b + c;
return ans;
}Will each thread create its own instance of this function on the stack or will they all use the same one
possibly causing synchronization problems?
If indeed there is no synch problem here then shouldn't any stateless function be declared as static?Aharon wrote:
public static int addup(int a,int b,int c)
ans = a + b + c;
return ans;
If this does compile, it's not stateless. ;-)
To answer the question: Yes, stateless static methods are thread safe. And no, not every stateless method should be static as this prevents the method from being overwritten in subclasses. (On the other hand, this does mean that every private, stateless method may be - and IMHO should be - static.) -
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()") -
Can anyone explain this to me, please. It's a static section question.
Can anyone explain this to me, please. It's a static section question.
I came across the following style of programming recently and I would like to know what the Static section is actually doing in the class. Thx.
Here is the code.
public class ClassA {
private static Hashtable ClassAList = new Hashtable();
private ClassB cB;
private Vector goodLink;
private Hashtable classCList;
static
ClassA cA = new ClassA();
ClassAList.put("whatever", cA);
public static ClassA getClassA()
return (ClassA) ClassAList.get("whatever");hi,
The static section shall be loaded before it's constructor is called. (i.e at the time of loading the class). Therefore making it available for any other objects to call.
hope this clarifies ur question
prasanna -
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. -
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! -
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 -
SD & FI BI functional Questions
Hi Experts,
I need to ask some questions to customer on SD & FI functional related questions for BI Analytical reports..
Already cutomer implemented Data ware house Informatica with congnos reporting tool.
right now they want to implement BI.
please any one can share on what type functional questions could ask the customer.
Advance Thanks,
Bala.Hi,
A few more pointers.
Start with Reports. What the client is using. What he is expecting.
If he got existing reports map the fields with Business Content BW Fields. Go to Business content and make a list of queries which are delivered from SAP. Explain them the KPI's. This should be good to start with. Also check the Tcodes they use.
Look for DataSources that get data from theses Tcode's.
Project Preparation (Initial stuff -- Do a conceptual review after this phase requirements gathering)
Collect requirement thru interviews with Business teams /Core users / Information Leaders.
Study & analyze KPI's (key figures) of Business process.
Identify the measurement criteria's (Characteristics).
Understand the Drill down requirements if any.
Understand the Business process data flow if any.
Identify the needs for data staging layers in BW (i. e need for ODS if any)
Understand the system landscape.
Prepare Final Requirements Documents in the form of Functional Specifications containing:
Report Owners, Data flow, KPI's, measurement criteria's, Report format along with drilldown requirements.
Hope this helps.
Thanks,
JituK -
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");
} -
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.
Maybe you are looking for
-
Office 2013 updates fail on computers with Access 2013 installed
I have about 10 workstations with the combination of Windows 7 enterprise 32 bit, Access 2013 and Office 2007 installed. SCCM offers up both Office 2007 and Office 2013 updates to these machines, but the Office 2013 updates, fail to install. The same
-
Hi, I have completed all the ten chapters in the SRDemo tutorial and when i run the SRList.jspx it is been running and will ask for the username and password so i am logging as username:bernst,password:welcome. When it opens in the browser it display
-
How to get RAM Preview in PP CS5?
Hello, I'm recently trying out premiere, and the biggest thing that is bothering me right now is that I can't find the RAM preview. I don't have the required graphics card to get the Mercury Playback Engine, but I would at least expect to be able to
-
Partitioning Question - range partition?
Hello all we have an issue with the amount of data we have in a particular schema that we are using to store production metrics. I have looked at a few options and are now trying to design a solution using partitioning. At a very high level we have d
-
Release Strategy not updated in PR
Hello, We had a purchase requisition that was released manually via ME54n. The status of the PR is "approved" (which it should be) in the tables in SAP. (We have tables in SAP for the front end portal to view the status of PRs). However, when we loo