I'm reading Concurrent Programming in Java, and getting confused about the fist example. class Particle { protected int x; protected int y; protected final Random rng = new Random(); public Particle(int initialX, int initialY) { x = initialX; y = initialY; } public [B]synchronized[/B] void move() { x += rng.nextInt(10) - 5; y += rng.nextInt(20) - 10; } public void draw(Graphics ...
Hi seetharaman, in short you need synchronization when using multiple threads in an application. Synchronization is needed to prevent unexpected access to shared data among multiple threads. Without proper synchronization you have good chances for corrupted data and kind of non-deterministic behavior of your program. But multi-threading and correct synchronization is really a complex topic and you should search for tutorials ...
Hi, I am reading the threads chapter for the first time.I tried a sample program on synchronization.Why am I getting different outputs for Example1 and Example 2. Please explain me what actually happens with the two examples.Request a spoon feeding public class AccountBalance { protected int balance =50; public int getBalance() { return balance; } public void withdraw(int amount){ balance =balance-amount; ...
Well it is absolutely legal to synchronize inside a loop or for that matter anywhere in your method. A word of caution though: When you use nested locks be sure that you take these locks in the same order everywhere in your application. Otherwise, it may cause deadlocks. Also, it may be better to put this synchronization logic inside the dispatch ...
All modern processors have an machine op code -- called the CAS operator. On some machines, it means Compare-N-Set, on others it means Compare-N-Swap. Regardless, it is an atomic operation, that is guaranteed to work across the processors cores on the computer. This instruction is used as the basic building block for synchronization. With this op code, it is possible to ...
I have one small sample code for synchronization test. **************************Account.java*************** public class Account { private int balance=50; public int getBalance(){ return balance; } public void withdraw(int amt){ balance=balance-amt; } } *********************AccountJob.java****************** public class AccountJob implements Runnable { private Account account; public static final int MIN_BALANCE=10; public static final int WID_BALANCE=10; public AccountJob(Account account){ this.account=account; } public void run(){ for(int i=0;i<5;i++){ withdraw(); ...
hi,query as follows. I have a one function which is public static void func_name(). Inside the function, there are three steps. for each step i.e step1 thred1 a[i]= new thred1[4]; // a[i]= new thred1(var); step2. thred2 b[]= new thred2[4];//declare inside constructor b[i]= new thred2(var); step3. thread3 c[]=new thread3[4]; c[i]=new thread3(var); This function is static as well as , these are also ...
Afternoon all. Suppose I have a runnable class that has methods A and B, say. Method A is not synchronized in the method declaration but has some portion of code that is synchronized. This synchronized portion of code may be executed or it may not depending on the path taken through method A. Method B is has no synchronization at all. ...
We have a web application deployed in a WebSphere AppServer cluster. We are doing some atomic operations in synchronized blocks. Apparently this will not work since every server instance is a different JVM and they don't share locks. How do we handle this situation? Please let me know your suggestions. Thanks, Sandhya
I have a class where there are bunch of read functions that are accessed frequently and an update function that will be used infrequently but should block all the read functions until it is complete. I'm not sure about the terminology used in java.util.concurrent.lock so Im not sure if there's a solution in there. Here's my requirements: 1. Multiple concurrent reads ...
Can someone please tell me how to do this or where to find information on how to do it? I have a general idea but don't want to waste time going down the wrong path. Here's my problem: I have three separate JVMs running on the same or different machines and they all read/write the same file, which resides on one ...
Is there a free, open source implementation I could use to compare files? Not being satisfied with JFileSync I have begun creating my own program to do file synchronization between a source and target folder. Also because I thought it could be fun to try create such a program. I was thinking of a fully implemented algorithm for file comparison that ...
I have a main method which is synchronized public static synchronized void main(String args[]){ } I am using cron to run the program 4 times all at the same time. e.g. the program is run 4 times a 3o'clock The synchronization doesn't seem to be working however. The program is run as usual. java -arguments Are the serperate java calls run ...
We have very weird issue that I cannot explain. However, I hope that someone can give some tips on it. We have a web site that display documents and information related to those documents. Some users complain that when they open a page the date when documents were submitted is wrong (really old date is shown). And after page is refreshed ...
I have just completed a big project on E-CRM, but in the end stage of our project we realized that there was flaw in our approach, which is turning out to be very dangerous. My JSPs are not threadsafe and global variables are declare in most of the jsps moreover jsps are included with global functions (within <%! %> tag). These ...
Well, using an operating system slows processes, too! You're trading performance for the luxury of not having to code and debug everything from scratch. Using Java REALLY slows processes - the level of personal happiness I got in C++ from a P-150 requires a 600MHz PIII. The point of using an appserver over individual custom apps is to get reliability and ...
Hi all! I have a question. Let's say that I create a DB wrapper class that a servlet can use to access mySQl. Rather than creating a new instance in the doGet method, which I assume means that each thread will create it's own instance, I make it a member variable of the Servlet Class. I initilize it in the init() ...
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 ...
I would think that any shared resource which should not have simultaneous access should be synchronized. In your case, if this servlet can be accessed by n no. of users to create new users at the same time, then you should synchronize database access. I would assume though that there would database row level loking while inserting...
Hey folks. I have created the following listener to track the current number of the users. public class TrackingListener implements HttpSessionListener { status int users = 0; public void sessionCreate(....) { users++; } public void sessionDestroyed(....) { users--; } public int getCurrent( ) { retrun users; } } my question is should I synchronized the access to the users variable ? ...
Thanks. but I have been reading some tutorials that creates such a class for accessing the database and synchronized the methods because the whole web application will use this class. this application creates one instance of this class and puts it in the application scope. in this case, synchronization is and issue right ??
thanks Bear. The reason I am asking is because a colegue of mine at work says that a server that supposed to return a unique number from a database sometimes returns the same number if server is hit twise. He says that making doGet() of the servlet synchronized will solve the problem. I say we need to make a synchronized block ...
Hi William, Thanks for the reply, I'm using the HFSJ and on page number xxv, point number 1 says, "Stop and Think" and to use my Brain(Only 200 grams availabe(lesser than the weight of the book)). I stopped on page 195 where Kim sits and asks to me "What do you think? Will it fix the problem I had??". I'm not ...
Hi guys, I have a database table filled with configuration stuff. Its a key/value table, that maps to a java.util.Map in runtime. The thing is, I cant afford a database hit every time a servlet/EJB needs a configuration value. But I need the latest value of the configuration (if someone updates the table, I need the value updated eventually, that is, ...
We know container invokes the init method once and then each client request is handled by a new thread. Now suppose number of different threads are running then Is it possible that container calls the destroy method when few threads are still running ? Do we need to synchronized the destroy method if we override this method?
heres my code (runs and compiles fine!) import java.util.*; class Counter { private int count; public Counter() { count = 0; } public void increment() { ++count; } public void decrement() { --count; } public int get() { return count; } } class Queue { static Queue store = new Queue(); private LinkedList data = new LinkedList(); public void put(Object o) ...
Hi, I think, 1)SingleThreadModel is used in server side and Synchronization is used in client side. 2)SingleThreadModel is for servlets and Synchronization is for Multithreading. This is the difference i knew. But the thing is both do the same function and i want to know some more differences. If am wrong please correct me.
Hey, I suppose synchronization is used when talking about threads. We use sybnchronization to prevent multiple threads from changing the state of an object, or to make sure that only one thread at a time access an object. We have the wait, notify and sleep etc .., methods in the Java API to help us do so. Object serialization provides a ...
Hi all, Am using the multithreads in the program. In my program am using 3 text files. a.txt,b.txt and c.txt. a.txt should be read by thread A, b.txt should be read by thread B, c.txt is blank file so using thread C, I want to write the containts of a.txt and b.txt. Up to now i tried only simple thread progrms ...
hello, folks. I am trying to synchronize two thread which can both sell tickets. The follwoing is my code: class SellTicket implements Runnable { int index = 100; Object obj = new Object(); boolean b = false; public void run() { if (b == false) { while (true) { Sell(); } } else { synchronized(this) { while (true) { if (--index ...
Greetings I'm working on a project which deals with converting one particullar BPEL process to Java code (it communicates with similar "BPEL services" written in Java - communication is done by Java RMI) and in the process I have 2 parallel sequences which are handled by 2 threads. Now my task is to deal with this: to make the execution of ...
Hi As a part of a program I create a file and then rename it to a folder address where it is supposed to be kept. I use the renameTo method to do this. The method returns true indicating it was moved correctly. I have tried doing File f = new File(movedFile.getAbsolutePath()); and the f.exists returns true. but say the parent ...
Hey guys! I've been a fan of this site for a while and now I'm joined and writing my first post. I'm working on a basic program. It is supposed to have three classes: One main class (with the main method) One class, T1, which extends Thread One class, T2, which implements Runnable. When the main class runs, it is supposed ...
I have a very simple hierarchy laid out here. Base class: ======== class A{ protected ObjectX m_data; public Object getAttribute(String name) { if(m_data!=null){.......} } } Inheriting classes: ============ public class B extends A { protected B(ObjectX dataValues) { m_data = dataValues; } public String getName() { if(m_data==null){RefreshData();} String name=m_data.getAttribute("NAME"); return name; } public boolean RefreshData() { ....; .....; m_data=xxx; } } ...
From what i understand about synchronization,the following 2 ways of synchronizing an instance variable are equivalent: Route 1: void reverseOrder() { synchronized (this) { int halfWay = intArray.length / 2; for (int i = 0; i < halfWay; ++i) { ....... ...... } } } Route 2: synchronized void reverseOrder() { int halfWay = intArray.length / 2; for (int i = ...
Hey guys , I thought of something and am not sure if my understanding is right... ONE: (When no synchroniztion is done ) If my servlet has one method (methodA) to iterate and display form 1 to 10 and another method (methodB) to iterate and display from 50 to 60 is it very much possible that the page might display: 1 ...
/** * Multiple instances of this class will be running at the same time. */ Class Consumer { public void execute() { // Get the list from the cache. List
Hi, I am currently studying for the Java exam and am writing some code to test the Synchronization keyword. Here is the code private void btnThreadActionPerformed(java.awt.event.ActionEvent evt) { // This is going to create two threads which call a synchronised method ThreadClass t1Class = new ThreadClass("t1"); Thread t1 = new Thread (t1Class); System.out.println("About to call t1 " + Calendar.getInstance().getTime().toString()); ThreadClass t2Class ...
I faced this question while going through an interview! If only this question ever comes up on any interview that I ever go to.... Synchronization is for a type of locking called "pessimistic locking". It is based on the theory that if you don't protect the code, the threads will step on each other and corrupt the data. This question is ...
Hi all, Please check the following code: public class MyThread extends Thread{ public MyThread(String name) { super(name); } public void run() { callMe(); } public synchronized void callMe() { while(true) { System.out.println(this.getName()); } } } public class Test { public static void main(String args[]){ MyThread t1 = new MyThread("FirstThread"); t1.start(); MyThread t2 = new MyThread("SecondThread"); t2.start(); } } Despite of the ...
I have created a class that implements runnanble interface Here i have a 1. public void run method(); 2.a synchronized method getChatFriends(); From another class I created a new Thread . I also called this getChatFriends(); But the execution was not sequential as expected . I understands that sychronization works correct when the same object calls two different synchronized methods of ...
Hi, I dont understand why the synchronization is not working properly within this code. Though I have one synchronized method, I am sure that two threads are aceeesing the code simultaneously. The output says so. class Account1 extends Thread { static int bal = 100; Account1(){} Account1(String name){super(name);} public void run() { if(this.getName().equals("Husband")) { System.out.println(this.getName()); deposite(500); } else { System.out.println(this.getName()); deposite(1000); ...
hello , what i exactly want to say is, if i have an application which have one field which is autoincremented, like as n when user add the record, the number will get incremented automatically.. now my problem is when 2 or more user trying to add record , from different machin. all of them are getting same number by saving ...
Nowadays Synchronization itself is not expensive, at least not enough to worry about. Early on in Java just getting a lock to synchronize on took some time, but that has been optimized in later implementations (Java 1.4 and later I believe). The cost now of Synchronization is the cost when a lock is contested - that is, if Thread-1 tries to ...
I have a function which will call by more then one thread, Which is synchronized by an referance of class ClientSession. So idea behind is that the two client reqiest will process parallaly. The problem is that the wating thread are getting active randomly not the oder it called the function. Ex: Suppose for Client 1 there are 5 threads suppose ...
Longer answer: the whole point of wait/notify is so that one thread can wait for another to do something. And "something" could be almost anything, but it usually involves the exchange of some mutable data. At a minimum, it probably involves one thread asking another, "are you done yet with that thing I asked you to do?" Where "are you done ...
Hi everyone, My doubt relates to the "single object" concept talked about in synchronisation. We know that two threads can conflict only when the "runnable instance" is the same (Please correct me if im wrong, this has been my understanding so far.) , for example: class MyThread implements Runnable{ public static void main(String[] s){ MyThread mt=new MyThread(); Thread a=new Thread(mt); Thread ...
I wanted following code in thread safe manner. So, In order to optimize I synchronized part of the method Instead of entire method. Because part of the code occurs for every 10 mins ( intial un-synchronized will be called every-time) Part of the method which is synchronized gets database updated value, and assigns it to member variable enabled. This part of ...
JVM performance with respect to uncontested locks has become much better over the years, especially so with Java 6. It's now at a point where I would not worry about it unless you're dealing with highly contested locks (at which point you may want to abandon simple synchronized methods and blocks, and use some of the more advanced concurrency capabilities. If ...
Here's a riddle for you all. The Setup: I have function A and function B. I want function A and B to be synchronized within object O. Multiple threads will be accessing object O. When function B is running, no function As will be running and vice-versa. The Problem: Function A should not stop another function A from running. Simply having ...
3)I dont know if this question is related to threads, i thought it might be achieved through threads, If two persons at the same time are trying to buy ticket for the same seat in a Airplane? How to avoid this situation and not let the seat become blocked? This is a problem of DB transactional concurrency control. It could be ...
You can call non-synchronized methods from synchronized ones but you should probably think carefully before doing so. Whilst you are in one of the synchronized methods of an object, any methods which are not synchronized can still be accessed by other threads. For example this code will return Two times 2 is 6 even though the method doubler is synchronized. However ...
Let me explain your questions with examples. #1 Define a class Class X { int val = 0; // getValStatic is not correct. it is shown for explanation only public static int getValStatic() { return val; } public static int getValInstance() { return val; } } #2 instantiate 2 objects X x1 = new X(); x1.val = 2; X x2 = ...
When a Thread1 is executing a synchronized methodA in a class A, Is it possible for another Thread2 to access another non-synchronized methodB in class A? I dont think it's possbile, because the instance is already locked by Thread1 and with that instance only, you can invoke the mehtodB, which is not possbile, as it is already locked. But is my ...
This is from "Effective Java" (p. 283). // Lazy initialization holder class idiom for static fields private static class FieldHolder { static final FieldType field = computeFieldValue( ); } static FieldType getField( ){ return FieldHolder.field; } Joshua Bloch wrote:When the getField method is invoked for the first time, it reads FieldHolder.field for the first time, causing the FieldHolder class to get ...
Guys , I am new to java and stuck in a problem here. I have written a java code to generate unique User ID. I am maintaining a .properties file which stores the numerical suffix of the user ID and the UserIDGenerator class reads the file and do some calculation on the value read from file and Generates a unique ID ...
the current object i.e the object calling the method move is synchronized..... my doubt was that if one thread has an id of 4 and other of 2....and the method is synchronized...both the same id's should be printed together...i mean 4 4 2 2 or 2 2 4 4..how can one thread interrupt another...and get the output 4 2 4 2 ...
Hi Ranchers, I have a few clarifications. Scenario 1> public class A{ public synchronized void MethodA(){ System.out.println("In synchronized MethodA"); //Accessed by Thread (1) } //in the same code below here i have another synchronized method(MethodB) public synchronized void MethodB(){ System.out.println("In synchronized MethodB"); //Can Thread (2) access this synchronized methodB ? } } ----------------------------------------------------------------------------------------------------------------------------------- Scenario 2> public class B{ public synchronized void ...
Hello Ranchers, I got some doubts on synchronization concept. whenever i red about synchronization they talk about threads that synchronization makes sure that only single thread will execute some block of code. my doubt is if i have this synchronized method in web application public synchronized void counter() { int var=0; var++; } 1.now 2 users (not threads) who are being ...
Hi all, I am having a little trouble with my buffer that uses Thread synchronization. What is meant to happen is that the InputManager inputs a String into the buffer. The buffer is then passed to LineToChar, where it takes the String from the buffer using the take() method and extracts the string into individual letters. These individual letters should then ...
I'm somewhat newbie here in trying to understand synchronization and threads. Here is an example of what I'm doing and want to get some inputs to see if that makes sense. ExecutorService exec = .....; for (i=0;i<1000;i++) { exec.execute(new TestThreads(i, var1, var2, var3)); } private class TestThreads implement Runnable { private int j; private String sVar1; private String sVar2; private String ...
Hi, Starting up this thread to get a few answers to some impending questions regarding threads. The questions are more inclined towards understanding the "issues" around multi-threading. 1. Synchronization (Thread interference) - This issue as explained at "The Java Tutorials" occurs when two thread have a reference to the same object and invoke the same method. class Counter { private int ...
Hi Satyajit, If you want to synchronize all the methods in your class, you will have to use the keyword synchronized on every method. Carefully decide whether it's necessary to synchronize a method though. Some don't need it, and synchronizing them will add an unnecessary performance penalty. You can also synchronize your code by making your fields volatile. This however, will ...
Hi, when i was playing with synchronization I came across this issue. I Created 2 threads in a class and then in the run method where I start my thread, I created an object whose 2 methods are synchronized and called each method from other method. When I was going through "Head First Java 2nd edition" in page 511(Topic object synchronization) ...
I am writing a class to retrieve a userid/password object. I want to store this value as a static variable so that its retreived only once. I am confused if synchronization is needed or will it not matter since the same value would be returned regarding of any thread accessing it. This is my class below. Is there any purpose achieved ...
Hi guys, I have service which accepts transfer objects (from an online stream) as parameter and write them into an ascii file. The current implementation works like that the service writes incoming objects immedatelly into a temporary file, and there is a backround thread which fires every 5 minutes, and takes care of publishing the temporary file. Publishing means renaming the ...
When a thread exits a monitor for a particular object and when a thread exits via object.t.join()? The difference between them is like when a thread finishes the function in which it was using that particular object, it exits out of it? Is this statement true? or it exits out when object.t.join is used. Because in definition of synchronization, its written ...
For a school project, I am making a maze generating GUI, and also several different "solving mice" based on various solving algorithms. Each mouse gets its own thread. I know a very small amount about thread management in C/C++ (semaphores, mutexes, etc), but these solutions are all geared toward protecting shared access to variables, which isn't exactly what I'm looking for ...
Hi, Is it safe/legal to synchronize only for write operations, but not on reads, assuming data is stored in an array ( or non thread safe collection )? Also asume there are many getter threads and many setter threads, and that the data stored will be Objects and not primitives. I am particular concerned about corrupt data, where thread 1 writes ...
hello friends class MyThread extends Thread { public synchronized void fname() { for(int i=0;i<5;i++) { System.out.println("started........"+i); try { Thread.sleep(200); } catch(Exception e) { System.out.println("exception..."+e); } } } public void run() { fname(); } public static void main(String[] ar) { MyThread m1=new MyThread(); MyThread m2=new MyThread(); m1.start(); m2.start(); } } i am not understanding the output of the above program as i ...
Hi, I'm continuing to do my self-test on SCJP and I can't understand Thread Synchronization things. Can anyone tell help me why the answer is C and E ? 3. class Chicks { 4. synchronized void yack(long id) { 5. for(int x = 1; x < 3; x++) { 6. System.out.print(id + " "); 7. Thread.yield(); 8. } 9. } 10. ...
We have multiple locations where files get uploaded. For eg., 1_minute, 30_minutes, 1_hour are folder names. I have a file parser ready that reads and parse the files only for 1_minute folder. Now, it is possible to use the same code to parse files for other folders too. Now, I can not start using the same function to parse files from ...
Hi all, Please clear my query. suppose i have one class which contain two methods a() and b() from which a() is static synchronized and b() is non static , synchronized. Now my one thread is trying to access both the methods at same time. how the code will behave??? Thanks in advance.
Hi, i am new to java programming and i need help. actually i am building the Global positioning system application. so whenever it retrieves the location values it uses gprs class to send it to some URL OK. so that gprs class can be used by other application at same time to send other data by some other application. what i ...
Hi everyone, i have created one application in java, in which i have used synchronized block. In synchronized block i have written some statements. so my question is ,when i keep some statements in synchronized block then execution of these statement would be atomic respective to all application threads in Operating system? or the execution of these statement would be atomic ...