问题
What happens to my static variables when app-engine spins new instances? More specifically I am using a Task Queue that can have 40 instances/thread. Within the Servlet in question, I am using a singleton, as in
public class WorkerThread extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
..
MySingleton single = MySingleton.getInstance();
..
}
...
}
Here is how the singleton is created
public class MySingleton {
public static I MySingleton getInstance() {
return MySingletonHolder.INSTANCE;
}
private static class MySingletonHolder {
public static final MySingleton INSTANCE = new MySingleton();
}
private MySingleton() {
}
..
}
I have the following questions:
Since this is a Task Queue, do I have to worry about App-Engine starting new instances to scale with high demands?
Does it matter if the singleton is an inner class of the WorkerThread class or another class that the WorkerThread class is accessing?
Are Task Queues instance independent? A believe they are but am not sure.
I hope the question is clear. I want there to be only one instance of my singleton across all instances. Please ask for clarification if the question is not clear.
UPDATE
Following is my exact use case
public class SingletonProductIndexWriter {
private static final Logger LOG = Logger.getLogger(SingletonProductIndexWriter.class.getName());
public static IndexWriter getSingleIndexWriter() {
return IndexWriterHolder.INDEX_WRITER;
}
private static class IndexWriterHolder {
static PorterAnalyzer analyzer = new PorterAnalyzer();
static GaeDirectory index = new GaeDirectory(LuceneWorker.PRODUCTS);// create product index
static IndexWriterConfig config = GaeLuceneUtil.getIndexWriterConfig(LuceneWorker.LUCENE_VERSION, analyzer);
public static final IndexWriter INDEX_WRITER = getIndexWriter();
private static IndexWriter getIndexWriter() {
try {
LOG.info("Create single index writer for workers");
return new IndexWriter(index, config);
}catch(IOException e){
return null;
}
}
}
}
called as
IndexWriter writer = SingletonProductIndexWriter.getSingleIndexWriter();
For pertinent details see Stack Overflow thread: Worker threads cause Lucene LockObtainFailedException
回答1:
Push and Pull queues are both processed by standard instances (you can target a module/frontend/backend in your queue.xml). Instances will scale up to meet the needs of both your normal traffic as well as your queues.
Singletons (in the classic sense portrayed here) are only unique to the classloader they are loaded by - they definitely are not unique across instances of your application on appengine - no state will be shared. Using this pattern you will have one singleton per appengine instance.
If you need to share state, you will need to use the datastore/cloud sql/something.
来源:https://stackoverflow.com/questions/30585365/behavior-of-singletons-in-task-queues-on-app-engine