Search in sources :

Example 16 with TimeoutException

use of org.apache.kafka.common.errors.TimeoutException in project kafka by apache.

the class BufferPool method allocate.

/**
     * Allocate a buffer of the given size. This method blocks if there is not enough memory and the buffer pool
     * is configured with blocking mode.
     * 
     * @param size The buffer size to allocate in bytes
     * @param maxTimeToBlockMs The maximum time in milliseconds to block for buffer memory to be available
     * @return The buffer
     * @throws InterruptedException If the thread is interrupted while blocked
     * @throws IllegalArgumentException if size is larger than the total memory controlled by the pool (and hence we would block
     *         forever)
     */
public ByteBuffer allocate(int size, long maxTimeToBlockMs) throws InterruptedException {
    if (size > this.totalMemory)
        throw new IllegalArgumentException("Attempt to allocate " + size + " bytes, but there is a hard limit of " + this.totalMemory + " on memory allocations.");
    this.lock.lock();
    try {
        // check if we have a free buffer of the right size pooled
        if (size == poolableSize && !this.free.isEmpty())
            return this.free.pollFirst();
        // now check if the request is immediately satisfiable with the
        // memory on hand or if we need to block
        int freeListSize = freeSize() * this.poolableSize;
        if (this.availableMemory + freeListSize >= size) {
            // we have enough unallocated or pooled memory to immediately
            // satisfy the request
            freeUp(size);
            this.availableMemory -= size;
            lock.unlock();
            return allocateByteBuffer(size);
        } else {
            // we are out of memory and will have to block
            int accumulated = 0;
            ByteBuffer buffer = null;
            Condition moreMemory = this.lock.newCondition();
            long remainingTimeToBlockNs = TimeUnit.MILLISECONDS.toNanos(maxTimeToBlockMs);
            this.waiters.addLast(moreMemory);
            // enough memory to allocate one
            while (accumulated < size) {
                long startWaitNs = time.nanoseconds();
                long timeNs;
                boolean waitingTimeElapsed;
                try {
                    waitingTimeElapsed = !moreMemory.await(remainingTimeToBlockNs, TimeUnit.NANOSECONDS);
                } catch (InterruptedException e) {
                    this.waiters.remove(moreMemory);
                    throw e;
                } finally {
                    long endWaitNs = time.nanoseconds();
                    timeNs = Math.max(0L, endWaitNs - startWaitNs);
                    this.waitTime.record(timeNs, time.milliseconds());
                }
                if (waitingTimeElapsed) {
                    this.waiters.remove(moreMemory);
                    throw new TimeoutException("Failed to allocate memory within the configured max blocking time " + maxTimeToBlockMs + " ms.");
                }
                remainingTimeToBlockNs -= timeNs;
                // otherwise allocate memory
                if (accumulated == 0 && size == this.poolableSize && !this.free.isEmpty()) {
                    // just grab a buffer from the free list
                    buffer = this.free.pollFirst();
                    accumulated = size;
                } else {
                    // we'll need to allocate memory, but we may only get
                    // part of what we need on this iteration
                    freeUp(size - accumulated);
                    int got = (int) Math.min(size - accumulated, this.availableMemory);
                    this.availableMemory -= got;
                    accumulated += got;
                }
            }
            // remove the condition for this thread to let the next thread
            // in line start getting memory
            Condition removed = this.waiters.removeFirst();
            if (removed != moreMemory)
                throw new IllegalStateException("Wrong condition: this shouldn't happen.");
            // over for them
            if (this.availableMemory > 0 || !this.free.isEmpty()) {
                if (!this.waiters.isEmpty())
                    this.waiters.peekFirst().signal();
            }
            // unlock and return the buffer
            lock.unlock();
            if (buffer == null)
                return allocateByteBuffer(size);
            else
                return buffer;
        }
    } finally {
        if (lock.isHeldByCurrentThread())
            lock.unlock();
    }
}
Also used : Condition(java.util.concurrent.locks.Condition) ByteBuffer(java.nio.ByteBuffer) TimeoutException(org.apache.kafka.common.errors.TimeoutException)

Example 17 with TimeoutException

use of org.apache.kafka.common.errors.TimeoutException in project kafka by apache.

the class RecordCollectorTest method shouldThrowStreamsExceptionAfterMaxAttempts.

@SuppressWarnings("unchecked")
@Test(expected = StreamsException.class)
public void shouldThrowStreamsExceptionAfterMaxAttempts() throws Exception {
    RecordCollector collector = new RecordCollectorImpl(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {

        @Override
        public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
            throw new TimeoutException();
        }
    }, "test");
    collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
}
Also used : MockProducer(org.apache.kafka.clients.producer.MockProducer) Callback(org.apache.kafka.clients.producer.Callback) DefaultPartitioner(org.apache.kafka.clients.producer.internals.DefaultPartitioner) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) Future(java.util.concurrent.Future) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Test(org.junit.Test)

Example 18 with TimeoutException

use of org.apache.kafka.common.errors.TimeoutException in project kafka by apache.

the class StoreChangelogReaderTest method shouldThrowStreamsExceptionWhenTimeoutExceptionThrown.

@SuppressWarnings("unchecked")
@Test
public void shouldThrowStreamsExceptionWhenTimeoutExceptionThrown() throws Exception {
    final MockConsumer<byte[], byte[]> consumer = new MockConsumer(OffsetResetStrategy.EARLIEST) {

        @Override
        public Map<String, List<PartitionInfo>> listTopics() {
            throw new TimeoutException("KABOOM!");
        }
    };
    final StoreChangelogReader changelogReader = new StoreChangelogReader(consumer, new MockTime(), 0);
    try {
        changelogReader.validatePartitionExists(topicPartition, "store");
        fail("Should have thrown streams exception");
    } catch (final StreamsException e) {
    // pass
    }
}
Also used : StreamsException(org.apache.kafka.streams.errors.StreamsException) List(java.util.List) MockConsumer(org.apache.kafka.clients.consumer.MockConsumer) MockTime(org.apache.kafka.common.utils.MockTime) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Test(org.junit.Test)

Aggregations

TimeoutException (org.apache.kafka.common.errors.TimeoutException)18 Test (org.junit.Test)8 Callback (org.apache.kafka.clients.producer.Callback)5 StreamsException (org.apache.kafka.streams.errors.StreamsException)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ProducerRecord (org.apache.kafka.clients.producer.ProducerRecord)3 PartitionInfo (org.apache.kafka.common.PartitionInfo)3 MockTime (org.apache.kafka.common.utils.MockTime)3 IOException (java.io.IOException)2 ByteBuffer (java.nio.ByteBuffer)2 List (java.util.List)2 Future (java.util.concurrent.Future)2 MockConsumer (org.apache.kafka.clients.consumer.MockConsumer)2 MockProducer (org.apache.kafka.clients.producer.MockProducer)2 RecordMetadata (org.apache.kafka.clients.producer.RecordMetadata)2 DefaultPartitioner (org.apache.kafka.clients.producer.internals.DefaultPartitioner)2 Cluster (org.apache.kafka.common.Cluster)2 KafkaException (org.apache.kafka.common.KafkaException)2 TopicPartition (org.apache.kafka.common.TopicPartition)2 TopicAuthorizationException (org.apache.kafka.common.errors.TopicAuthorizationException)2