Reentrancy of subclass overriding superclass - java.util.concurrent

I was reading book "Java concurrency in practice", the 2.3.2 Reentrancy. It says "because the doSomething methods in Widget and LoggingWidget are both synchronized, each tries to acquire the lock on the Widget before proceeding". I wonder why they all try to acquire the lock on the Widget, but not on the LoggingWidget.
public class Widget{
public synchronized void doSomething(){
...
}
}
public class LoggingWidget extends Widget{
public synchronized void doSomething(){
System.out.println("calling doSomething");
super.doSomething();
}
}

Related

How to enforce default behavior in a virtual function

For example, say I have a basic data object class as below.
class DataObject {
protected:
bool data_changed;
virtual void save() {}
virtual void load() {}
public:
virtual void idle() {
if (data_changed) {
save();
data_changed = false;
}
}
};
The idea is that "idle" is called periodically from some main looping thread and performs non-critical updates.
Now I want derived classes to be able to have their own idle functions. But I don't want to lose the default behavior.
One solution is to say "remember to call DataObject::idle() from overridden idle() functions".
Like this:
class ChildData : public DataObject {
public:
virtual void idle() override {
//do something
DataObject::idle(); //remember to call parent idle!
}
};
But this is very dangerous as people can just forget.
Is there a way to enforce this somehow? Or make it automatic, like a virtual destructor?
(My current "workaround" is to have 2 functions, one the parent_idle that does the important stuff, and then one overridable child_idle that derived functions can override. But this is a bit messy, and also you have to make a whole new set of functions again if you want some child function to enforce its own default...)
Maybe you could write it:
...
void idle_start() { // not virtual, main looping thread calls this
idle();
if (data_changed) {
save();
data_changed = false;
}
}
virtual void idle() { } // virtual, noop by default
...
That depends if you want to have your derived behavior before the mandatory base behavior.

QThreadPool calls pure virtual function of parent class QRunnable

During runtime I get the error message: "pure vitual function called".
QThreadpool seems to call the pure virtual void run() of the parent class QRunnable, instead off void run() in the derived class Bm.
Strangely enough the if I ry to call the function manually with b_1.run();, there is no problem during runtime.
Here is my class implentation:
class Bm : public QRunnable
{
public:
void run()
{
test();
}
private:
void test();
};
Here is my main function where the error happens.
int main()
{
QThreadPool pool;
pool.setMaxThreadCount(1);
BM b_1;
pool.start(&b_1);
return 0;
}
My Question: Why doesnt Qthreadpool use Bm::run() over QRunnble::run()?
The thread objects gets deleted when going out of the main() function scope even before the QThreadPool calls IRunnable::run(). Using QThreadPool::waitForDone() before returning will assure the thread being executed.

Opaque Pointer (pimpl) and signals and slots

I am getting more and more into the Pimpl idiom (private opaque pointer to real class implementation). But I still have an issue which bothers me.
How does this idiom\design pattern deal with signals in the public class (like boost or qt signals)?
class my_class : public QObject
{
Q_OBJECT
public:
void monitorstuff();
signal:
void needupdate();
private:
class impl; unique_ptr<impl> pimpl; // opaque type here
};
class my_class::impl {
void reallymonitorstuff();
};
my_class::impl::reallymonitorstuff()
{
...
//update required here
...
}
void my_class::monitorstuff()
{
pimpl->reallymonitorstuff();
}
Do I replicate all signals in the pimpl, connect with signals of the outer class? A bit annoying to have twice as much signals as what is publicly available, also annoying when I need to swap instances.
Do I pass the public instance as parameter to the private instance which calls directly the public signals
Another design mechanism in conjuction I didn't heard of?
In general, I don't really see the problem. The public class should forward all calls to the impl including calls to connect a slot. The impl contains the signal, not the public class. E.g here using Boost.Signals2:
#include <memory>
#include <boost/signals2.hpp>
#include <iostream>
using signal_type = boost::signals2::signal<void()>;
using slot_type = signal_type::slot_type;
class my_class {
public:
my_class();
void monitorstuff();
void connect(const slot_type& slot);
private:
struct impl; std::unique_ptr<impl> pimpl;
};
struct my_class::impl {
signal_type signal;
void reallymonitorstuff();
void connect(const slot_type& slot){ signal.connect(slot); }
};
void
my_class::impl::reallymonitorstuff() {
//...
signal();
//...
}
void my_class::monitorstuff() {
pimpl->reallymonitorstuff();
}
void my_class::connect(const slot_type& slot) {
pimpl->connect(slot);
}
my_class::my_class() : pimpl(std::make_unique<my_class::impl>()){}
int main() {
my_class mc;
auto slot = []{ std::cout << "Notified!\n"; };
mc.connect(slot);
mc.monitorstuff();
}
Live demo.
I wonder if your problem is more specific to Qt.
Do I replicate all signals in the pimpl, connect with signals of the outer class? A bit annoying to have twice as much signals as what is publicly available, also annoying when I need to swap instances.
No, you don't need to do that.
Do I pass the public instance as parameter to the private instance which calls directly the public signals
That is not necessary either.
Another design mechanism in conjuction I didn't heard of?
That is not necessary either.
Assuming my_class::monitorstuff is supposed raise a signal, I think all you need is:
void my_class::monitorstuff()
{
pimpl->reallymonitorstuff();
emit <<Details of signal>>;
}
pimpl does not need to be concerned with signals or slots.

