when synchronized(xxx.class), where is the markword? - object

I know that synchronized will used markword at object head, to mark the lock status, but when I use synchronized(xxx.class), Which markword am I using?
public void foo() {
synchronized (Object.class) {
System.out.println("object class");
}
}

Related

Can you access a Hazelcast Queue from within an ItemListener?

I have a use case where I have a set of items, DiagnosticRuns, that are submitted to my cluster. I want to process them serially (to avoid conflicts). I am trying to use a Hazelcast Queue protected by a Lock to make sure the items are processed one at a time. Hazelcast is running in embedded mode in my cluster. If I register an ItemListener with the Queue, is it safe to call take() on the Queue from within the itemAdded() method? For example:
#Component
public class DistributedQueueListener
{
public static final String DIAGNOSTICS_RUN_QUEUE_NAME = "diagnosticRun";
#Autowired
private HazelcastInstance hazelcast;
#Autowired
private ProductVersioningService productVersioningService;
private IQueue<DiagnosticRun> diagnosticRunQueue;
private ILock diagnosticRunLock;
private String diagnosticRunListenerId;
#PostConstruct
public void init()
{
diagnosticRunQueue = hazelcast.getQueue(DIAGNOSTICS_RUN_QUEUE_NAME);
diagnosticRunLock = hazelcast.getLock("diagnosticRunLock");
diagnosticRunListenerId = diagnosticRunQueue.addItemListener(new DiagnosticRunListener(), false);
}
#PreDestroy
public void stop()
{
diagnosticRunQueue.removeItemListener(diagnosticRunListenerId);
}
public class DiagnosticRunListener implements ItemListener<DiagnosticRun>
{
#Override
public void itemAdded(ItemEvent<diagnosticRun> item)
{
diagnosticRunLock.lock(5, TimeUnit.SECONDS);
try
{
DiagnosticRun diagnosticRun = diagnosticRunQueue.poll();
if(diagnosticRun != null)
{
productVersioningService.updateProductDeviceTable(diagnosticRun);
}
}
finally
{
diagnosticRunLock.unlock();
}
}
#Override
public void itemRemoved(ItemEvent<diagnosticRun> item)
{
}
}
}
I'm not sure whether it's threadsafe to call take() on the Queue from that location and thread.
If that is not allowed, I'll have to set up my own long-running loop to poll() the Queue. I'm not sure what's the best way to set up a long-running thread in a Spring Boot application. Assuming the method above does not work, would the below code be threadsafe? Or is there a better way to do this?
#Component
public class DistributedQueueListener
{
public static final String DIAGNOSTIC_RUN_QUEUE_NAME = "diagnosticRun";
#Autowired
private HazelcastInstance hazelcast;
#Autowired
private ProductVersioningService productVersioningService;
private IQueue<diagnosticRun> diagnosticRunQueue;
private ILock diagnosticRunLock;
private ExecutorService executorService;
#PostConstruct
public void init()
{
diagnosticRunQueue = hazelcast.getQueue(DIAGNOSTIC_RUN_QUEUE_NAME);
diagnosticRunLock = hazelcast.getLock("diagnosticRunLock");
executorService = Executors.newFixedThreadPool(1);
executorService.submit(() -> listenToDiagnosticRuns());
}
#PreDestroy
public void stop()
{
executorService.shutdown();
}
private void listenToDiagnosticRuns()
{
while(!executorService.isShutdown())
{
diagnosticRunLock.lock(5, TimeUnit.SECONDS);
try
{
DiagnosticRun diagnosticRun = diagnosticRunQueue.poll(1L, TimeUnit.SECONDS);
productVersioningService.updateProductDeviceTable(diagnosticRun);
}
catch(InterruptedException e)
{
logger.error("Interrupted polling diagnosticRun queue", e);
}
finally
{
diagnosticRunLock.unlock();
}
}
}
}
First I'll qualify that I'm not exactly an expert on which threads these are executed on and when so some may disagree but here're my thoughts on this so anyone please chime in as this looks to be an interesting case. Your first solution mixes the Hazelcast event threading with it's operation threading. In fact you're triggering three operations to be invoked as a result of the single event. If you put some arbitrary latency in your call to updateProcductDeviceTable, you'll see that eventually, it will slow down but resume up again after some time. This will cause your local event queue to pile up while operations are invoked. You could put everything you're doing in a separate thread which you can "wake" up on #itemAdded or if you can afford to have a bit of latency, do what you're doing on your second solution. I would, however, make a couple changes in
listenToDiagnosticsRuns() method:
private void listenToDiagnosticRuns()
{
while(!executorService.isShutdown())
{
if(diagnosticRunQueue.peek() != null)
{
diagnosticRunLock.lock(5, TimeUnit.SECONDS);
try
{
DiagnosticRun diagnosticRun = diagnosticRunQueue.poll(1L, TimeUnit.SECONDS);
if(diagnosticRun != null)
{
productVersioningService.updateProductDeviceTable(diagnosticRun);
}
}
catch(InterruptedException e)
{
logger.error("Interrupted polling diagnosticRun queue", e);
}
finally
{
diagnosticRunLock.unlock();
}
} // peek != null
else
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
//do nothing
}
}
}
}

