Understanding 'synchronized' keyword
Hello,
I have a main class (ClsA.java) that extends JFrame, the frame contains one JButton and one JTextArea.
When pressing the button x number of threads are created and each thread will write a couple of messages in the JTextArea by using a method in ClsA.java, the method looks like this:
public void output(String output){
this.taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
}everything works fine, but sometimes a few messages from different threads end up on the same line in the JTextArea. To fix this I changed the output method to this:
public synchronized void output(String output){
this.taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
}I have just added the synchronized keyword that will make the the system associates a unique lock with every instance of ClsA (there is only one). This works alomost fine, but when I increase the number of concurrent threads the application freezes(I�m not able to scroll down in the textarea or press the button)? Why does it freeze? I have tried adding notifyAll() at the end of the output method but there is no difference. What am I doing wrong here? The acquisition and release of a lock is done automatically and atomically by the Java runtime system.....but can it still end up in a freeze?!
Greatfull for any suggestions!
//Anders =)
Hi,
Use
public void output(String output){
SwingUtilities.invokeLater(new Runnable()
public void run()
taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
so as to update the text area only in the event thread!
Roger
Similar Messages
-
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. ;) -
Use of synchronized keyword with portal services
Hi,
Can you confirm me if it is true that a portal service is a Singleton? I mean, when using an instance variable of a portal service I am able to set the value of the instance variable using one client app and get it afterwards using another client app. So we are talking about the same and only instance of the portal service, right?
If this is true how can I synchronize the access to a portal's service method? I tried to mark
the method syncronized (in the interface) but then I realized that this issues a compiler error because one can not mark an interface method synchronized. So can I mark the implementation class instead? That is, can I leave the interface without the synchronized keyword for the method and still mark the implementation of the method in the service class as syncronized? Does this work?
Thanks in advance,
DizHi,
Portal service is not a Singleton, as the name says a service is just provider for services which does not save state between two requests/applications.
So if you want to save state, then use some session variables to save it.
In a cluster installation, each server node has its own portal services, so if you save state in service, then your application should save this state on all servers of the cluster.
So you should change your approch.
http://help.sap.com/saphelp_nw70/helpdata/en/e3/fab74247e2b611e10000000a155106/frameset.htm
Greetings,
Praveen Gudapati
[Points are always welcome for helpful answers] -
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 -
Dont understand Synchronized method to complete program
I'm trying to finish theis program but i don't understand synchronized methods. I checked the java tutorial and i am still confused. Can someone help me approach finishing this program. Here is the spec and the first part of the program i have done.
===================================================================================
When the above is working, create a class called Food. The objective here is to demonstrate the behavior of threads that share data, and use synchronized methods.
Simulating an animal eating, simply means that the thread will sleep for some length of time.
There is one instance of the Food class that is shared by both of the animals. Pass it to the constructor of the Animal class.
There is a method in the Food class called eat(). This method is synchronized, i.e., only one Animal can be eating at a time.
The rabbit eats the food (the thread will sleep) for a longer time than the turtle, thus giving an advantage to the rabbit.
But, the turtle must wait until the rabbit is done eating until it can eat, so the advantage is reduced. Print out a message in the eat method when the animal begins to eat, and when it is done eating. Indicate which animal it is that starts to eat.
Try making the eat method not synchronized, and observe the different behavior if the eat method allows the rabbit to begin eating before the turtle is done eating
import java.util.Random;
public class Animal extends Thread implements Runnable{
private String name;
private int position;
private int speed;
private int restMax;
public static boolean winner = false;
Random random = new Random();
public Animal (String name, int position, int speed,int restMax){
this.name = name;
this.position = position;
this.speed = speed;
this.restMax = restMax;
public void run(){
try{
while( winner == false){
if(position < 100){
Thread.sleep(random.nextInt(restMax));
position += speed ;
System.out.println(name+" is in "+ position+" position ");
if (position >= 100){
winner = true;
System.out.println(name+" is the winner");
System.exit(0);
catch(InterruptedException e){
public static void main(String[] args){
Animal rabbit = new Animal("trix", 0, 5, 150);
Animal turtle = new Animal("maury",0, 3, 100);
rabbit.start();
turtle.start();
}Example:class Donkeyphile implements Runnable {
private Donkey donkey;
private long time;
Donkeyphile(Donkey donkey, long time) {
this.donkey = donkey;
this.time = time;
public void run() {
for (int i = 0; i < 10; i++) {
donkey.love(time);
public static void main(String[] args) {
Donkey donkey = new Donkey();
Donkeyphile jverd = new Donkeyphile(donkey, 500);
Donkeyphile yawmark = new Donkeyphile(donkey, 100);
Thread j = new Thread(jverd, "Jverd");
Thread y = new Thread(yawmark, "Yawmark");
j.start();
y.start();
class Donkey {
synchronized void love(long time) {
String name = Thread.currentThread().getName();
System.out.println(name + " hugs the donkey.");
try { Thread.sleep(time); } catch (InterruptedException e) { }
System.out.println(name + " releases the donkey.");
} -
How can see the effect of synchronized keyword
hi
I read the follwoing code in some books:
class W{
static private int count=0;
public String name;
int no;
private static synchronized int addW(){ return ++count; }
public W(){ no= addW(); }
}but I think that synchronized keyword in this code doesn't have an effect, i.e., if we remove it, the output would be ok, can anyone able to change this code such that the output becomes different depend on existance of synchronized keyword.
thank youbut I think that synchronized keyword in this code
doesn't have an effect, i.e., if we remove it, the
output would be ok,Well, you're mistaken.
can anyone able to change this
code such that the output becomes different depend on
existance of synchronized keyword.No change is necessary. Synchronization is required to ensure proper behavior for the code presented. -
Implementing method and add 'synchronized' keyword
Basically, I have the following scenario:
public interface ClassA {
public void doSomething(String s);
} Then, the class that implements ClassA:
public class ClassB implements ClassA {
public ClassB() {
doSomething("Testing");
public synchronized void doSomething(String s) {
// Do something...
public static void main(String[] args) {
ClassB cb = new ClassB();
}ClassB implements the doSomething(String s) method but adds the 'synchronized' keyword. I compile this and get no errors, but I wanted to make sure that adding the 'synchronized' keyword to a method that is implemented is a legit thing to do.
The reason I am asking is that Rational Rose does not generate code for this situation correctly, and before I call tech support, I wanted to make sure that it is not a problem with what I am doing. When Rose generates the code, it gives a warning that the method doSomething was not implemented and it adds the method. I then have two methods called 'doSomething'.
Thanks'synchronized' is not part of the method signature. But if you want to work around the problem, instead of declaring the method as synchronized, simply do this instead, which is equivalent (for non-static methods):
public void doSomething(String s) {
synchronized (this) {
// your code here -
Use of Synchronized Keyword / Concurrency
I have a program which makes two Writer threads (they add 1 to a shared
counter), A sampler Thread (like a reader thread � it also displays the
data held by the other thread). I have been playing around with the
synchronised keyword � but I am not sure how to interpret the
results..I'll post the code first....
the shared counter------------------------------
package sycTest;
public class Counter
{public int val = 0;}
the sampler / reader class----------------------
package sycTest;
public class Sampler extends Thread
private Counter c;
private MyThread A, B;
public Sampler ( MyThread A, MyThread B, Counter c ) {
this.A = A;
this.B = B;
this.c = c;
public void run()
while(true)
try { sleep( 1000 ); } catch (Exception x) { }
System.out.println
"A count = " + A.getCount() + ", " +
"B count = " + B.getCount() + ": " +
"A + B count = " + (A.getCount() + B.getCount()) + ", " +
"shared counter = " + c.val
the main class to get things started------------------------------------
package sycTest;
import java.util.Random;
public class Main
public static void main( String[] args )
Counter c = new Counter();
MyThread A = new MyThread( c );
MyThread B = new MyThread( c );
A.start(); B.start();
// create and start Sampler thread in one step
new Sampler( A, B, c ).start();
// main thread waits to read a carriage-return.
try {
System.in.read();
catch( Exception e ) { }
System.exit(0);
/* rand_sleep function is used to generate "random switching" behaviour
assuming n > 0,
rand_sleep( n ) sleeps a random time between 0 and n millisec.
private static Random rand = new Random();
public static void rand_sleep( int maxms ) {
int ms = rand.nextInt() % maxms; // - maxms < ms < maxms
int amt=(ms + maxms + 1)/2;
try { Thread.sleep(amt); } catch(Exception e) { }
the thread / writer class-------------------------------------------
package sycTest;
public class MyThread extends Thread
private Counter sharedCounter;
public MyThread( Counter c ) { this.sharedCounter=c; }
private int count=0;
public int getCount() { return count; }
public void run() {
while(true)
// simulate non-critical section by sleeping a "large" amount
Main.rand_sleep(1000);
synchronized (sharedCounter) {
criticalSection();
//Main.rand_sleep(1000);
++count;
private void criticalSection() {
int x=sharedCounter.val + 1;
Main.rand_sleep( 100 );
sharedCounter.val=x;
--the question!
The idea is that running the main methods gives something like
A count=13, B count=10: A + B count=23, shared counter=23
(where A and B are writer threads)
If I take out the synchronised keyword in the MyThread class, things get
much worse...the 'personal' totals of A and B do not equal the total
held in the shared counter rather quickly..
criticalSection();
//Main.rand_sleep(1000);
++count;
eg
A count=13, B count=10: A + B count=23, shared counter=22
However, adding the synchronised keyword (eclipse suggested
�sharedCounter� as the argument � the notes seem to suggest �this�, but
if I do that the synchronised keyword seems much like the example above...
synchronized (sharedCounter) {
criticalSection();
++count;
this makes it much better...I never saw it get the counts 'wrong'
eg
A count=56, B count=72: A + B count=128, shared counter=128
Now comes the confusing bit...when I add some time between the 2 methods
within the sychonized block...
synchronized (sharedCounter) {
criticalSection();
Main.rand_sleep(1000);
++count;
Then mismatches appear very quickly, the program behaves very similarly
to when it didn't have the synchronised keyword...
Why is this? Is it because the Sampler class is asking what the values
of the shared and personal counters during the �Main.rand sleep(1000)�
call??
The other question I was hoping someone could help me with, is pointing
out what the difference is between �synchronized (sharedCounter)� and
�synchronized (this)� is in this context. Why does the later not do
anything in this example?
Thanks,
JulianHello Julian,
you're Sampler thread reads the different counters without any synchronization. He may call A.getCount() and get 5 back, then yield and then ask for c.val which was increased by A in the meantime. Or A increases it's own counter, then yields and lets the Sampler output nonsense.. ;)
To clear up the confusion surrounding Thread.sleep(long): It would be a waste to do nothing while the thread is sleeping, so another thread gets to play. Since the other MyThread is waiting on sharedCounter's monitor and the sleeping thread still owns it<sup>1</sup> the Sampler thread gets the execution time. Now the sampler gets going and you know the rest.
1: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.9
EDIT: In future, use code-tags:
class MyClass {
private int myField;
}will turn into
class MyClass {
private int myField;
}With kind regards
Ben
Edited by: BenSchulz on Mar 24, 2008 11:45 AM -
Not understanding "synchronized key word"
Hello all,
I have a singleton class as below
package test;
public class TestClass {
private final static TestClass testClass = new TestClass();
private TestClass() {
super();
// TODO Auto-generated constructor stub
public static TestClass getInstance() {
return testClass;
public synchronized void keepRunning() {
for (int i = 0; i < 10454564564l; i++) {
for(int j=0 ; j<242342342342l;j++){
System.out.println(j);
}And two other classes which take the reference and call keepRunning simultaneously as shown
package test;
public class TestClass1 {
public TestClass1() {
super();
// TODO Auto-generated constructor stub
* @param args
public static void main(String[] args) {
TestClass testClass = TestClass.getInstance();
testClass.keepRunning();
}and
package test;
public class TestClass2 {
public TestClass2() {
super();
// TODO Auto-generated constructor stub
* @param args
public static void main(String[] args) {
TestClass testClass = TestClass.getInstance();
testClass.keepRunning();
}Now if i run both TestClass1 and TestClass2, i can see sysouts from both the programs. I am not able to understand Why synchronized key word allowing TestClass2 to acess the code.(As there are no shared variable)ohhhhhhhhhhh!!!!! Sorry ! I am ashamed of myself!! :-(
-
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. -
Help needed understanding final keyword and use 3
Hi Everyone,
I have been studying a book on multi-threading and have inadvertently come accross some code that I don't really understand. I am wondering if anybody can explain to me the following:
1). What effect does using the final keyword have when instantiating objects, and
2). How is it possible to instantiate an object from an interface?
public class BothInMethod extends Object
private String objID;
public BothInMethod(String objID)
this.objID = objID;
public void doStuff(int val)
print("entering doStuff()");
int num = val * 2 + objID.length();
print("in doStuff() - local variable num=" + num);
// slow things down to make observations
try{
Thread.sleep(2000);
}catch(InterruptedException x){}
print("leaving doStuff()");
public void print(String msg)
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ": " + msg);
public static void main(String[] args)
final BothInMethod bim = new BothInMethod("obj1"); //Use of final on objects?
Runnable runA = new Runnable() //Creating objects from an interface?
public void run()
bim.doStuff(3);
Thread threadA = new Thread(runA, "threadA");
threadA.start();
try{
Thread.sleep(200);
}catch(InterruptedException x){}
Runnable runB = new Runnable()
public void run()
bim.doStuff(7);
Thread threadB = new Thread(runB, "threadB");
threadB.start();
}If you know of any good tutorials that explain this (preferably URL's) then please let me know. Thanks heaps for your help.
Regards
Davofinal BothInMethod bim = new BothInMethod("obj1"); //Use of final on objects?
Runnable runA = new Runnable() //Creating objects from an interface?
public void run()
bim.doStuff(3);
};Here final is the characteristics of bim reference variable and it is not the characteristics of class BothInMethod
This means u cannot use bim to point to some other object of the same class
i.e, u cannot do this
final BothInMethod bim = new BothInMethod("obj1");
bim = new BothInMethod("obj2"); This bim is a constant reference variable which will point only to the object which it is initialized to
and not to any other object of the same class later on.
How is it possible to instantiate an object from an interface?Regarding this yes we cannot create an object from an interface but
but here it is not an interface u are providing the implementation of the interface Runnable
as
new Runnable()
}This now no longer stays an interface but now it is an object that implements the interface Runnable -
Synchronized keyword was not supposed to be reentrant ?
Synchronized block in the below code seems to be working properly as a reentrant code. I've written this to check out the reentrancy by causing a deadlock but it worked without deadlock./* This code might cause to a deadlock */
public class NotReentrant {
public static void main(String[] args) {
final LoggingWidget widget = new LoggingWidget();
Thread t1 = new Thread(new Runnable() {
public void run() { widget.execute(); }
t1.start();
try { t1.join(); } catch (Exception e) {}
System.out.println("You might not going to see this: There is a deadlock !");
/* dummy classes that show the proof */
class Widget {
public synchronized void execute() {
System.out.println(toString() + " (base).execute: synchronized");
synchronized (this) {
System.out.println(toString() + " (base).execute: synchronized (this)");
try { Thread.sleep(500); } catch (Exception e) {}
System.out.println(toString() + " (base).execute");
// .... code
class LoggingWidget extends Widget {
public synchronized void execute() {
System.out.println(toString() + ".execute: synchronized");
super.execute();
System.out.println(toString() + ".execute");
}I perfectly understand how Java monitors work and I also perfectly know that Java synchronized ( aka intrinsic locks ) monitor is re-entrant.
The reason behind my previous post was that I am trying to check out a code which is written in Goetz's book: Java Concurreny in Practice. In there, he gives a code example that leads to a deadlock. Despite, I am aware of the fact that it cannot be occurred, I have given it a shot.
Thanks for the comments. -
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... -
Best position of "synchronized" keyword?
Hi, I have a fairly straightforward question: which one is better/more performant:
synchronized (dirLock) {
try {
FileUtils.forceMkdir(dir);
} catch (IOException e) {
throw new Exception("Could not create storage directory!", e);
}or
try {
synchronized (dirLock) {
FileUtils.forceMkdir(dir);
} catch (IOException e) {
throw new Exception("Could not create storage directory!", e);
}I.e. is it better to wrap the entire try/catch block in a synchronized block, or just the operation I care about?
Thanks in advance,
MaartenIn your example it hardly matters, but in general it is better to synchronize as little as possible, therefore
I prefer your second example. I would use it even with your code, just for consistency.
try {
synchronized (dirLock) {
FileUtils.forceMkdir(dir);
} catch (IOException e) {
... do stuff...
... do more stuff....
throw new Exception("Could not create storage directory!", e);
} -
Need help understanding NEW keyword
I can create a string array a couple of different ways.
Method one:
Dim i As Integer
Dim sarr1(4) As String
For i = 0 To sarr1.Length - 1
sarr1(i) = "12345"
Next
Method two:
Dim sarr2 = New String() {"12345", "12345", "12345", "12345", "12345"}
Are these two methods equivalent?
If I try to declare the arrays by either of the following methods, I get errors.
Method three:
Dim sarr3 As New String(4)
error: Value of type 'Integer' cannot be converted to '1-dimensional array of Char'.
Method four:
Dim sarr4(4) As New String()
error: Arrays cannot be declared with 'New'.
Why isn't method four equivalent to method two except for the initialization?
Regards, MikeMethod 1 and 2 are basically the same. We didn't always have array initializers in the language (method2). That has only been around the past couple of years. Prior to that you had to do some sort of loop to initialize the array like your method 1. Method
2 was added just to make it easier from a syntax point of view. It certainly looks cleaner and you can read one line of code and know what the array is and what its contents are.
The reason method 2 and method 4 are different is because in method 2, you are performing an assignment. It is using type inference so it might not be as clear, but method 2 could be fully written out as
Dim sarr2() As String = New String() {"12345", "12345", "12345", "12345", "12345"}
In which case you can see that it isn't really using the new keyword for the declaration, but for the right side instantiation of a string array, which is then assigned to the declared array variable.
Matt Kleinwaks - MSMVP MSDN Forums Moderator - www.zerosandtheone.com
Maybe you are looking for
-
How to format a date to display the ISO week number in BI Publisher ?
Hi there, I need to format a date to display the ISO week number in BI Publisher. I've tried the following <?format-date:NEED_BY_DATE;'WW'?>, but it returns a week number (1-53) where week 1 starts on the first day of the year and continues to the se
-
In my SOA Composite, Can I use file/FTP adapter to get the EDI X12 850
Our requirement is to build a SOA Composite to dump all the details in a EDI X12 850 ( Purchase order ) document in to a database table. In my SOA Composite, Can I use file/FTP adapter to get the EDI X12 850 element details to map them to a base base
-
Acrobat 7.0 Prof. - Auf Grund eines Speicherschadens wird die Anwendung beendet
Does anybody know anything about a solution to this error message? translated: "Because of a memory damage the application is closed". Version: Adobe Acrobat 7.0 Professional - English, Français, Deutsch PC, XP SP3. I would be very glad if anybody ha
-
Dynamic configuration variable lifetime?
We are migrating from PI 7.1 to PI 731 and one of our applications uses dynamic configuration variable. It is a custom dynamic config variable saved in the first message (IDOC to PI BPM). We have asynch to synch scenario and send a synchronous messa
-
Office files like Word-to-PDF converter ribbon on Mac side?
Is there a ribbon feature available on the Mac side for converting Office files like Word-to-PDF? http://www.adobe.com/products/acrobat/word-to-pdf-converter.html I have Adobe Acrobat Pro XI and a MacBook Air running Mavericks. Thanks!