C++ on singleton

I've a singleton class and I'm sure that the first call of the singleton is done by only one thread. I've implemented singleton with lazy initialization.
class MySingleton : private boost::noncopyable {
public:
/** singleton access. */
static MySingleton & instance()
{
static MySingleton myInstance;
return myInstance;
}
void f1();
void f2();
void f3();
void f4();
private:
MySingleton();
};
Now I've another factory class that is responsable to create all singletons in a single thread enviorment.
The singleton can be used from multiple threads and methods are protected from mutex.
First question
Is this approach accetable?
Second question
I've a complex class that must be thread safe. This class has to be a singleton. How can that a calling of different methods of the class is thread safe. For example.
{
MySingletonLock lock;
// Other thread must wait here.
MySingleton::instance().f1();
MySingleton::instance().f3();
}
How can I get this?
The answer to your second question:
class MyProtectedSingleton: public MySingleton
{
public:
void f1()
{
MySingletonLock lock;
// Other thread must wait here.
MySingleton::instance().f1();
}
void f2()
{
MySingletonLock lock;
// Other thread must wait here.
MySingleton::instance().f2();
}
};
Call f1, f2, etc through wrappers in MyProtectedSingleton.

How to access class members from a method?

I want to access the engine from inside my eventReceiver object. They are fellow members of the game class, but how do I reach it?
// game.h
class game
{
public:
game();
3dEngine* engine;
eventReceiver* receiver;
};
// eventReceiver.h
class eventReceiver
{
public:
eventReceiver () {}
virtual bool OnEvent (const SEvent& event)
{
...
case QUIT_BUTTON_PRESSED:
>>> engine->quit(); // how to access engine from here??
return true;
...
}
};
Should I use 'this' ? I don't understand why receiver can't see the engine.
Implement the class as a Singleton and write a getter for the engine property. Accessing code could then look like:
game::getInstance()->getEngine()->quit();
I would recommend you though, that you create a quite() method in the game class itself hiding implementation details and allowing you to handle overall application shutdown and not just of the 3dEngine:
game::getInstance()->quit();
If you dont want to implement the game class as singleton you could also pass a reference/pointer of a game object to the constructor of your event handler:
class CloseButtonHandler : public eventHandler {
game& game;
public:
CloseButtonHandler(game& game) : game(game) {
}
virtual bool OnEvent(const SEvent& event){
...
game.getEngine()->quit();
}
}
The eventReceiver shouldn't know anything about the engine. That's a bad design. There are a few solutions. One reasonable solution is to derive game from eventReceiver since game can clearly receive events. You can then implement the game-specific OnEvent handler in game itself. From there you can call engine->quit.
I don't know how elegant this design is, but it works.
I just separated the receiver from the game class and gave its constructor a pointer to the instance of myGame. (Thanks to Paranaix)
class eventReceiver {
public:
eventReceiver (game* gameInstance) : gamei(gameInstance)
virtual bool OnEvent (...)
{...
case QUIT_BUTTON_PRESSED:
gamei.engine->quitGame();
...}
private:
game* gamei;
}
int main() {
game myGame;
eventReceiver receiver (&myGame);
}