Implementing JComponent blinking in Java using threads

I am trying to implement a program where I want different Components to blink at different speeds. I am using threads. But its not working.
How can I implement this.
This is the void run function in the class that implements runnable
public void run()
{
try
{
while(true)
{
Thread.sleep(1000);
if(isVisible()==true)
{
setVisible(false);
}
else
{
setVisible(true);
}
repaint();
}
}
catch(InterruptedException e)
{
}
}
}
and this is the class (its in a paint component of the main JPanel)where I call the threads-
{
cars[i]=new Car(color, xLocation, yLocation, speed, type, i, widthController, heightController);
cars[i].setBounds(widthController+(xLocation*50)+10, heightController+(yLocation*50)+10, 30, 30);
add(cars[i]);
threads[i]=new Thread(cars[i]);
threads[i].start();
}
cars is an array of JComponents of which void run is part of.
Thanks
With Swing, all operations that affect visible components should be run on the AWT-EventQueue. This is a dedicated thread for Input/Output operations as well as drawing and component operations. My recommendation is to use a swing timer for your run operation. The repaint call you made will call the paintCompnent method on the AWT-EventQueue. However you're changing the state of visibility on a seperate thread. This means that by the time the repaint call is made, it's possible the state has already changed to the previous value.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
//Rest of code above...
//This will execute the timer every 500 milliseconds
Timer aTimer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent pE) {
aComponent.setVisible(!aComponent.isVisible());
}
});
aTimer.start();
Another option is that on each thread add this call:
//This should be added inside of your thread
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
aComponent.setVisible(!aComponent.isVisible());
}
});
Here's the answer I was alluding to in my comments:
public void run()
{
try
{
while(true)
{
Thread.sleep(1000);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
setVisible(!isVisible());
}
}
});
}
catch(InterruptedException e)
{
}

Setting a label in a thread causes IllegalStateException

I have a thread like:
startButton.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field arg0, int arg1) {
Thread thread = new Thread(){
public void run() {
uploadFile();
}
};
thread.start();
}
//});
});
The uploadFile method contains the line label_up_result.setText(result); which causes an IllegalStateException.
label_up_result is defined like: final LabelField label_up_result=new LabelField("", LabelField.FIELD_LEFT);
What can be the problem ? How can I fix it ?
The problem is probably that you are trying to update the UI from a worker thread. There are two approaches. You can synchronize on the event lock:
synchronized(UiApplication.getUiApplication().getEventLock())) {
label_up_result.setText(result);
}
or you can create a Runnable to execute on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
label_up_result.setText(result);
}
});
I don't know about blackberry, but usually you need to perform the ui-actions in the ui-thread. SwingUtilities.invokeLater provides that functionality in JavaSE, http://www.java2s.com/Code/Java/Swing-JFC/Swinginvokelater.htm

C# - set empty delegate for event

