У меня есть многопоточный класс A, который обращается к следующему insert()
методу другого класса B (A имеет только один экземпляр B).
Вместо того, чтобы синхронизировать весь метод, есть ли лучшие способы синхронизации следующего метода? (чтобы уменьшить накладные расходы на синхронизацию)
private void insert(byte[] shardKey, byte[] queueKey,
byte[] value, PipelineMessageType msgType) {
PipelineMessage pipelineMessage = new PipelineMessage(queueKey,
value, msgType);
LinkedBlockingQueue<PipelineMessage> queue;
JedisShardInfo shardInfo = shardedJedis.getShardInfo(shardKey); // shardedJedis is an instance variable of this class
String mapKey = shardInfo.getHost() + shardInfo.getPort();
queue = shardQueue.get(mapKey); // shardQueue is an instance variable of this class
boolean insertSuccessful = queue.offer(pipelineMessage);
if(!insertSuccessful) {
// perform the pipeline sync - flush the queue
// use another thread for this
// (processing of queue entries is given to another thread here)
// queue would be empty now. Insert (k,v)
queue.offer(pipelineMessage);
}
}
Я пытался синхронизировать только фрагмент, который обращается к переменным экземпляра, но может быть сценарий, когда 2 потока пытаются вставить в полную очередь и войти в блок if
. Тогда 2 потока могут обработать записи в очереди, чего я не хочу.
Любые предложения приветствуются. Заранее спасибо.