How to use Synchronized Keyword
Hi guys,
Sorry if this is a simple question, but I'm not sure about the following:
Suppose we have the class,
Class Foo
public synchronized void bar1() {...}
public synchronized void bar2() {...}
If I have two threads running concurrently, say T1 and T2.
I know that T1 and T2 can't both be in bar1() at the same time right? [It has to be in some serial order]
But, can T1 be in bar1() and T2 be in bar2() at the same time?
I guess the question is, does the synchronized apply to that specific method only? Or rather to the object (which basically limits at most one thread calling that object's synchronized methods)?
Thanks a bunch! :)
-Michael.
Hi Michael,
In general, when you syncronize a block of code, the execution of the block is syncronized ON an object. Any object can function as a lock, and only one thread can have a lock of one object at a time. If one thread already has a lock on an object and another thread tries to acquire lock on the same object, the latter thread will wait until the lock is released.
When you use 'synchronized' in method declaration, it means that the execution of the whole method is syncronized on the object itself (NOT class, if the method is non-static. Static method would be synchronized on the .class object.)
So, if you have more than one syncronized methods, only one of them is executed at a time ON THE SAME OBJECT. The same method can, of course, be executed simultaneously on other objects. Also, if some of the methods are synchronized, but other methods are not, the non-synchronized methods are not affected in any way.
It might be good to note that these two pieces of code have exactly the same meaning:
public synchronized doSomething() {
// do something
}and
public doSomething() {
synchronized (this) {
// do something
}Hope this helps.
Cheers,
Vesa
p.s. It's a good idea to design your code so that one thread will have no more than one lock at a time. If it's possible for more than one thread to have lock on more than one object, there may be a risk of the threads dead-locking, which will crash any program...
Similar Messages
-
Oracle deadlock - how to use "synchronised" keyword in a transaction?
Hi,
I use WL6.1 SP4, Oracle 8.1.6, with some Java objects which execute a
lot
of SQL queries (mixed update, insert and select) using plain JDBC
calls,
and Weblogic connection pools. These objects are called by servlets.
I experienced recently deadlocks when two users call the object at the
same
time (See error below).
I execute the queries using "synchronized" keyword in the following
way:
synchronized (this)
conConnection.setAutoCommit(false);
executeTransaction(myStatement);
conConnection.commit();
executeTransaction is overriden in sub-classes and is the method which
executes
all the queries.
It calls methods in other objects. These methods are not declared as
synchronized.
1) Should they?
2) Should I use the keyword "synchronized" in another way?
3) This part of code is also called when I do only "select"
statements. I guess
it should only be synchronized when we do "update" and "insert" which
could lead
to a deadlock?
4) Do you have any idea why this deadlock occurs as I use the
"synchronized"
keyword, and one thread should wait until the other one has finished?
Thanks for any idea,
Stéphanie
----------------- error:
<ExecuteThread: '4' for queue: 'default'> <> <> <000000> <SQL request
sent to database: UPDATE PARTICIPANT par SET par.PARTICIPANTLASTRANK =
4 WHERE par.IDPARTICIPANT = 8983566>
<ExecuteThread: '11' for queue: 'default'> <> <> <000000> <SQL request
sent to database: UPDATE PARTICIPANT par SET par.PARTICIPANTLASTRANK =
6 WHERE par.IDPARTICIPANT = 8983570>
ORA-00060: deadlock detected while waiting for resource
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1891)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2709)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:796)
at weblogic.jdbc.pool.Statement.executeUpdate(Statement.java:872)
at weblogic.jdbc.rmi.internal.StatementImpl.executeUpdate(StatementImpl.java:89)
at weblogic.jdbc.rmi.SerialStatement.executeUpdate(SerialStatement.java:100)
at bfinance.framework.EDBBLBean.executeSQL(EDBBLBean.java:299)Hi Stepanie,
I'd try to group update statement together. Usually it helps.
Regards,
Slava Imeshev
"Stephanie" <[email protected]> wrote in message
news:[email protected]...
Thanks for your answer.
In the case you describe, is there a way to ensure that tx-2 waits for
tx-1
to be finished before beginning?
My transaction which causes the problem is the following (simplified):
UPDATE tableA SET islast=0 WHERE externalid=myid;
for (int i=0; i< aVector.size(); i++) {
INSERT INTO tableA (id, islast, ranking, externalid) (SELECT
SEQ_tableA.nextval, 1, 0, myid);
UPDATE tableA SET ranking = /*calculated ranking */
WHERE externalid=myid AND islast=1;
UPDATE tableB ....
commit;
tx-1 and tx-2 execute this transaction at the same time. tx-1 begins
The deadlock appears when tx-2 executes the second UPDATE tableA
query.
I don't see how I can avoid to execute these two update queries, so if
I can find another way to prevent deadlock, it would be great!
Stéphanie
Joseph Weinstein <[email protected]_this> wrote in message
news:<[email protected]_this>...
Stephanie wrote:
Hi,
I use WL6.1 SP4, Oracle 8.1.6, with some Java objects which execute a
lot
of SQL queries (mixed update, insert and select) using plain JDBC
calls,
and Weblogic connection pools. These objects are called by servlets.
I experienced recently deadlocks when two users call the object at the
same
time (See error below).Hi. The error you are getting isn't necessarily from a lack ofsynchronization
of your java objects. It has to do with the order in which you accessDBMS
data. You are getting ordinary DBMS deadlocks, which are caused when
two DBMS connections each have a lock the other wants, in order toproceed.
The DBMS will quickly discover this and will kill one transaction inorder to
let the other one proceed:
time 0: tx-1 and tx-2 have started.....
time 1: tx-1: update tableA set val = 1 where key = 'A'
time 2: tx-2: update tableB set val = 2 where key = 'B'
time 3: tx-1: update tableB set val = 1 where key = 'B' (waitsbecause tx-2 has the row
locked)
time 4: tx-2: update tableA set val = 2 where key = 'A' (waitsbecause tx-1 has the row
locked)
This is a deadlock. The solution is to organize your application code sothat every
transaction accesses the data in the same order, eg: update tableAfirst, then update tableB.
This will prevent deadlocks.
Joe Weinstein at BEA
I execute the queries using "synchronized" keyword in the following
way:
synchronized (this)
conConnection.setAutoCommit(false);
executeTransaction(myStatement);
conConnection.commit();
executeTransaction is overriden in sub-classes and is the method which
executes
all the queries.
It calls methods in other objects. These methods are not declared as
synchronized.
1) Should they?
2) Should I use the keyword "synchronized" in another way?
3) This part of code is also called when I do only "select"
statements. I guess
it should only be synchronized when we do "update" and "insert" which
could lead
to a deadlock?
4) Do you have any idea why this deadlock occurs as I use the
"synchronized"
keyword, and one thread should wait until the other one has finished?
Thanks for any idea,
Stéphanie
----------------- error:
<ExecuteThread: '4' for queue: 'default'> <> <> <000000> <SQL request
sent to database: UPDATE PARTICIPANT par SET par.PARTICIPANTLASTRANK =
4 WHERE par.IDPARTICIPANT = 8983566>
<ExecuteThread: '11' for queue: 'default'> <> <> <000000> <SQL request
sent to database: UPDATE PARTICIPANT par SET par.PARTICIPANTLASTRANK =
6 WHERE par.IDPARTICIPANT = 8983570>
ORA-00060: deadlock detected while waiting for resource
at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
atoracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1891)
atoracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
atoracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047
atoracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
atoracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java
:2709)
atoracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:796)
atweblogic.jdbc.pool.Statement.executeUpdate(Statement.java:872)
atweblogic.jdbc.rmi.internal.StatementImpl.executeUpdate(StatementImpl.java:89
atweblogic.jdbc.rmi.SerialStatement.executeUpdate(SerialStatement.java:100)
at bfinance.framework.EDBBLBean.executeSQL(EDBBLBean.java:299) -
Object or Statement Block locking using synchronized keyword in java
Hi ,
Can anyone tell me how java is implementing the Object locking and the code block locking mechanism using the 'synchronized' keyword internally??
Thanks in advance
RajThe JVM implements a concept known as a monitor using a combination of direct implementation and support by the operating system. For more detail, refer to the Java JVM and language specifications.
Chuck -
How to Use synchronous RFC calls during test run for remote accesses
there is a Setting for the usage of RFC accesses from a tested system
using eCATT.
'X' - Use asynchronous RFC calls during test run for remote accesses
' ' - Use synchronous RFC calls during test run for remote accesses
I developed an eCATT as following :
SAPGUI ( SAPGUI_1 , Target_system_1 ).
SAPGUI ( SAPGUI_2 , Target_system_2 ).
My question is how to run the eCATT in a synchronous RFC calls
PS: I do not want to change the Target_system to the same one in the
above script of ecatt.Because I need to run it in 2 different Target
systems sometime.
for example, I give a Target_system_3 when run this eCATT
I want the SAPGUI_1 and SAPGUI_2 run the Target_system_3 but not the
Target_system_1 or Target_system_2 .
Could you please tell me how to make it without the changes in script?
Edited by: Weitong Liu on Mar 24, 2011 9:44 AMHi Liu,
Weitong Liu wrote:
> ' ' - Use synchronous RFC calls during test run for remote accesses
This is the standard option value. Asynchronous are not the standard way and used only for very special purposes.
Weitong Liu wrote:
> I developed an eCATT as following :
> SAPGUI ( SAPGUI_1 , Target_system_1 ).
> SAPGUI ( SAPGUI_2 , Target_system_2 ).
> My question is how to run the eCATT in a synchronous RFC calls
The commands will be executed in sequence. So each call will be synchronously replayed against TS1 and TS2.
What is you issue with this standard procedure?
Kind regards,
Christoph -
How to Use native keyword in java programming
Hi ,
I am using JDK 1.6.0_11 , and i was trying to create a java program using "native" keyword ,
i got the sample code for the same from the site : - http://www.javaworld.com/javaworld/javatips/jw-javatip23.html
But when i type this command " C:\javah -stubs Happy " following error occurs
" Error: JNI does not require stubs, please refer to the JNI documentation. "
then typed " c:\javah -jni Happy" without any error .
After that i wrote a HappyImpl.c as mentioned in the above tutorial
#include <StubPreamble.h> /* Standard native method stuff. */
#include "Happy.h" /* Generated earlier. */
#include <stdio.h> /* Standard C IO stuff. */
void Happy_printText (struct HHappy *this)
puts ("Happy New Year!!!");
then it is not compling and error is
"unable to open included file StubPreamble.h file
unable to open included file Happy.h file "
Please help me . i want to use native method , i did exactly the same in tutorial at above link.
Thanks & Regards
Mannatyou do need to know how to use your C compiler... It quite clearly can't find those files which indicates that you didn't tell it where to find them.
-
How to use Synchronized method when creating our own controls
I don't know how to use the synchronized method when creating our own activex like controls to speed up the application.
[url http://java.sun.com/docs/books/tutorial/essential/threads/multithreaded.html] here you go
-
How to use Multiple Keywords in a Search Form?
I'm currently using a bind variable on the view object to generate a search form where the user enters one keyword that is applied to the WHERE cause of the SQL query.
The problem is I'm trying to implement a Google-type search, where the user can enter multiple keywords in a single text input area. I then want to parse out those keywords and search the database on each keyword (similar to a Google search.) Can someone please help me point me in the right direction as to where / how to code in the appropriate hooks to accomplish this?
Example:
(user input) Enter Search Keywords: keyword1 keyword2 keyword3.. keywordn
database query:
Select item from table where (desc like '%keyword1%') or .. (desc like '%keywordn%') or
(category like '%keyword1%') or .. (category like '%keywordn%')Can't you parse what was entered and create a number of view criteria rows, then apply them? At that point, they would be 'OR'd together'.
-
How to use synchronized(obj) ?
Hi, dear all:
It may be a basic lesson, but I need to know how synchronized(obj) exactly work.
Code as below :
Boolean flag = new Boolean(false);
......// some other codes
synchronized(flag)
flag = Boolean.TRUE;
flag.notify(); // or flag.wait();
}Why the notify() or wait() will cause IllegalMonitorStateExcption ?
If I can't change flag object in synchronized block, how can I change its value ?
In JDK documents, there seems no method of Boolean class can do this job ....
Or, It must be written as below ?
boolean bflag = false;
Boolean flag = new Boolean(false);
synchronized(flag)
bflag = true;
flag.notify();
} Thank you for help !
Edited by: jesvh on Dec 2, 2008 11:54 PMjesvh wrote:
If I can't change flag object in synchronized block, how can I change its value ?You need to synchronize on something else.
Boolean flag = new Boolean(false);
Object lockObject = new Object();
synchronized(lockObject )
flag = Boolean.TRUE;
lockObject.notify();
} -
How to use LIKE keyword in a select statement
Hi:
I want to use the following sql statement,
String str = "xyz";
String query="Select * from tab where col like '"+str+"' '%' ";
Kindly suggest
TIA% is a wildcard in the like clause, so:.
String str = "xyz";
String query="Select * from tab where col like '%"+str+"%'"; -
Shall I use synchronized keyword?
Hi there!
I have made a small client-server applikation with RMI.
The server has a connection to a database (only one connection). On the server I have also placed the SQL-queries in separate methods that can be invoced from the clients. The question is:
Do I have to sychronize these methods that access the databse from the one and only database connection? Or can several clients that invoce the same method simultanously use the same one and only database connection?
Thanks in advance!
/MackanAccording to my experience, the connection can be shared among multiple threads, but the statements and resultsets must be in method scope.
-
How to use chain and endchain keywords?
Hi i have got a requirement where i have to use chain and endchain keywords can anyone help me with the sample code how to use this keywords?
Hi,
Within a chain block, you must use ON CHAIN-INPUT addition. The module is then called if the conteents of at least one screen field within CHAIN block have changed from their intial value.
Also, there is ON CHAIN-REQUEST addition, this module is called if user changes changes contents of atleast one screen field within CHAIN block..
ON CHAIN-INPUT--
PROCESS AFTER INPUT.
CHAIN.
FIELD : <Field name 1>,
<Field name 2>.
MODULE <module> ON CHAIN-INPUT
ENDCHAIN.
ON CHAIN-REQUEST--
PROCESS AFTER INPUT.
CHAIN.
FIELD : <Field name 1>,
<Field name 2>.
MODULE <module> ON CHAIN-REQUEST
ENDCHAIN.
I hope u find this helpful..
write brief about ur requirement??
Regards,
Vikram -
Hello everyone, I have a question, how to use the keyword exit?
I want to add something in F1.
Thank you very much!
Edited by: li zhu on Nov 7, 2008 10:35 AM@Shan Palani
Nice Copy Paste Work From;
[SAP Library : Creating Customer-specific Documentation|http://help.sap.com/saphelp_nw04s/helpdata/en/c8/19763443b111d1896f0000e8322d00/frameset.htm]
Regards
Karthik D -
Regarding using 'Enhancement' keyword in ABAP
Hi All,
How to use ENHANCEMENT keyword in abap.
Thks
ShaileshHi,
Check out this
http://help.sap.com/abapdocu/en/ABAPENHANCEMENT.htm
Thanks,
Krishna.. -
Thread confusion - synchronized keyword
Hi All,
I am trying to understand when and how to use synchronized. From my tinkering I have come to a situation that is confusing me:
I have an object with two (unsynchronized) methods (called inc and dec). These methods increment and decrement an Integer field called counter. The methods then sleep for a random amount of time.
The contents of the methods are enclosed with a synchronized block, synchronized to the field 'counter'.
I now create two threads, one calling inc the other dec continuously.
From the output the methods are not synchronizing at all.
If I change the synchronized block to sync to a different variable, eg. 'this' or an arbitrary unused object, the code synchronizes properly.
My question/problem is why does the code not synchronize properly on an object that I am altering in the synchronized block.
A second and (hopfully) related question - is:
synchronized public void foo() {...}syntactic sugar for:
public void foo() {
synchronized (this) {...}
}Thank you for your time in reading this, any help would be very appreciated.
Alex.Peter-Lawrey - Thankyou!!!
It's obvious now - by creating a new Integer object I am synchronizing on different objects in the two methods, hence still failing to lock the other thread out... DOH!
Here's one of the methods for completeness
public void inc() {
synchronized (this) {
System.out.print("Inc = ");
try {
sleep(1001);
} catch (InterruptedException e) {
e.printStackTrace();
counter = new Integer(counter.intValue() + 1);
System.out.println(counter.toString());
} As Integers are readonly I have to intValue, then increment then create a new Integer Object.
Out of curiosity - does the synchronized block fail at this point or does is now apply to the new object until the end of the block is reached?
Thankyou again for your help and returning a small part of my sanity!
Alex. -
Synchronized keyword for simple addition
Hi, I have a function, as given below
{noformat}public static void increment() {{noformat}{noformat} a = a + 1; {noformat}{noformat}}
{noformat}
This function will be called from multiple threads (a is also a static variable).
My question is should I use "synchronized" keyword for this method to avoid unpredictable results? Is there a way to wirte this function without using "synchronized" keyword?
Please suggest.Thanks, jwenting. I wanted to confirm that "synchronized" has to be used.
jwenting wrote:
yes. Depending of course on what you decide to be "unpredictable" :)you understand what "unpredictable" means here ;)
jwenting wrote:
yes, don't use a static variable but a method local one. Of course that will have a totally different effect.Variable "a" should be a class level variable. Yes, local variable has a totally different effect. ;)
Maybe you are looking for
-
How to set a jpg image ContentType of JEditorPane
Hi how can i display an image on a JEditorPane like image.jpg? I tried myEditor.setContentType("image/jpeg") but it still displays characters instead of the image. import java.awt.*; import javax.swing.*; import java.io.*; public class Pagina extends
-
Hello Please...; I don't know how to use time stretch. When i select a music from a cd and import it in garage band. I change the tempo to accelarate but i can hear no change ... Would please help me and tell me if there is anyway. Thank you .... Oli
-
Affichage écran IPOD nano brouillé
Bonjour, L'écran de mon ipod nano est totalement brouillé. Je n'arrive plus à voir les listes de lecture et en changer. L'appareil n'a pas subi de dommages. C'est arrivé d'un coup. Est-ce qu'il existe une solution ? Merci
-
does anyone know how to transfer to a new computer, the list of email addresses that drop down in mail when you start typing an address. that is, not the address book list. thanks
-
BO experts our company plannning to use BOBJ for web dashboard..we are new to BO and would like to clarify the following questions - Can I get the BOBJ architecture diagrams? - How GRC, BPC can be integrated with BOBJ and ECC? - Can we run BOBJ on Ne