public event EventHandler MyButtonClick = delegate { };
The construction above allows to not check if there is any subscriber:
public virtual void OnMyButtonClick(EventHandler e)
{
this.MyButtonClick(this, e);
}
in stead of
public virtual void OnMyButtonClick(EventHandler e)
{
if (MyButtonClick!=null)
this.MyButtonClick(this, e);
}
But is it really a good idea? Is this the only benefit: to not check if any subscriber exists?
UPDATE: Here is example
namespace ConsoleApplication2
{
public class TestClass
{
public event EventHandler MyButtonClick;
//= delegate { };
public void OnButtonClick(EventArgs e)
{
MyButtonClick(this, e);
}
}
class Program
{
static void Main(string[] args)
{
var testClass = new TestClass();
//it throws an exception
testClass.OnButtonClick(new EventArgs());
// if you add an handler it will call it
testClass.MyButtonClick += myCustomHandler;
testClass.OnButtonClick(new EventArgs()); // myCustomHandler has been invoiked
}
private static void myCustomHandler(object sender, EventArgs e)
{
Console.WriteLine("myCustomHandler has been invoiked");
}
}
}
Well, the code you've given here:
public virtual void OnMyButtonClick(EventHandler e)
{
if (MyButtonClick!=null)
this.MyButtonClick(this, e);
}
isn't thread-safe. If the final subscription is removed after the nullity check but before the invocation, you could end up with a NullReferenceException (depending on whether the "raising" thread sees the change).
So you can change it to this instead:
public virtual void OnMyButtonClick(EventArgs e)
{
var handler = MyButtonClick;
if (handler != null)
{
handler(this, e);
}
}
... but of course you might forget to do that, and even if you don't, it's cumbersome to do that all over the place, IMO. So yes, while the benefit is "only" to avoid the nullity check, I'd say that's not a bad trade-off in many cases. Anything that makes it harder to make mistakes is a good idea, IMO.
Another alternative is to have an extension method:
public static void SafeInvoke(this EventHandler handler, object sender,
EventArgs e)
{
if (handler != null)
{
handler(sender, e);
}
}
Then change your calling code to:
public virtual void OnMyButtonClick(EventArgs e)
{
MyButtonClick.SafeInvoke(this, e);
}
(and use the same code for other events). You'd probably want a generic form for EventHandler<T> as well.
you don't need to do that. If the client that uses you class won't add an handler (subscriber) for MyButtonClick event the code won't throw an exception.
That is how events works (and delegates as there are the same thing) otherwise you would be forced to add an handler to all the events of a class (assuming there are any)
so you can do the below:
public virtual void OnMyButtonClick(EventArgs e)
{
MyButtonClick(this, e);
}
have a look at the example below:
public class TestClass
{
public event EventHandler MyButtonClick = delegate { };
public void ButtonClick(EventArgs e)
{
MyButtonClick(this,e);
}
}
class Program
{
static void Main(string[] args)
{
var testClass=new TestClass();
testClass.ButtonClick(new EventArgs());
// if you add an handler it will call it
testClass.MyButtonClick += myCustomHandler;
testClass.ButtonClick(new EventArgs()); // myCustomHandler has been invoiked
}
private static void myCustomHandler(object sender, EventArgs e)
{
Console.WriteLine("myCustomHandler has been invoiked");
}
}

Obvious deadlock - How do i fix this appropriately

class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread((ThreadStart)DLockSample.FunctionA);
Thread therad2 = new Thread((ThreadStart)DLockSample.FunctionB);
thread1.Start();
therad2.Start();
}
}
public class DLockSample
{
static object object1 = new object();
static object object2 = new object();
public static void FunctionA()
{
lock (object1)
{
Thread.Sleep(1000);
lock (object2)
{
Thread.Sleep(1000);
Console.WriteLine("heart beat - object2");
}
}
}
public static void FunctionB()
{
lock (object2)
{
lock (object1)
{
Thread.Sleep(1000);
Console.WriteLine("heart beat - object1");
}
}
} }
Always enter the locks in the same order in all threads. See also hierarchy of critical sections I.e. FunctionB needs to be:
public static void FunctionB()
{
lock (object1)
{
lock (object2)
...
That's a pretty abstact problem to fix. Just a few tips:
Always lock on objects in the same order
If it's impossible to lock in the same order, use object's fields to preserve the order (for example, if A.Id > B.Id then always lock on A before B).

Resources