synchronized 1 « synchronize « Java Thread Q&A

Home
Java Thread Q&A
1.concurrency
2.Development
3.Exception
4.Notify
5.Operation
6.Socket
7.State
8.synchronize
9.Thread Safe
10.ThreadPool
Java Thread Q&A » synchronize » synchronized 1 

1. In Java critical sections, what should I synchronize on?    stackoverflow.com

In Java, the idiomatic way to declare critical sections in the code is the following:

private void doSomething() {
  // thread-safe code
  synchronized(this) {
    // thread-unsafe code
 ...

2. Avoid synchronized(this) in Java?    stackoverflow.com

Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that synchronized(this) should be avoided. Instead, they claim, a lock on a private ...

3. Are Synchronized Methods Slower In Single Threaded Applications?    stackoverflow.com

I've been debating this to myself for the last few minutes, and I'm seeing reasons for both yes and no. This stemmed from looking at the answers to Java ...

4. Java Synchronized and Threads    stackoverflow.com

I'm having issues with Synchronized not behaving the way i expect, i tried using volatile keyword also: Shared Object:

public class ThreadValue {

    private String caller;
    private ...

5. Where to look for synchronized contention evidence in java?    stackoverflow.com

Our Tomcat web application feels slow when it is used by a couple hundred users. The servers are in a hosting company and their reports doesn't show any problem with bandwith ...

6. Java: synchronized put() with a list of objects    stackoverflow.com

I'm using a LinkedBlockingQueue to handle message objects from other threads. For example, I have something like this:

LinkedBlockingQueue<Message> message_queue = new LinkedBlockingQueue<Message>();

public void run(){
    while(true){
   ...

7. Disadvantage of synchronized methods in Java    stackoverflow.com

What are the disadvantages of making a large Java non-static method synchronized? Large method in the sense it will take 1 to 2 mins to complete the execution.

8. Synchronization in threads for Java    stackoverflow.com

I have a home grown web server in my app. This web server spawns a new thread for every request that comes into the socket to be accepted. I want the ...

9. Synchonization in Java    stackoverflow.com

Quick question. I am pretty new to thread-safe programming, and was wondering if I have something like below, would this be safe from deadlock once compiled and run?

public class ...

10. Why are synchronize expensive in Java?    stackoverflow.com

I am really new to Java and I read that "synchronized" is "very expensive" in Java. All I want to know is what is expensive and how is it expensive? Thanks. ...

11. Java: synchronized method    stackoverflow.com

we have two threads accessing one list via a synchronized method. Can we a) rely on the run time to make sure that each of them will receive access to the method ...

12. Synchronizing on two or more objects (Java)    stackoverflow.com

I have code similar to following:

public class Cache{
 private final Object lock = new Object();
 private HashMap<Integer, TreeMap<Long, Integer>> cache = 
  new HashMap<Integer, TreeMap<Long, Integer>>();
 private AtomicLong ...

13. Is synchronized needed here    stackoverflow.com

I have a java applet. A class inside that applet is creating a thread to do some work, waiting 30 seconds for that work to complete, if its not completed in ...

14. Understanding synchronized    stackoverflow.com

Given this code:

public class Messager implements Runnable {            

  public static void main(String[] args) {   
 ...

15. Java: synchronized(Object) and RejectedExecutionException    stackoverflow.com

I have this problem: I have a few threads which access one object with synchronized(Object) { ... } But sometimes this exception is raised: execute: java.util.concurrent.RejectedExecutionException Why? And what should I do with it? Thanks

16. synchronized(Object) { } problems    stackoverflow.com

I have ran into a perfomance problem where 880 threads are doing synchronized() { method() } in the same time and this has lead to a major perfomance problem. Is it ...

17. Side effects of throwing an exception inside a synchronized clause?    stackoverflow.com

Are there any unclear side effects to throwing an exception from within a synchronized clause? What happens to the lock?

private void doSomething() throws Exception {...}

synchronized (lock) {   
  ...

18. Threaded State Machines in Java    stackoverflow.com

Is there a way of Holding a thread in a State waiting for changes? I mean wait tll something happend (change var, call method, etc..) perhaps it needs using Event Listeners, or synchronized ...

19. Java synchronization question    stackoverflow.com

I was going through some code snippets looking at the synchronization aspect. I believe locking happens on objects. In the case of java we only have references to objects. Java should ...

20. Many Readers, one writer: Do i need to synchronize this?    stackoverflow.com

do i need to synchronize this, when many threads accessing the get Method and only one thread is accessing the setList method?

public class ListContainer {
  private List<String> myList = new ...

21. How to unit test synchronized code    stackoverflow.com

I am new to Java and junit. I have the following peice of code that I want to test. Would appreciate if you could send your ideas about what's the best ...

22. Simple java synchronization question    stackoverflow.com

In Groovy code something simple: #!/usr/bin/env groovy

public class test {
  boolean val
  def obj=new Object()

  def dos() {
    val=false
    ...

23. Is 'synchronized' really just syntactic sugar?    stackoverflow.com

I am new to multithreading, and I wrote this code which prints the numbers 1-10000 by having concurrently running threads increment and print a variable. Here's the code I'm using:

package threadtest;

public class ...

24. Do two synchronized methods execute simultaneously    stackoverflow.com

I have 4 methods (m1,m2,m3 and m4) in a class. m1,m2 and m3 are synchronized method. Also i have 4 threads t1,t2,t3 and t4 respectively. If t1 access the m1 method (synchronized ...

25. How to make two planes land in two different synchronized runways in java?    stackoverflow.com

In my Air traffic Control application, I am trying to land two planes in two different runways. I have done synchronizing of 2 runways, sadly only one plane lands when I ...

26. Using synchronized lists    stackoverflow.com

This is my first time using the synchronized keyword, so I am still unsure of how it exactly works. I have a list that I want to be accessed by multiple ...

27. Are all Java Properties' methods fully synchronized?    stackoverflow.com

I know that the Properties class is a sub-class of Hashtable. So all the inherited methods are synchronized, but what about the other methods of Properties such as store, load, etc? ...

28. Java synchronized question    stackoverflow.com

I'm new to Java Threads and synchronization. Lets say I have:

public class MyClass(){

    public synchronized void method1(){ 
        //call method2();
   ...

29. Java: Thread safety in class with synchronized methods    stackoverflow.com

I read that the following class is not thread safe since threads could read inconsistent data as there is a chance for a thread to read scaled version of real and ...

30. synchronized methods can execute simultaneously?    stackoverflow.com

I have created 2 objects and 2 threads. Assume m1() and m2() are synchronized methods. t1.m1(); t2.m2(); can both threads can execute simultaneously ? is it possible both synchronized methods can execute simultaneously? ...

31. Regarding significance of synchronization    stackoverflow.com

This might be a dumb question to ask but I am new to multi-threaded programming in Java.I created 4 threads and then invoked the run method on them.In the run method ...

32. Can AtomicInteger replace synchronized?    stackoverflow.com

The javadoc for the java.util.concurrent.atomic package says the following:

A small toolkit of classes that support lock-free thread-safe programming on single variables.
But I don't see any thread-safe (synchronized ...

33. Does the method need to be synchronized?    stackoverflow.com

I need to decide if the following method requires synchronization or not in a multi-threaded environment and why?

public class MultiMain 
{

 public int add(int a,int b)
 {

  int r=a+b;
  ...

34. Cost of synchronization    stackoverflow.com

In a highly concurrent Java program and assuming that my methods are correctly written and correctly synchronized, I am wondering about how to determine which is better:

void synchronized something() {
  ...

35. JLayer Synchronization    stackoverflow.com

(I'm attempting to make my previous question more generic in the hopes of a solution.) I am using the JLayer library and a sample.mp3 file. I would like to play AND ...

36. Throw exception vs synchronized    stackoverflow.com

I have a method that many threads access in parallel which uses a class with two synchronized methods that I have no control over. getObject and createNewObject. I want to be ...

37. External call to synchronized function held/locked    stackoverflow.com

The Following class DoStuff starts a thread and syncs to protect the listener object from being accessed when null. Now when accessing the DoStuff class function setOnProgressListener() externally I'm having ...

38. What does synchronized means in Java    stackoverflow.com

Regarding the difference beween hashMap and hashTable in Java, I read this. Can anyone help me what does "Synchronized" below means? “The key difference between the two is that access to the Hashtable ...

39. Correct way to use Java Synchronized?    stackoverflow.com

I am building a stock system which will be used over an office lan with multiple users. I have a query about using the synchronized keyword to update the stock correctly. ...

40. Why can't Java constructors be synchronized?    stackoverflow.com

According to the Java Language Specification, constructors cannot be marked synchronized because other threads cannot see the object being created until the thread creating it has finished it. ...

41. How does join() work? (Multithreading in Java)    stackoverflow.com

I'm preparing for an exam and after going over some sample exercises (which have the correct answers included), I simply cannot make any sense out of them.

The question

(Multiple Choice): What ...

42. Synchronized Implementation of a Business Logic    stackoverflow.com

Implement using existing Synchronized Java classes (Hashtable, StringBuffer, Vector) or synchronize the blocks when we implement Unsynchronized Java classes (HashMap, StringBuilder, ArrayList) or create a synchronized collection objects from Collections.synchronizedXXX() method and then use ...

43. Using guava's MapConstraint on a somehow synchronized Map    stackoverflow.com

Using Guava, I would like to have a map that has the following properties:

  • A lot of reads, but very few writes.
  • the data doesn't expire.
  • must be synchronized, so a write is "atomic" ...

44. How to safely flush a buffer from a different thread, without synchronized methods?    stackoverflow.com

There are multiple threads, say B, C and D, each writing small packets of data to a buffer at a high frequency. They own their buffer and nobody else ever writes ...

45. Can this "synchronized" work?    stackoverflow.com


1. Is the way to use synchronized here correct?
2. Do the randomScore is locked when one thread access to it so that other threads can not access to randomScore?
3. If ...

46. Is there a drop-in replacement for Java Stack that is not synchronized?    stackoverflow.com

I have a large codebase (written by me) that uses the Stack data structure. This was used for convenience and I am using it as Stack sometimes or Vector/List some other ...

47. Is `synchronized` on a method a syntax sugar or not?    stackoverflow.com

Possible Duplicate:
synchronized block vs synchronized method?
I.e., are the following two entirely equivalent? a)
public synchronized void method1() {
    // ...
}
b)
public void method1() {
 ...

48. How can I create synchronized methods across different classes and files?    stackoverflow.com

I have multiple files and classes. To put it simply, one will run calculations one the location of a particle while another class moves the particle. The problem I'm having is ...

49. java method synchronization object    stackoverflow.com

I just wanted to be sure that I understood the following right.

  1. The synchronized keyword on methods forbids two such methods to be run simultaneously on one instance of the class.
  2. The synchronization ...

50. synchronized(this) and observers notifications    stackoverflow.com

This is related, but definitely not identical, to this famous SO question: Avoid synchronized(this) in Java? Very often I've got an "observable subject" that likes to notify its observers when it is ...

51. Why is TimeZone.getTimeZone(id) synchronized, and why this isn't documented?    stackoverflow.com

java.util.TimeZone.getTimeZone(id) is a method to obtain a timezone based on an id. While I was using the class I opened it with a decompiler and noticed that it is ...

52. Synchronized method keeps getting called    stackoverflow.com

I'm still somewhat new to multithreading so maybe this is an easy answer, but I tried searching around with locks and synchronized methods but this isn't working out right. I have a ...

53. Java synchronized references    stackoverflow.com

I have a class A and B.

public class A() { 
    private static List<int> list = new ArrayList<int>(); 
    public static List<int> getList() {
  ...

54. Synchronized Adventure    stackoverflow.com

If i come across a situation where i will have to make each and every method in my Java program synchronized, will that affect the performance of my code?

55. ReentrantReadWriteLock - many readers at a time, one writer at a time?    stackoverflow.com

I'm somewhat new to multithreaded environments and I'm trying to come up with the best solution for the following situation: I read data from a database once daily in the morning, and ...

56. java - general synchronizedList question    stackoverflow.com

I have a general question regarding synchronized List.
Lets say that in the constructor I am createing a list

List synchronizedList = Collections.synchronizedList(list);
and I have one method adds an object to ...

57. Question about Java synchronized    stackoverflow.com

The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave". What I need to know is whether synchronized will ...

58. When to use synchronized    stackoverflow.com

I'm wondering what is the reason behind synchronizing the below code. I don't think deadlock could occur ?

private final Object lock = new Object();
private Hashtable content = new Hashtable();

   ...

59. Memory leak in weakValue map reference for synchronized method    stackoverflow.com

I am creating an interface for executing methods concurrently, while abstracting away the synchronization details (To swap for a distributed implementation when needed). I've created a single jvm implementation that allows ...

60. Distributed synchronized execution    stackoverflow.com

I'm trying to accomplish something that in terms of concept is very simple to understand. I want to synchronize a block of java code between different machines. There are two instances ...

61. Java synchronized methods question    stackoverflow.com

I have class with 2 synchronized methods:

class Service {

 public synchronized void calc1();

 public synchronized void calc2();

}
Both takes considerable time to execute. The question is would execution of these methods blocks ...

62. The need for the synchronized function when doing write operation to DBMS    stackoverflow.com

In the common DBMS, the read/write operation has been implemented the Lock-system implicitly so that programmer does not necessarily handle this complex locking mechanism. But why when we write code ...

63. How to obtain a customized synchronizedList in java?    stackoverflow.com

I have one customized list MyList that extends ArrayList, like this:

class MyList extends ArrayList<SomeParticularItem>{
   [some methods...]
}
Since I have concurrent reads and writes to the list, I want to synchronize ...

64. reentrantreadwritelock vs synchronized    stackoverflow.com

When should we use reentrantreadwritelock as compared to Synchronized keyword in multithreaded environment in Java? What are the benefits of using reentrantreadwritelock over Synchronized in Java? Can any one give an example ...

65. Synchronization of non-final field    stackoverflow.com

A warning is showing every time I synchronize on a non-final class field. Here is the code:

public class X  
{  
   private Object o;  ...

66. Calling a method from within a synchronized method    stackoverflow.com

I'm facing a strange problem which has made me wonder what exactly happens in a synchronized method. Let's say there is a method

synchronized public void example(){
     //...code
 ...

67. why wait/notify/notifyAll methods are not synchronized in java ?    stackoverflow.com

in Java whenever we need to call wait/notify/notifyAll, we need to have access to object monitor (either through synchronized method or through synchronized block). So my question is why java ...

68. Synchronized Methods in Java    stackoverflow.com

Just wanted to check to make sure that I understand this. A synchronized method doesn't create a thread, right? It only makes sure that no other thread is invoking ...

69. Java Synchronization problem -- Chatting multiple chatroom applications    stackoverflow.com

I am developing a chat application. I have a function which processes chat messages. Each chatroom is identified by unique shortcode. Now I want that when message for one shortcode is ...

70. Should you synchronize the run method? Why or why not?    stackoverflow.com

I have always thought that synchronizing the run method in a java class which implements Runnable is redundant. I am trying to figure out why people do this:

public class ThreadedClass implements ...

71. Synchronized code performs faster than unsynchronized one    stackoverflow.com

I came out with this stunning result which i absolutely do not know the reason for: I have two methods which are shortened to:

private static final ConcurrentHashMap<Double,Boolean> mapBoolean = 
   ...

72. Multithread using synchronized method    stackoverflow.com

I want to create two threads in whic one thread makes increment and another thread makes decrement.Synchronized block should used in this. Output put format should look like this 5 classA makes increment ...

73. get and initialValues method of ThreadLocal synchronized    stackoverflow.com

I came across a code where the get() and initialValue() methods of ThreadLocal is synchronized. I couldn't find any use of having these methods synchronized. Correct me if I am ...

74. Synchronized FIFO Buffer Usage    stackoverflow.com

I am trying to create a system where one thread A adds items to a buffer, then another thread B is responsible for reading the items in the exact order they ...

75. What data structure should I use for a simple synchronized LIFO?    stackoverflow.com

What data structure should I use for a simple synchronized LIFO? I'm using Android Java 1.6. The problem with Java collections is that there are millions of slightly different classes and ...

76. seeking suggestions/critique for async rebuilding of a resource    stackoverflow.com

Here is the proposed solution (I did search for the same - unsuccessfully)

    public abstract class AsyncCache<T> {

        /**
   ...

77. How to test automatically that xsd and generated classes are synchronized?    stackoverflow.com

I have an xml schema file and have generated classes out of that. During development the xsd can change. How can I make sure that the xsd and the generated classes ...

78. What does "synchronized" mean in Java?    stackoverflow.com

I have been trying to learn design patterns. This site uses the synchronized keyword, but I don't understand what it does. I searched on the net and found that it ...

79. Threading and synchronized methods    stackoverflow.com

I have the following code:

public class MyThread extends Thread {
    private int i;
    public static int sum=0;
    public MyThread(int k){
   ...

80. Synchronized calling non-synchronized    coderanch.com

hi marcela, a lock is obtained for the SYNCHRONIZED methods only(lock is never never related to the non sync. methods). so when a thread which is exceuting a synch. method calls an async. method in between it still holds the lock on the object.which means that no other thread can execute any other SYNCHRONIZED method on that object. but this restriction ...

81. yield() on synchronized code    coderanch.com

I have broken up your questions into 1 yield() method does it give up the lock. yield does give up the lock 2. what happens if the current thread performs synchronized code: it will be forces to give the processor to other thread immediately (and what about lock?) The program below creates 3 threads in total. the first is the demo ...

82. synchronized classes?    coderanch.com

Can classes be synchronized? I am getting some conflicting information on this from other forums and mock exams. Can anyone please clarify this for me? Also, if interrupt() is used to stop a thread, what method is used to start it again? Do you tell it to run(), or will this restart the thread from the beginning? Thanks for the help!!! ...

84. synchronized again    coderanch.com

Suneel, The exact bytecodes may differ, but how many of us are actually concerned with the code at that level? The same behavior can be accomplished with different bytecode arrangements. Anyway, look at JLS2 8.4.3.6 and 14.18. Sun guarantees that both of the code samples Bob presented will have the same effect. Regarding performance, there is a small penalty associated with ...

85. Question of synchronized(aObject)    coderanch.com

Nothing really. The only difference is the first code example offers more granularity when it comes to threading and scheduling. Since the JVM doesn't have to lock the entire method then another thread could access parts of that method (a case in mind is if you have a if..then condition, the true part could be synchronized as it updates a bit ...

86. 2 Synchronized methods    coderanch.com

David, Just to clarify, your response is correct in the case of two synchronized methods but not necessarily in the cases of one sync'ed method and one sync'ed statement, or two sync'ed statements. If the two critical sections are sync'ed on different monitor objects, then they are not mutually exclusive.

 class A { public synchronized void A() { ... } public ...

87. synchronized method.    coderanch.com

If a synchronized method throws an exception in it's execution, the lock accquired by it is released automatically ? Is this true or false; I think it's false. Am i wrong ? I think that the object will not release the lock if the error occured or does it ?Please explain your answer.

88. Synchronized method/blocks.....???????    coderanch.com

Synchronization makes sure that we donot write in a common memory space by more than one thread. Sync. methods are used when you think that the entire method should be locked from access to the other thread. Sync. blocks are used when you know that the rest of the method is Ok to be left un-sync'ed, but only a portion of ...

89. Synchronized class    coderanch.com

90. What is the real deal with the use of synchronized    coderanch.com

A lot of authors warn against the perils of synchronizing everything in your classes. Recently I read one of the slides at JavaOne 2000 where it was said that synchronization is not that expensive especially in places where it is needed. There are several clever alternatives to synchronization out there but the JavaOne slide claimed that it is better to go ...

91. question about synchronized code    coderanch.com

Dear all: Do I have to put wait() and notify() in the synchronized code. I have a method like public static synchronized void increment() { // I didn't put wait() and notify() here. } this method was still able to call by multiple thread. The goal I want to achieve here is every time only allow only one thread to access ...

92. Iterating over Synchronized Map    coderanch.com

If the method that contains the iteration code over a synchronized HashMap (i.e. one optained from Collection.synchonizedMap(new HashMap()) is synchronized must I still synchronize on the underlying Map. Or must synchronization on the underlying Map only take place if two threads are iterating at the same time not if one thread is iterating and one or more other threads are reading ...

93. synchronized linked list    coderanch.com

94. Synchronized ?    coderanch.com

I am trying to understand synchronization and just tried to code a simple program . But the output is not what I expected. Cud some body explain? public class sub extends Thread{ public static void main(String[] args) { sub sub1=new sub(); sub1.setName("Sub1"); sub1.start(); sub sub2=new sub(); sub2.setName("Sub2"); sub2.start(); } synchronized public void run() { String str=getName(); for(int i=0;i<10;i++) System.out.println(str); } } ...

95. Big Question in Synchronized    coderanch.com

Only one method of a class is ever operating at a given time - at least I can't think of an example where this isn't the case (excepting threads and multiple objects of a class). If you are talking about methods from two different objects of the same class, then you may wish to implement threads to get the job done. ...

96. Calling synchronized method()    coderanch.com

Sure, its possible. If you call another synchornized method in the same class (object) then it has the lock and it continues with the new method. If you call a synchronized method in another object, then it needs to aquire THAT lock as well... until it doesnt i guess it is STUCK in the first synchronized method (which can cause a ...

97. Thread with synchronized run() method and sleep()    coderanch.com

The following SyncRun source code demonstrates what happens when you synchronize the run() method. If you run this program, you will notice that either thread A or thread B runs to completion before the other thread. That is due to the running thread holding the lock until it exits run(). As a result, the other thread delays its execution of that ...

98. synchronized    coderanch.com

99. synchronized(obj)    coderanch.com

Synchronization comes in two flavors. You can synchronize an entire method or you can synchronize access to a shared object for a block scope. synchronized(obj) means the access to obj is exclusive to the thread that executes the following block and all other threads must wait till the current thread completes executing the block. sychronized(this) means the same, but the shared ...

100. Thread with synchronized run() method and sleep()    coderanch.com

This code starts two parallel threads which print out: hread-1i=576 Thread-1i=577 Thread-1i=578 Thread-1i=579 Thread-2i=0 Thread-2i=1 Thread-2i=2 Thread-2i=3 ... until every thread has reached 1000. public class BussyThread extends Thread{ public synchronized void run(){ for(int i=0;i<10000; i++){ System.out.println(Thread.currentThread().getName()+"i="+i); }//end of for loop }//end of run() public static void main(String args[]){ BussyThread b1=new BussyThread(); BussyThread b2=new BussyThread(); b1.start(); b2.start(); } } First question: ...

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.