I have a method that access some DATABASE and write the result to a file. Like this... public class yyy{ public void x(){ #1... // execute a query on database... #2... // Write to file the result... } } yyy class will be INSTANTIATE by the servlet. The point is IF some request execute the first line (#1), it MUST execute ... |
if thread1 calls obj1, can thread2 call obj2? The answer to this question depends on which object(s) is/are used to call methods obj1() and obj2() from threads thread1 and thread2. If it is the same object, then the methods will be run in sequence. If it is two different objects (two instances of a class that has synchronized methods), one of ... |
i read in core java book that each object that has synchronized methods has counter that is set to the number of synchronized methods in the object .when a thread has the lock of the object(after it called a synchronized method) then this counter will be decreased by one for each synchrized method termination after calling it by this thread and ... |
I agree with Huang's point, then I try some experiments with the code, I found something quite confusing here. In the following code, SyncTest still extends Thread, however, in main() I use Huang's style to generate two threads. the code compiles & generates expected result. AAAAA BBBBB What I don't get, why those two lines compiles ? Thread does not have ... |
public class MyClass { public synchronized void methodA() { //do something } public synchronized void methodB() { //do something } public void methodC() { //do something } } Threads T1 and T2 have the same instance of MyClass, lets say oMyClass. T1 calls methodA. While methodA is executing in T1, T2 calls methodB. What happens?? - T2 has to wait for ... |
I am very new at Threads so I was hoping to get some information here. I was wondering when I synchronize a method, and then lets say I create multiple threads (just 2), that each has objects that call this synchronized method. That means that method is only called, by one of those objects at any given moment right? So, in ... |
A constructor can only be called by one thread at a time. You could never have two "new MyObject()" calls interferring. If you need them to be synchronized accross the class, that is possible, but I'd advise you to rethink your design as this is a very unusual question. Perhaps you could provide a business problem that we could help you ... |
|
Hi u r right the lock is obtained on instance of the class /Object.. u can execute a sync method & non sync method same time using multiple threads. but if a class has two sync methods only one can be run at a time. if u r using a complex method in which a small part is to be synchrinized ... |
hi guys, a question about synchronized if i put the modifier synchronized on a non-static method, and some instance is created for the class that contain that method. if that method was called on EACH instance, will the synchronized modifier still take effect? or does the synchronized only work if we're calling that method on the same instance? I'm not sure ... |
Hello all, First, off thanks all involved for providing an excellent Java resource and thanks seores Sierra and Bates for an excellent book on SCJP. On to the question. I've been studying for the SCJP using the KS&BB book and have a question regarding an example on page 533 (the calculator/reader example that demonstrates notifyAll()) in the Threads chapter. My understanding ... |
Look at the following question i picked up in the internet. public class Vertical { private int alt; public synchronized void up() { ++alt; } public void down() { --alt; } public synchronized void jump() { int a = alt; up(); down(); assert(a == alt); } } if the code is run with assertions enabled ,what are the possible answers? a.The ... |
Hi. Please consider this piece of code: public class JndiUtilities{ /** Internal configuration object storing information about initial context, datasources, etc*/ private static final Configuration configuration = ConfigurationProvider.getConfiguration(); /** Internal map where to store objects obtained via jndi for reusing instances*/ private static final Map map = new HashMap(); // HERE WE STORE WITH SPECIAL KEYS JNDI RESOURCES TO BE CACHED; ... |
|
I'm afraid there's no quick-and-easy fundamental rule for what you should be synchronizing your blocks of code on. It really depends on what the block of code is actually doing. If all you need is a simple mutex, then you can synchronize on any dedicated object. If you need something to enforce exclusive access to a resource, then you can synchronize ... |
I have the below 2 methods in my DBConnection class which establishes my database connection from a connection pool. If I am using servlets, and inside my service() method, I declare and initialize a class A, which in turn calls the DBConnection class to establish database connection, then where in my below code do I need to synchronize the methods. I ... |
Hi, I came across this in 'The Java Programming Language, 3ed' by Arnold,Gosling,Holmes (Section 10.4, page 244). ================================================ There is a standard pattern that is important to use with wait and notification. The thread waiting for a condition should always do something like this: Synchronized void doWhenCondition () { while (!condition) wait (); .. Do what must be done when the ... |
Hi all, Say, I have N threads competing access and modify an object. All I have to do is qualify all the methods of that object with 'Synchronized' keyword. This would automatically force 'synchronous' access to that object. None of the accessing threads need to wait/notify. Am I correct? Thanks in advance. Bala. |
Hello all, I have a thread and shared resource synchronization problem. Here's the skinny on what I want my program to do. I have a class that extends Thread, call it class X. The class X object takes a String array and an integer representing the position in the array to update as the input parameters of its constructor. (This String ... |
Welcome to JavaRanch! I suppose you're meaning to ask about why some things should be synchronized. Take a look at the Synchronizing Threads section of Sun's Java Tutorial for an introduction to synchronization in Java. From that page: [T]here are many interesting situations where separate, concurrently running threads do share data and must consider the state and activities of other threads. ... |
class threadtest {static void print(String message) {System.out.println(">>>>>> "+message);} public static void main(String[] args) {new SimpleThread("A").start(); new SimpleThread("B").start(); } } // ************************************************** class SimpleThread extends Thread {public SimpleThread(String str) {super(str); } public void run() {callme1(); callme2(); } void callme1() {threadtest.print("111"); synchronized(this) {threadtest.print("in Callme1 "+getName()); try { sleep(5000); } catch (InterruptedException e) {} threadtest.print(getName()+" getting out of Callme1"); } } synchronized void callme2() ... |
|
Interfaces cannot require or disallow use of the synchronized modifier in implementing methods. There are many ways to manage synchronization, and that should be (must be) an implementation detail. The only place synchronization belongs in an interface is when your Javadocs describe the thread safety properties of a class or method, which is obviously not machine enforcable*. * (Footnote) Not enforcable ... |
Howdy Java partners! I gotta a question and I hope you can help me. Here is some PSEUDO-CODE that I cant really tell if it is really synchronized protected. public void changeValues() { changeX(); changeY(); viewXY(); } private void synchronize changeX() { x++; } private void synchronize changeY() { y++; } private void synchronize viewXY() { System.out.println(x + " " + ... |
Doug Lea "wrote the book" on threads in Java. The Sun tutorial on threads is also pretty good. Dig into those for a start, be sure to ask here again if you find specific questions. It's a tricky area - expect to be a bit confused for a while. Lea's Concurrent Package This stuff is a bit advanced and rather under-documented ... |
Hi, I'm having this issue and not really sure what to do. There is this HashMap contianing about 3000 to 120000 elements. Each element is mapped to an object which is never null and contains mostly longs, shorts, and ints inside. I will have one thread updating those objects continuesly and there will be dozens others reading values from those objects. ... |
I am creating an application which uses a database as a persistent queue. I have one process writing to the queue (which happens to originate from a servlet), and one process reading from the queue. This seems to be the classic producer-consumer problem, except that I cannot use notify/wait because I am using different processes in different JVMs (at least that ... |
Hi all, I have some questions in my mind. 1. Whats the difference between the synchronized keyword when applied to a method and a block of code. 2. When synchronization is done, a lock is obtained to a particular object only. In that case the same synchronised method can be accessed by multiple threads with different instances of that class. Suppose ... |
Hi All Any one can pls tell me 1, How one thread will communicate with another thread ? 2, How to write a thread safe application? 3, What is the use of synchronized Block? I am developing a application i want to make it thread safe. I am doing my buisness logic in Servlets. This is sample code. try{ synchronized(this){ pstmt=con.prepareStatement(" ... |
I have a boolean method that calls another method and needs to wait until it is finished. I put a sleep into the first method code but when it sleeps everything sleeps .. so the entire program hangs. How can I fix this ? Is this a thread problem ? Here is simulation and the calling / wait code: boolean mthod ... |
Hello, Upon init of my servlet, I initialize a static class that caches some data from a database - the data is a set of objects stored in a HashMap. The data does not change very frequently so I am going to update it once a day. So here is my question...given that most of the time (23 hours a day) ... |
My function is checking on work attendance with IC Card : 1. Read Serial, get IC cardno 2. check cardno, query cardno from database 3. if cardno is valid, send "S98" to serial, otherwise send "S97" 4. Save cardno and current time to database My program is often running corret, but sometimes do absurdness things. For example, my ic cardno is ... |
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ... |
watch this. please dont take it as it is. just take it as a scenerio. i have some handler classes which is instantiated inside init() of servlet. in the constructor of every handler class i m constructing my DB classes say DAOs. 1. now if i get the connection object, from DriverManager.getConnection(), in the constructor of my each DAO. and all ... |
Hi I have an application with two threads running.One (SocketListener)is listennig to socket and getting packets and writing them to a hashtable.The other one (PacketHandler) is checking if a new packet has been written to the hashtable and if so, getting the packet and analysing the packet. In PacketHandler thread I have a static counter, which starts from zero and increment ... |
The following example consists of 2 threads that both increment a static int by 1 and decrement it by 1. Both threads are stopped abruptly after half a second. What i don't understand is why there are other results possible than 0, 1 or 2. Synchronizing one a shared object helps but this shouldn't be necessairy. What is going one here? ... |
Hi, I have a text file used for tracing purposes. I have to do a validation before each line is written to the file...like it has to compare the date the file is created and current file.Whenever the file is created , a time stamp is written as the first line. If the file is 2 days old It has to ... |
Hi Ranchers, I have a loop where in I create 2 threads per iteration; I synchronize these 2 threads using shared variable and synchronization method; { There's a minor glitch though that I cannot possibly determine before hand how many threads are created } Now after these threads are executed I need to refresh a screen.... I tried couple of ways ... |
Ranchers, I always thought when it comes to Threads: implementing Runnable is flexible and advantageous over Extending Thread. However I'm encountering a peculiar problem. Could you please suggest alternatives, get-arounds or solutions: Here's the scenario: I have a Dialog where in user asks for some Tasks(each implemented by a sepearte Thread) Now here's what i do: 1> Close the dialog (SwingUtilities.invokeLater ... |
Hello Java-Gurus! I have some questions about the synchronization. I have one class, say Database. This class makes some I/O action with the file (RandomAccessFile). I synchronize every method, that works with the RandomAccessFile instance. public class Database { RandomAccessFile file; public synchronize String read(int pos) { file.seek(pos); file.read(..) } public synchronize void write(String str, int pos) { file.seek(pos); file.write(..) } ... |
Hi, welcome to the ranch! Synchronization is used in multi-threaded programs to make sure that only one thread gets into a sensitive code block at a time. If I have code that might be run by two threads and it does something as simple as: private void method(int a) { memberVariable = a; if (memberVariable == a) System.out.println("YES!"); } it is ... |
Friends, I was given the following class (IncrementImpl) already written. Now we have so many threads which access this concurrently. How can I make it synchronize it. Please help me. Thanks, Senthil. ------------------- public class IncrementImpl { private static int counter = 0; public synchronized void increment() { counter++; } public int getCounter() { return counter; } } |
1. can i put this code inside a method to synchronize a particular block Yes. 2. does synchoronize(this) block works only on instance variables. When you use synchronization, you synchronize on an object. With "synchronize (this)", you synchronize on the current object (what "this" points to). When you do that, you lock the current object for concurrent access by other threads. ... |
As I was trying to understand better the behaviour of JVM, a issue came up. I defined a Calculator thread which calculates a sum and makes the result available through the getTotal() method. The Reader thread keeps a reference to the Calculator and prints the result. As I wanted the result to the be printed only after the calculation, Reader calls ... |
How to choose between writing a synchronized method or a synchronized block? A synchronized method syncs on the object instance that is running the method. This may not be the right level of granularity for some problems. It may block other threads for longer than really necessary. Static methods have no "this" and lock on the class which is even larger ... |
If in a class two synchronized method are defined.Two threads are created of the class. If thread1 has acquired a lock on method1 and at the same time thread2 is trying to access the method2 then will it be able to acquire lock on the method2 or thread2 has to wait until thread1 releases the lock on method1. |
|
Hi, I have a class called A{} in which I have three methods.Inside one method I have given synchronized(A.class){ and some code here }.There are also other methods outside this class.I want to know whether the other two methods are also synchronized.I want to know this because I have given synchronized inside a method and if I call a method before ... |
Hi Sir... This is Naseem here. I have one confusion in synchronization concept. I read that in synchronization if one thread is accessing ny synchronized method, no other thread can access that method at that time. I am getting that same from my code. In main method I created 100 different threads. Now in threads's run() method i hav a synchronized ... |
|
Hi, Raghuram, welcome to the ranch! That tutorial is definitely the place to go. Since you asked about synchronization (just one part of threading) I'll venture a very short explanation. Often when two threads share a resource it is necessary to make sure only one thread accesses it at a time. A resource can be any object or something outside the ... |
Hi Thank you for reading my post. In a section of mmy application i have some threads which i start by a button. I have a List object in my main class , in this list i store some objects that my thread need to process , i should show users that which object is under process in my GUI and ... |
Just a quick (or maybe not so quick question). On a recent bout of refactoring I came across a bunch of static initializers that would initialize some data and throw exceptions. This was refactored to use lazy loading and data was now initialized in the constructor. My question is what is the best way to synchronize the whole process of inisitalizing ... |
Originally posted by Meenu Mehta: Hi, I am new to using threads. I have read in many articles that synchronization makes the programs slow and un-neccessary synchronization should be avoided. Can you please tell me why synchronized methods take longer time and what can be the harm of using it more. Thanks, Meenu Well... it is not that clearly black and ... |
Hi, I have some question regarding the synchronization i.e. A couple as join account in the some xyz bank and many cases like both accesses the account at the same time. Bank application is executed in two or more JVMS and as I know for each JVM single object created for servlet. My question is if suppose two thread i.e. one ... |
Not sure if I understand you correctly, what do you mean you want to synchronize "TO DO BOTH THE WRITING AND THE READING OPERATION SIMULTANEUSLY"? Do you mean that you are doing both simultaneously and need synchronization to protect it? or do you mean that you want to allow one thread to write and one thread to read simultaneously? Regardless, synchronization ... |
I have a question about the following code: public class MessageHash { protected Hashtable hash = new Hashtable(); protected void put(Object message) { String messageId = getMessageId(message); LogMessage msg = new LogMessage(); synchronized (hash) { hash.put(messageId, msg); } } protected LogMessage get(Object message) { String messageId = getMessageId(message); return (LogMessage)hash.get(messageId); } protected void reportAndClear () { synchronized (hash) { Iterator iter ... |
Is there any difference between these 2 pieces of code? class A { private Object lock = new Object(); public void aMethod() { synchronized (lock) { // some code here } } }; and this one: class A { public void aMethod() { synchronized(this) { // some code here } } Thank you. |
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ... |
Hi all, I'm using Java reflection to instantiate a class but am running into a rather strange problem. In particular, even though the block of code that instantiates the object is synchronized, it appears that I sometimes get back the same exact object instead of a new object. For example, here's the code block that creates a new object: public IHardwareDriver ... |
Hi all, Following is what I'm trying to do. 1) I hava a baseclass CLass A which has a instance String variable. Abstract class A { protected String var = "base"; abstract protected void modify(string input); } 2) I have a subclass Class B which extends Class A class B extends Class A { modify(String input){ if (input.equlasIgnorecase("A") var = "subclass"; ... |
public class CheckSync { private int i=0; public synchronized void method1() { i++; } public void method2() { i--; } } We have two methods here one is synchronized and the other is not. When an object of this class is locked, only one thread can access method1() but any number of threads can access method2(). while method1() runs, method2() also ... |
Hi guys, I have a quiz question I hope you guys can understand public class OrderedThread { public static void main(String[] args) { MBThread first,second,third; OrderedThread orderedThread = new OrderedThread(); first = new MBThread("One",orderedThread); second = new MBThread("Two",orderedThread); third = new MBThread("Three",orderedThread); second.start(); first.start(); third.start(); } public void display(String msg) { synchronized (msg) { for(int i = 1;i<=20;i++) { System.out.println("Name = ... |
|
1 public class ThreadA { 2 3 public static void main(String[] args) { 4 5 ThreadB b = new ThreadB(); 6 b.start(); 7 8 synchronized(b) { 9 try { 10 System.out.println("Waiting for b to complete..."); 11 b.wait(); 12 } 13 catch (InterruptedException e) { 14 System.out.println(); 15 } 16 17 System.out.println("Total is " + b.getTotal()); 18 } 19 } 20 } ... |
Well, you could define an object that acts as a monitor for I/O to that file. Your reading and writing operations would need to get that monitor's lock before commencing. That would, however, mean that your application could spend a long time blocked, waiting to get that lock. If that is unacceptable, consider having a status variable, with thread-safe access, and ... |
Hi all, I need some suggesstions on a problem. I am using two programs operating on same file. The two programs are seperate.My need is , when one program is reading from the file, another must not write in it(simultaneous access). I can't use the synchronized blocks here because the two are seperate programs and doesnot share any objects.Can anybody suggest ... |
After reading the java tutorial : "Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods." Since all objects have the potential to be visible to more than one thread hould I synchronize all ... |
In real simple terms it locks the method and creates a single key to open it, When a call is made to that method, if the key is not being used it is passed to the caller and it can call the method, otherwise it can't until current keyholder puts it back. Yes, that is simplistic, but hopefully it can help ... |
Well, I think it's probably silly, but it's hard to say for sure without knowing what other code may be doing in the same class. It's true that if other threads have the ability to change the contents of the Hashtable object, then the synchronization shown is insufficient. You'd want to sync around the entire iteration process. You'd also typically sync ... |
|
Hey all, Ive been trying to implement a double GA model (GA within a GA) using threads and I still can't figure out how to do the synchronization properly! At the moment, my code is: The top GA runs and after initiliazation of the population and at the point of setting fitnesses, the second GA is called .I tried pausing the ... |
Its hard to know where to start, most of the points have been commented on elsewhere in this forum. Quick answer : As the add (B) isn't synchronized and the size (A) is then the synchronized does make no sense. Minor Point : ArrayList isn't thread safe ( see Collections.synchronizedList ) so calling any of its methods from outside a sync'ed ... |
|
Hi All, Please look at the following code: class CalculatorThread implements Runnable { public void run() { try { String threadName = Thread.currentThread().getName(); if ( threadName.equals("adderThread") ) { printMessage("Adder"); } else if( threadName.equals("subtractorThread") ) { printMessage("Subtractor"); } }catch(Exception e) { e.printStackTrace(); } } public void printMessage(String component) { System.out.println(component+" in Action"); } } public class ThreadDemonstrator { public ThreadDemonstrator() { Thread ... |
|
I have a singleton class. - In another class say A i get that singleton instance. - Call a set method - then start a thread which works on this singleton instance. Now my problem is when one such thread is started and works on that instance another thread is also started. this leads to sync problm. This can be fixed ... |
hi Everyone I am new to threads and having a problem understanding the concept of Synchronization. I am providing the code below: Given: public class Letters extends Thread { private String name; public Letters(String name) { this.name = name; } public void write () { System.out.print(name); System.out.print(name); } public static void main(String[] args) { new Letters("X").start(); new Letters("Y").start(); } } We ... |
You can do it.You can syncronize methods of a class (with multiple instances / Object) by capturing the lock of Class rather than lock of object. You can capture the lock of a class by using a static syncronized method. As the method is static is static , the JVM would try to grab the lock of the class ,so if ... |
We guys are developing a P2P file sharing software(on LAN) and our program requires that we implement a multi-threaded client. I somewhere read on the forum about a multi threaded server but it doesnt work in my case (not on the client side.)The program runs properly when a single transfer is happening but if more then one file is getting downloaded ... |
I ran across the following code which got me to thinking: Is there any good reason to synchronize a run method for a class that implements Runnable? Because this method implements a while(true) statement in the method body, a second invocation of the run method will never be executed. Perhaps that was the original developer's intention? /* (non-Javadoc) * @see java.lang.Runnable#run() ... |
Hi I'm writing a domain object that will be used in a multi-threaded environment. It's properties are bound. Is it a common idiom to just make the getters and setters synchronized? Is this safe/a good idea? Would it be better to have a lock per property? Here's some code : import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import org.joda.time.DateTime; public class Market { public ... |
I've never come up against this before, but for all things there is a first time. I'm trying to code up a Java version of the olde game of Asteroids. I have an ArrayList called gameobjects which holds all the objects in the game, asteroids, bullets, the players ship, etc. Objects have a public boolean called 'nuke' which if set to ... |
hi Can anyone explain me the output of the following code Consider the following method: public void getLocks(Object a, Object b) { synchronized(a) { synchronized(b) { //do something } } } and the following instantiations: Object obj1 = new Object(); Object obj2 = new Object(); obj1 and obj2 are accessible to two different threads and the threads are about to call ... |
Originally posted by santhosh kumarM: I want the one example of synchronization on a block. Okay: package demo;// import java.lang.Thread; //Java 2 Platform Standard Edition 5.0. public class kumarM { String stringOne = "santhosh"; String stringTwo = "kumarM"; private Concatonator catatonic;// just humor, folks. public kumarM() { this.catatonic = new Concatonator(stringOne,stringTwo); } public static void main(String [] args) { try { ... |
Hello, I have to make a presentation on Threads and Synchronization in a few days time.I have gone through the topic once and have just understood it , but still i am unable to envisage some real practical examples based on it. Could someone please help me with some good articles from where i can have an abstract which is comprehensive. ... |
|
For a number of threads to synchronize a block of code correctly they need to synchronize on the same object instance. That sample code would allow someone to change "o" to a new object instance between the time Thread 1 synchronizes and the time Thread 2 synchronizes. Then both threads could enter the synchronized block at the "same time". We could ... |
|
hi m new to these concepts, bascially my question is that i have to develop a server which listens to client requets, so each client gets its own thread .. currently application funcationality is limited to accessing the same method( bascially clients try to access an RFID antenna to view the current tags it could read) the reader while processing should ... |
There are five libraries in our system. viz 01) communikator 02) FM 03) NM 04) UM 05) booter 06) application Each of these libraries has a defined API - a Facade. Libraries communicate with each-other thru their facade only. FM is dependent on communikator.i.e.FM calls methods in communikator facade only. NM is dependent on FM and communikator.i.e. calls methods in communikator ... |
2. Why the wait/notify/notifyAll need to be called from synchronized blocks or statements? Short Answer. Every threading system -- Solaris, POSIX, Windows, etc. -- require it. It is not possible to wait on a condition variable without holding the mutex assigned to the variable. So Java does it because everyone else does it... Long Answer. In general, you don't send a ... |
The "this" keyword refers to the current instance of the class in which it appears. In your case, it is the current instance of class TthrA. You can synchronise on any object. However, choosing the correct object for a particular situation is not trivial. Perhaps you should work through a good on-line tutorial or book (e.g. "Java Threads") on Java threading. ... |
[Jim Dewberry]: But the main reason I'm asking is that I wonder if the contains() method iterates through the ArrayList. If it does, then I need to lock the list while doing the check. Is that right? Yes, contains iterates through the list, and so some synchronization is required here. You might want to replace the ArrayList with a HashSet or ... |
|
|
I have a Hash Map to which one application will insert objects. There is another thread which access this Hash Map, do some processing on the objects and ultimately removes the object from the Hash Map. How can I synchronize the Map insertion and removal with out causing a concurrent modification exception? |
I'm in a really fast pace training program and we are covering a lot of material in a relatively short period of time. I've really not had much trouble up until this problem. I had to do one other problem using concurrency and it worked out well but this problem is stumping me a little. The problem is a non-network black ... |
I am trying to implement some cache in my application. The situation is like this, objects can be added to a cache, the cache can be invalidated on some conditions, and some user may retrieve some object from the cache. I don't want the process to break with all these activities may happen all at the same time. I therefore thought ... |
|