What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?
|
I was reading this article about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author ... |
I have a class which looks something like this:
public class Test {
private static final Object someObject = new Object();
public void doSomething()
{
synchronized (someObject) {
System.out.println(someObject.toString());
}
}
}
Can I consider the object ... |
Checkstyle reports this code as "The double-checked locking idiom is broken", but I don't think that my code actually is affected by the problems with double-checked locking.
The code is supposed to ... |
The Java Tutorials say: "it is not possible for two invocations of synchronized methods on the same object to interleave."
What does this mean for a static method? Since a static ... |
Here's the scenario: I have a multi threaded java web application which is running inside a servlet container.
The application is deployed multiple times inside the servlet container. There are multiple servlet ... |
class A {
public synchronized void myOneMethod() {
// ...
}
}
class B extends A {
...
|
|
I was wondering if
synchronize (lock) {
...
}
Where lock is an instance of java.util.concurrent.locks.Lock, treats lock like any other object or as the try-finally idiom i.e. ... |
Just curious to know (in as much detail as possible), why is it a bad practice to
modify the object while using it as a lock.
//Assuming the lockObject is globally available
...
|
I have a process A that contains a table in memory with a set of records (recordA, recordB, etc...)
Now, this process can launch many threads that affect the records, and sometimes ... |
Since thread execution happens in a pool, and is not guaranteed to queue in any particular order, then why would you ever create threads without the protection of synchronization and locks? ... |
I just need a confirmation that i have understood the concept of locks in synchronized blocks correctly.
First I will tell what I have understood.
Acquiring a lock of an object means that ... |
I've read all about how double checked locking fixes never work and I don't like lazy initialization, but it would be nice to be able to fix legacy code and such ... |
What does this java code means? Will it gain locks on all objects of 'MyClass'
synchronized(MyClass.class) {
//is all objects of MyClass are thread-safe now ??
}
And how the above code ... |
I commented earlier on this question ("Why java.lang.Object is not abstract?") stating that I'd heard that using a byte[0] as a lock was slightly more efficient than using an java.lang.Object. ... |
I'm creating a static class which is going to hold some vectors with info.
I have to make it synchronized so that the class will be locked if someone is editing or ... |
First question here: it is a very short yet fundamental thing in Java that I don't know...
In the following case, is the run() method somehow executed with the lock that somemethod() ... |
In Java, do ReentrantLock.lock() and ReetrantLock.unlock() use the same locking mechanism as synchronized()?
My guess is "No," but I'm hoping to be wrong.
Example:
Imagine that Thread 1 and Thread 2 both have access ... |
If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on ... |
I have a confusion about object lock.
The below class having 4 methods, the method addB() is synchronized.
In my scienario, there are 4 threads. When a thread-2 access the addB() method ... |
I know when you want to lock method to be executed by only one thread you declare it with synchronized keyword.
What about classes, how to provide a lock on an ... |
I often find myself with code like
private static final MyType sharedResource = MyType();
private static final Object lock = new Object();
...
synchronized(lock)
{
//do stuff with sharedResource
}
Is this really neccessary or ... |
I know the difference between synchronized method and synchronized block but I am not sure about the synchronized block part.
Assuming I have this code
class Test {
private int x=0;
...
|
I will try to explain the quetion by taking following 3 cases.
CASE I:
I was using shared lock for synchronization using something like this:
...
|
I have main thread which calls another thread. timeout period of second one is 15 seconds. Current implementaion is main thread check second one for every 2 seconds. What I need ... |
I am currently resolving a performance degradation issue due to heavy lock contention. I am considering "Lock splitting" to resolve this issue.
The skeletal usage pattern is ::
CURRENT USAGE ::
public class HelloWorld{
...
|
What is the difference between synchronized and lock?
Thx.
|
suppose we have multi processor machine and multi threaded application. If two threads have access to a synchronized method and they got executed at the same time which thread will gets ... |
java.util.concurrent api provides a class called as Lock, which would basically serializes the conntrol in order to access the critical resource. It gives method such as park() and unpark().
We ...
|
Consider code sniper below:
package sync;
public class LockQuestion {
private String mutable;
public synchronized void setMutable(String mutable) {
this.mutable ...
|
I have a collection which guaranteed to be visible across threads. However that doesn't guarantee visibility of states of items which are stored in this collection(eg. if I have collection of ... |
I have two threads thread1(printing numbers) & thread2(printing alphabets).
My goal is to have the following output via syncronization:
1
a
2
b
3
c
... |
I am wondering how exactly "synchronized" works in java.
Let's say I model a board-game that consists of a number of fields. I implement the fields as a class (Field) and the ... |
I'm modelling a game where multiple players (threads) move at the same time.
The information of where a player is located at the moment is stored twice: the player has a variable ... |
I met some locking issue in my application, in which contains several classes like below:
public interface AppClient {
void hello();
}
public class Client implements AppClient {
...
|
I've written the following code:
public class ClassAndObjectLock {
public static void main(String[] args) {
new Thread(new EvenThread()).start();
new Thread(new OddThread()).start();
}
}
class EvenThread implements Runnable {
public void run() {
...
|
I have written the following code:
public class ClassLevelSynchronization {
public static void main(String[] args) {
new Thread(new AddThread()).start();
...
|
If a running thread access a specific object thus it also held lock on the field members of that specific object?
|
It's stated that fields assignment is always atomic except for fields of long or double.
But, when I read an explaination of why double-check locking is broken, it's said that the problem ... |
I have a Java class that is used in a multithreading application. Concurrent access is very likely. Multiple concurrent read operations should not block so I'm using a ReadWrite lock.
class Example ...
|
I have been messing around with synchronization in Java and it has yet to work for me.
I have two Runnable objects that are used to create separate threads, and each object ... |
When we say we lock on an object using the synchronized keyword, does it mean we are acquiring a lock on the whole object or only at the code that exists ... |
Greetings, fellow SO users.
I am currently in the process of writing a class of which instances will serve as a cache of JavaBean PropertyDescriptors. You can call a method getPropertyDescriptor(Class clazz, ... |
I read that every object in java have a lock.That will be acquired by the thread when a synchronized method is called with that object.And at the same time thread can ... |
I am learning synchronized blocks with locks.I want to know the difference between this lock and some third party lock that provided in the program.
public class NewThread extends Thread {
StringBuffer sb;
NewThread(StringBuffer ...
|
Is this a fair analogy to make? I think I can think of some scenarios where you have to use locks, but I'm not sure if they're necessary.
For instance, here ... |
I need to synchrozize my accesses to the hashmap.
Here are my options
- I know I can use Synchronize keyword. this is one option. Can I use the map itself ? ...
|
Is something like this possible with synchronized, or do I need to use java.util...Lock:
public void outer() {
synchronized(lock) {
inner();
}
}
public void inner() {
thing1();
release(lock) {
result = ...
|
I am working with an object that serves as a database in my application. However, I need to have redundant copies of this database. So, on init, I create multiple instances ... |
If I want to ensure exclusive access to an object in Java, I can write something like this:
...
Zoo zoo = findZoo();
synchronized(zoo)
{
zoo.feedAllTheAnimals();
...
}
Is there a ... |
Take this code:
public class MyClass {
private final Object _lock = new Object();
private final MyMutableClass _mutableObject = new MyMutableClass()
public void ...
|
The keyword synchronize does not appear in the source code of ArrayBlockingQueue. Does that mean I am free to use its intrinsic lock for "my own purposes"? Or could this change ... |
To start off I have two processes that are running concurrently that support each other. One process reads a simple flatfile which contains snapshots of data separated by timestamps. This application ... |
I have an object that is shared in read/write between threads.
Assuming that the synchonization is correctely done, if A is the object previously initialized when no threads are running, when they ... |
I have a web application and I am using Oracle database and I have a method basically like this:
public static void saveSomethingImportantToDataBase(Object theObjectIwantToSave) {
if (!methodThatChecksThatObjectAlreadyExists) ...
|
hmmm i'm trying to justify the use of synhronized statement vs Java Concurrent API for my SCJD..
so far the only reason I can give is it is more simple, easier to ... |
I have a piece of code that can be executed by multiple threads that needs to perform an I/O-bound operation in order to initialize a shared resource that is stored in ... |
If a class A is having a public static method which is tagged by 'synchronized' keyword, then Is there a possibility to have class level lock?
When there is a lock in ... |
I have a store of data objects and I wish to synchronize modifications that are related to one particular object at a time.
class DataStore {
Map<ID, DataObject> objects ...
|
Are there any synchronizing/reference issues with this code?
(Assume that myStrings is already instantiated.)
MySynch.java:
public class MySynch
{
public static String[] myStrings = new String[10];
public static void ...
|
I have one thread, that is receiving tcp packets and add each line to a buffer that is an ArrayList<String>.
The other thread should periodically check if new data is available, ... |
I have a BIG question for you. How to synchronize two different methods from the same class in order to lock on the same object? Here is an example:
public class MyClass ...
|
I'm wondering if there's a way in Java to synchronize using two lock objects.
I don't mean locking on either object, I mean locking only on both.
e.g. if I have 4 ... |
What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the ... |
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns but what happens when a static synchronized ... |
the code listed below is my exercise. I try to test how synchronize work. but my result shocked me, like this: 3 which = 1shareVal=3inside show, i = 0 4 which = 2shareVal=4inside show, i = 0 wake up which = 2shareVal=4inside show, i = 1 wake up which = 1shareVal=4inside show, i = 1 wake up which = 2shareVal=4inside show, ... |
Is any one aware of Synchoronizing all methods in class. I have a third party class.whose methods are not synchronized. but when i am using that class in my application.I used extensively.now we have a case where there is a chance of dead lock.because the same class is accessed from two different threads. one solution to this is subclass the third ... |
Dear all, have anyone of you tried to run the ATM example from Henry Wong's Java Threads 2nd edition? You can find the example on page 62. It uses class BusyFlag to create a session scope lock (locking the session between login and logoff to the ATM) I tried to run this example and put myself (Darya) and my wife (Mehrak) ... |
Hello, I keep reading about how synchronized code incurrs performance penalty for acquiring and releasing locks even when they are uncontested. However after making a test jsp page that compares a 10 million synchronized calls to an empty method to 10 million calls without any synchronization, I found that the penalty varied between 150ms and 250ms. And this is for acquiring ... |
Object someObject = ...; synchronized public void test() { someObject.doSomething(); } Let's say class A and class B both have methods similar to above, they both modify the same Object but do so via synchronized methods. So Class A and Class B have the synchronized methods and both modify Object C. Is it possible then for Class A and Class B ... |
Hello, could someone help me please.. With synchronization keyword what actually gets locked? For example, If I have following two classes: class ownCounter: class ownCounter{ int counter; String name; // set parameter n to variable name, so one can follow print-outs ownCounter(String n){ name=n; } public void print(){ for(int i=0;i<10;i++){ try{ counter++; System.out.println(name+" "+counter); } catch(Exception e){} } } public synchronized ... |
hi ! I have this try-catch block in a servlet. Whenever a client makes a call to this servlet, the log file gets updated with a new entry. Now there can be more than one client making a call at the same time. I want to make sure that, when the log file is getting updated (during first call to the ... |
Hi all. I was reading JDK 1.4 Tutorial book and I have a question about NIO chapter. the following code creates a simple database : public SimpleDatabase(String filename) throws IOException { File file = new File(filename); boolean exists = file.exists(); raf = new RandomAccessFile(file, "rw"); fc = raf.getChannel(); if (!exists) { byte b[] = new byte[SLOTSIZE]; for (int i = 0; ... |
|
I came across these statements => The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time. => When a synchronized non static method is called a lock is obtained on the object. When a synchronized static method is called a ... |
Hi All I tried to synchronised one block by using synchronized ( this ){ } i have one scheduler to invoke this block each 2 secs, if it is locked scheduler shouldn't take control on method, but am not acquiring lock on that method. is there any other way to lock method / block of code. Note : i tried with ... |
Dear All, I have a code fragment that is not working. I posted it before on this same forum, but now the problem is better defined, and the code is changed a bit. I am having event dispatch thread trouble again, the thing is that when i run the program by clicking the 1-step button, it executes perfectly, but when i ... |
|
I have a synchronized reset method whose job is to reset every variable i am using in that class.. its a synchronized method so when i am doing the reset stuff, no other method in that class can update that variable. But someone told me i need to also put lock inside the reset method and check for the lock everywhere ... |
|
|
There's no way to achieve synchronization without an object. Synchronizing always obtains an object's lock. In the case of static synced methods, the object whose lock we obtain is the Class object for that class. As far as syncing goes, it's just another object. There is no such thing as "code level synchronization" vs. any other kind. All syncing occurs in ... |
|
Synchronized exclusively lock the runnable object. you can do without synchronized key word as follow. public void f(){ Lock lk = new ReentrantLock(); lk.lock() try{ your code............. }finally { lk.unlock(); } } whick is same as public synchronized void f(){ your code..... } I think above code is very usefull to understand. |
public void method_a() throws SomeException { synchronized(_lock) { } } public void method_b() throws SomeException { synchronized(_lock) { } } public void method_c() throws SomeException { synchronized(_lock) { } } public void method_d() throws SomeException { synchronized(_lock) { } } } They found the application hang running for a while and using bugseeker they find 2 situations amoung the hangs: 1. ... |
public class AccountDanger implements Runnable { private Account acct = new Account(); public static void main(String args[]){ AccountDanger r = new AccountDanger(); Thread one = new Thread(r); Thread two = new Thread(r); one.setName("A"); two.setName("B"); one.start(); two.start(); } public void run(){ for (int x = 0; x < 5; x++){ makeWithdrawal(10); if(acct.getBalance() < 0){ System.out.println("account is overdrawn!"); } } } private synchronized ... |
static { instance = new InnerClient(); doSomethingThatWillCallClientGetInstanceSeveralTimes(); } } public class Application { new Thread() { AppClient c = Client.getInstance(); c.hello(); }.start(); new Thread() { AppClient c = Client.getInstance(); c.hello(); }.start(); // ... new Thread() { AppClient c = Client.getInstance(); c.hello(); }.start(); } In the doSomethingThatWillCallClientGetInstanceSeveralTimes() method, it will do quite a lot initialization work involving many classes and circularly call ... |
|